PHP Manual

Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Georg Richter
Damien Seguy
Jakub Vrana
And several others

Edited by

Philip Olson

2007-06-17

Copyright

Copyright © 1997 - 2007 by the PHP Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. A copy of the Open Publication License is distributed with this manual, the latest version is presently available at http://www.opencontent.org/openpub/.

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.

In case you are interested in redistribution or republishing of this document in whole or in part, either modified or unmodified, and you have questions, please contact the copyright holders at doc-license@lists.php.net. Note that this address is mapped to a publicly archived mailing list.

The Chapter 56 section of the documentation is based on an initial contribution by Zend Technologies.


Table of Contents
Preface
Authors and Contributors
I. Getting Started
1. Introduction
2. A simple tutorial
II. Installation and Configuration
3. General Installation Considerations
4. Installation on Unix systems
5. Installation on Mac OS X
6. Installation on Windows systems
7. Installation of PECL extensions
8. Problems?
9. Runtime Configuration
III. Language Reference
10. Basic syntax
11. Types
12. Variables
13. Constants
14. Expressions
15. Operators
16. Control Structures
17. Functions
18. Classes and Objects (PHP 4)
19. Classes and Objects (PHP 5)
20. Exceptions
21. References Explained
IV. Security
22. Introduction
23. General considerations
24. Installed as CGI binary
25. Installed as an Apache module
26. Filesystem Security
27. Database Security
28. Error Reporting
29. Using Register Globals
30. User Submitted Data
31. Magic Quotes
32. Hiding PHP
33. Keeping Current
V. Features
34. HTTP authentication with PHP
35. Cookies
36. Sessions
37. Dealing with XForms
38. Handling file uploads
39. Using remote files
40. Connection handling
41. Persistent Database Connections
42. Safe Mode
43. Using PHP from the command line
VI. Function Reference
I. .NET Functions
II. Apache-specific Functions
III. Alternative PHP Cache
IV. Advanced PHP debugger
V. Array Functions
VI. Aspell functions [deprecated]
VII. BCMath Arbitrary Precision Mathematics Functions
VIII. PHP bytecode Compiler
IX. Bzip2 Compression Functions
X. Calendar Functions
XI. CCVS API Functions [deprecated]
XII. Class/Object Functions
XIII. Classkit Functions
XIV. ClibPDF Functions
XV. COM and .Net (Windows)
XVI. Crack Functions
XVII. Character Type Functions
XVIII. CURL, Client URL Library Functions
XIX. Cybercash Payment Functions
XX. Credit Mutuel CyberMUT functions
XXI. Cyrus IMAP administration Functions
XXII. Date and Time Functions
XXIII. DB++ Functions
XXIV. Database (dbm-style) Abstraction Layer Functions
XXV. dBase Functions
XXVI. DBM Functions [deprecated]
XXVII. dbx Functions
XXVIII. Direct IO Functions
XXIX. Directory Functions
XXX. DOM Functions
XXXI. DOM XML Functions
XXXII. enchant Functions
XXXIII. Error Handling and Logging Functions
XXXIV. Exif Functions
XXXV. Expect Functions
XXXVI. File Alteration Monitor Functions
XXXVII. Forms Data Format Functions
XXXVIII. Fileinfo Functions
XXXIX. filePro Functions
XL. Filesystem Functions
XLI. Filter Functions
XLII. Firebird/InterBase Functions
XLIII. Firebird/Interbase Functions (PDO_FIREBIRD)
XLIV. FriBiDi Functions
XLV. FrontBase Functions
XLVI. FTP Functions
XLVII. Function Handling Functions
XLVIII. GeoIP Functions
XLIX. Gettext Functions
L. GMP Functions
LI. gnupg Functions
LII. Net_Gopher
LIII. Haru PDF Functions
LIV. hash Functions
LV. HTTP
LVI. Hyperwave Functions
LVII. Hyperwave API Functions
LVIII. i18n Functions
LIX. IBM Functions (PDO_IBM)
LX. IBM DB2, Cloudscape and Apache Derby Functions
LXI. ICAP Functions [removed]
LXII. iconv Functions
LXIII. ID3 Functions
LXIV. IIS Administration Functions
LXV. Image Functions
LXVI. Imagick Image Library
LXVII. IMAP, POP3 and NNTP Functions
LXVIII. Informix Functions
LXIX. Informix Functions (PDO_INFORMIX)
LXX. Ingres II Functions
LXXI. IRC Gateway Functions
LXXII. PHP / Java Integration
LXXIII. JSON Functions
LXXIV. KADM5
LXXV. LDAP Functions
LXXVI. libxml Functions
LXXVII. Lotus Notes Functions
LXXVIII. LZF Functions
LXXIX. Mail Functions
LXXX. Mailparse Functions
LXXXI. Mathematical Functions
LXXXII. MaxDB PHP Extension
LXXXIII. MCAL Functions
LXXXIV. Mcrypt Encryption Functions
LXXXV. MCVE (Monetra) Payment Functions
LXXXVI. Memcache Functions
LXXXVII. Mhash Functions
LXXXVIII. Mimetype Functions
LXXXIX. Ming functions for Flash
XC. Miscellaneous Functions
XCI. mnoGoSearch Functions
XCII. Microsoft SQL Server Functions
XCIII. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
XCIV. Mohawk Software Session Handler Functions
XCV. mSQL Functions
XCVI. Multibyte String Functions
XCVII. muscat Functions
XCVIII. MySQL Functions
XCIX. MySQL Functions (PDO_MYSQL)
C. MySQL Improved Extension
CI. Ncurses Terminal Screen Control Functions
CII. Network Functions
CIII. Newt Functions
CIV. NSAPI-specific Functions
CV. Object Aggregation/Composition Functions
CVI. Object property and method call overloading
CVII. Oracle Functions
CVIII. ODBC Functions (Unified)
CIX. ODBC and DB2 Functions (PDO_ODBC)
CX. oggvorbis
CXI. OpenAL Audio Bindings
CXII. OpenSSL Functions
CXIII. Oracle Functions [deprecated]
CXIV. Oracle Functions (PDO_OCI)
CXV. Output Control Functions
CXVI. Ovrimos SQL Functions
CXVII. Paradox File Access
CXVIII. Parsekit Functions
CXIX. Process Control Functions
CXX. Regular Expression Functions (Perl-Compatible)
CXXI. PDF Functions
CXXII. PDO Functions
CXXIII. Phar archive stream and classes
CXXIV. PHP Options&Information
CXXV. POSIX Functions
CXXVI. Regular Expression Functions (POSIX Extended)
CXXVII. PostgreSQL Functions
CXXVIII. PostgreSQL Functions (PDO_PGSQL)
CXXIX. Printer Functions
CXXX. Program Execution Functions
CXXXI. PostScript document creation
CXXXII. Pspell Functions
CXXXIII. qtdom Functions
CXXXIV. Radius
CXXXV. Rar Functions
CXXXVI. GNU Readline
CXXXVII. GNU Recode Functions
CXXXVIII. RPM Header Reading Functions
CXXXIX. runkit Functions
CXL. SAM - Simple Asynchronous Messaging
CXLI. Satellite CORBA client extension [deprecated]
CXLII. SCA Functions
CXLIII. SDO Functions
CXLIV. SDO XML Data Access Service Functions
CXLV. SDO Relational Data Access Service Functions
CXLVI. Semaphore, Shared Memory and IPC Functions
CXLVII. SESAM Database Functions
CXLVIII. PostgreSQL Session Save Handler
CXLIX. Session Handling Functions
CL. Shared Memory Functions
CLI. SimpleXML functions
CLII. SNMP Functions
CLIII. SOAP Functions
CLIV. Socket Functions
CLV. Standard PHP Library (SPL) Functions
CLVI. SQLite Functions
CLVII. SQLite Functions (PDO_SQLITE)
CLVIII. Secure Shell2 Functions
CLIX. Statistics Functions
CLX. Stream Functions
CLXI. String Functions
CLXII. Shockwave Flash Functions
CLXIII. Swish Functions
CLXIV. Sybase Functions
CLXV. TCP Wrappers Functions
CLXVI. Tidy Functions
CLXVII. Tokenizer Functions
CLXVIII. Unicode Functions
CLXIX. URL Functions
CLXX. Variable Handling Functions
CLXXI. Verisign Payflow Pro Functions
CLXXII. vpopmail Functions
CLXXIII. W32api Functions
CLXXIV. WDDX Functions
CLXXV. win32ps Functions
CLXXVI. win32service Functions
CLXXVII. xattr Functions
CLXXVIII. xdiff Functions
CLXXIX. XML Parser Functions
CLXXX. XML-RPC Functions
CLXXXI. XMLReader functions
CLXXXII. XMLWriter Functions
CLXXXIII. XSL functions
CLXXXIV. XSLT Functions
CLXXXV. YAZ Functions
CLXXXVI. YP/NIS Functions
CLXXXVII. Zip File Functions
CLXXXVIII. Zlib Compression Functions
VII. PHP at the Core: A Hacker's Guide to the Zend Engine
44. The PHP 5 build system
45. Extension structure
46. Memory management
47. Working with variables
48. Writing functions
49. Working with classes and objects
50. Working with resources
51. Working with INI settings
52. Working with streams
53. PDO Driver How-To
54. Extension FAQs
55. Zend Engine 2 API reference
56. Zend Engine 1
57. The future: PHP 6 and Zend Engine 3
VIII. FAQ: Frequently Asked Questions
58. General Information
59. Mailing lists
60. Obtaining PHP
61. Database issues
62. Installation FAQ
63. Build Problems
64. Using PHP
65. PHP and HTML
66. PHP and COM
67. PHP and other languages
68. Migrating from PHP 2 to PHP 3
69. Migrating from PHP 3 to PHP 4
70. Migrating from PHP 4 to PHP 5
71. Miscellaneous Questions
IX. Appendices
A. History of PHP and related projects
B. Migrating from PHP 5.1.x to PHP 5.2.x
C. Migrating from PHP 5.0.x to PHP 5.1.x
D. Migrating from PHP 4 to PHP 5
E. Migrating from PHP 3 to PHP 4
F. Migrating from PHP/FI 2 to PHP 3
G. Debugging PHP
H. Configure options
I. php.ini directives
J. List of Supported Timezones
K. Extension Categorization
L. List of Function Aliases
M. List of Reserved Words
N. List of Resource Types
O. List of Supported Protocols/Wrappers
P. List of Available Filters
Q. List of Supported Socket Transports
R. PHP type comparison tables
S. List of Parser Tokens
T. Userland Naming Guide
U. About the manual
V. Open Publication License
W. Function Index

Preface

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.

You can download this manual in several formats at http://www.php.net/download-docs.php. More information about how this manual is developed can be found in the 'About the manual' appendix. If you are interested in the history of PHP, visit the relevant appendix.


Authors and Contributors

We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All the lists provided below are in alphabetical order.


Authors and Editors

The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Hannes Magnusson, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.

The following contributors have done significant work editing the manual: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe and Egon Schmid.


User Note Maintainers

The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Etienne Kneuss, Nuno Lopes, Hannes Magnusson, Bobby Matthis and Philip Olson.

These people have also put a lot of effort into managing user notes: Daniel Beckham, 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, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Maciek Sokolewicz, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.

I. Getting Started

Table of Contents
1. Introduction
2. A simple tutorial

Chapter 1. Introduction

What is PHP?

PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

Simple answer, but what does that mean? An example:

Example 1-1. An introductory example

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

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

    </body>
</html>

Notice how this is different from a script written in other languages like Perl or C -- instead of writing a program with lots of commands to output HTML, you write an HTML script with some embedded code to do something (in this case, output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode".

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.

Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.


What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.

  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit its own website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Adabas DInterBasePostgreSQL
dBaseFrontBaseSQLite
EmpressmSQLSolid
FilePro (read-only)Direct MS-SQLSybase
HyperwaveMySQLVelocis
IBM DB2ODBCUnix dbm
InformixOracle (OCI7 and OCI8) 
IngresOvrimos 

We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...

As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.


Chapter 2. A simple tutorial

Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.

PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.


What do I need?

In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the PHP Links section for resources on finding PHP enabled web hosts.

Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as Apache, and of course PHP. You will most likely want to install a database as well, such as MySQL.

You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). In case you have problems with installing PHP yourself, we would suggest you ask your questions on our installation mailing list. If you choose to go on the simpler route, then locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find rpmfind and PBone helpful for locating RPMs. You may also want to visit apt-get to find packages for Debian.


Your first PHP-enabled page

Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:

Example 2-1. Our first PHP script: hello.php

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

Use your browser to access the file with your web server's URL, ending with the "/hello.php" file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

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

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many PHP support options.

The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

A Note on Line Feeds: Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

A Note on Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

A Note on Word Processors: Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

A Note on Windows Notepad: If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

Example 2-2. Get system information from PHP

<?php phpinfo(); ?>


Something Useful

Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].

Note: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)

To display this variable, you can simply do:

Example 2-3. Printing a variable (Array element)

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

A sample output of this script may be:

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

There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.

$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.

You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:

Example 2-4. Example using control structures and functions

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

A sample output of this script may be:

You are using Internet Explorer.<br />

Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.

The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.

We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:

Example 2-5. Mixing both HTML and PHP modes

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>

A sample output of this script may be:

<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>

Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.


Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from outside of PHP for more information and examples on using forms with PHP. Here is an example HTML form:

Example 2-6. A simple HTML form

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

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:

Example 2-7. Printing data from our form

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

A sample output of this script may be:

Hi Joe. You are 22 years old.

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.

You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.


Using old code with new versions of PHP

Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.

Two of the most important recent changes that affect old code are:

  • The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following superglobal arrays were introduced in PHP 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, still exist as they have since PHP 3. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

  • External variables are no longer registered in the global scope by default. In other words, as of PHP 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

For more details on these changes, see the section on predefined variables and links therein.


What's next?

With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: http://www.php.net/links.php.

To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Sites: http://conf.php.net/ and http://talks.php.net/


Chapter 3. General Installation Considerations

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

  • Websites and web applications (server-side scripting)

  • Command line scripting

  • Desktop (GUI) applications

For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.

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

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

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

From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.

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


Chapter 4. Installation on Unix systems

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

As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.

There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

Prerequisite knowledge and software for compiling:

  • Basic Unix skills (being able to operate "make" and a C compiler)

  • An ANSI C compiler

  • flex: Version 2.5.4

  • bison: Version 1.28 (preferred), 1.35, or 1.75

  • A web server

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

The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.

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


Apache 1.3.x on Unix systems

This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.

You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.

Example 4-1. Installation Instructions (Apache Shared Module Version) for PHP

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

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 1 and MySQL support.  Your
    path to apxs may differ from our example.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to 
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
  
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

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

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10. 
    
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.
        
    For PHP 4:
            
      LoadModule php4_module libexec/libphp4.so

    For PHP 5:
                      
      LoadModule php5_module libexec/libphp5.so
      
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
    
    For PHP 4:
    
      AddModule mod_php4.c
      
    For PHP 5:
    
      AddModule mod_php5.c

16. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.

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

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps

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

Alternatively, to install PHP as a static object:

Example 4-2. Installation Instructions (Static Module Installation for Apache) for PHP

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

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

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (The above line is correct! Yes, we know libphp5.a does not exist at this
    stage. It isn't supposed to. It will be created.)

12. make
    (you should now have an httpd binary which you can copy to your Apache bin dir if
    it is your first install then you need to "make install" as well)

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

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .php

Note: Replace php-5 by php-4 and php5 by php4 in PHP 4.

Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.

Example 4-3. Example commands for restarting Apache

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.

Different examples of compiling PHP for apache are as follows:

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

This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.

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

This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

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

This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

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

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().

When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache web page on DSO support.

Note: Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"

Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.

Note: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.


Apache 2.0 on Unix systems

This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.

Warning

We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM

You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.

PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

These versions of PHP are compatible to Apache 2.0.40 and later.

Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.

All mentioned versions of PHP will work still with Apache 1.3.x.

Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.

Example 4-4. Installation Instructions (Apache 2 Shared Module Version)

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

    Now you have Apache 2.0.NN available under /usr/local/apache2,
    configured with loadable module support and the standard MPM prefork.
    To test the installation use your normal procedure for starting
    the Apache server, e.g.:
    /usr/local/apache2/bin/apachectl start
    and stop the server to go on with the configuration for PHP:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php-NN

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 2 and MySQL support.  Your
    path to apxs may differ, in fact, the binary may even be named apxs2 on
    your system. 
    
      ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
                
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.
    
13. Setup your php.ini 
    
    cp php.ini-dist /usr/local/lib/php.ini
          
    You may edit your .ini file to set PHP options.  If you prefer having
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10.
    
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.

    For PHP 4:
  
      LoadModule php4_module modules/libphp4.so
      
    For PHP 5:
    
      LoadModule php5_module modules/libphp5.so
 
15. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.
            
      AddType application/x-httpd-php .php .phtml
                  
    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps
 
16. Use your normal procedure for starting the Apache server, e.g.:
   
      /usr/local/apache2/bin/apachectl start

Following the steps above you will have a running Apache 2.0 with support for PHP as SAPI module. Of course there are many more configuration options available for both, Apache and PHP. For more information use ./configure --help in the corresponding source tree. In case you wish to build a multithreaded version of Apache 2.0 you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Take care about the consequences and understand what you are doing. For more information read the Apache documentation about the MPM-Modules.

Note: If you want to use content negotiation, read the Apache MultiViews FAQ.

Note: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.


Caudium

PHP 4 can be built as a Pike module for the Caudium webserver. Note that this is not supported with PHP 3. Follow the simple instructions below to install PHP 4 for Caudium.

Example 4-5. Caudium Installation Instructions

1.  Make sure you have Caudium installed prior to attempting to
    install PHP 4. For PHP 4 to work correctly, you will need Pike
    7.0.268 or newer. For the sake of this example we assume that
    Caudium is installed in /opt/caudium/server/.
2.  Change directory to php-x.y.z (where x.y.z is the version number).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Restart Caudium if it's currently running.
7.  Log into the graphical configuration interface and go to the
    virtual server where you want to add PHP 4 support.
8.  Click Add Module and locate and then add the PHP 4 Script Support module.
9.  If the documentation says that the 'PHP 4 interpreter isn't
    available', make sure that you restarted the server. If you did
    check /opt/caudium/logs/debug/default.1 for any errors related to
    <filename>PHP4.so</filename>. Also make sure that 
    <filename>caudium/server/lib/[pike-version]/PHP4.so</filename>
    is present.
10. Configure the PHP Script Support module if needed.

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.

Note: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.


fhttpd related notes

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

Note: Support for fhttpd is no longer available as of PHP 4.3.0.


Sun, iPlanet and Netscape servers on Sun Solaris

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

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

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

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

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

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.

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

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

  5. Change to your extracted PHP directory: cd ../php-x.x.x

  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:

    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape. Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php

  2. Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

  3. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):

    <Object name="default">
    .
    .
    .
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    .
    .
    </Object>
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

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

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

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

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

Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").


CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note: Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On


Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].


Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!


CGI and command line setups

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

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.

As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.


Testing

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


Benchmarking

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

Note: make bench is only available for PHP 3.


Using Variables

Some server supplied environment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.


HP-UX specific installation notes

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

There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.

Official pre-compiled packages are located here: http://software.hp.com/

Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: Building Apache and PHP on HP-UX 11.11


OpenBSD installation notes

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


Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Example 4-6. OpenBSD Package Install Example

# pkg_add php4-core-4.3.8.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (add in mysql)
# pkg_add php4-mysql-4.3.8.tgz
# /usr/local/sbin/phpxs -a mysql
  (add in imap)
# pkg_add php4-imap-4.3.8.tgz
# /usr/local/sbin/phpxs -a imap
  (remove mysql as a test)
# pkg_delete php4-mysql-4.3.8
# /usr/local/sbin/phpxs -r mysql
  (install the PEAR libraries)
# pkg_add php4-pear-4.3.8.tgz

Read the packages(7) manual page for more information about binary packages on OpenBSD.


Using Ports

You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.


Common Problems

  • The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.

  • The OpenBSD 3.6 package for the gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.


Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).


Solaris specific installation tips

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


Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:

  • gcc (recommended, other C compilers may work)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

  • GNU sed

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


Using Packages

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


Debian GNU/Linux installation notes

This section contains notes and hints specific to installing PHP on Debian GNU/Linux.


Using APT

While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.

The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.

PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.

If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at http://www.apt-get.org/. One of the results found should be Dotdeb. This unofficial repository is maintained by Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :

Example 4-7. The two Dotdeb related lines

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

The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.

Now that everything is in place, you can use the following example to install Apache and PHP:

Example 4-8. Debian Install Example with Apache 1.3

# apt-get install libapache-mod-php4

APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :

Example 4-9. Stopping and starting Apache once PHP 4 is installed

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

Better control on configuration

In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.

When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).

Example 4-10. Getting the list of PHP additional packages

# dpkg -l 'php4-*'

As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.

If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:

Example 4-11. Install PHP with MySQL, cURL and GD

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

APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).

Example 4-12. These lines activate MySQL, cURL and GD into PHP

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

You'll only have to stop/start Apache as previously to activate the modules.


Common Problems

  • If you see the PHP source instead of the result the script should produce, APT has probably not included /etc/apache/conf.d/php4 in your Apache 1.3 configuration. Please ensure that the following line is present in your /etc/apache/httpd.conf file then stop/start Apache:

    Example 4-13. This line activates PHP 4 into Apache

    # Include /etc/apache/conf.d/
  • If you installed an additional module and if its functions are not available in your scripts, please ensure that the appropriate line is present in your php.ini, as seen before. APT may fail during the installation of the additional module, due to a confusing debconf configuration.


Chapter 5. Installation on Mac OS X

This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.


Using Packages

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

The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:


Using the bundled PHP

PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).

Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.

The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:

  1. Locate and open the Apache configuration file. By default, the location is as follows: /etc/httpd/httpd.conf

    Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.

    Note: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /etc/httpd/httpd.conf

    Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

  2. With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):

    # LoadModule php4_module libexec/httpd/libphp4.so
    
    # AddModule mod_php4.c
    Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

  3. Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)

    Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.

    <IfModule mod_php4.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>

  4. Be sure the DirectoryIndex loads the desired default index file

    This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.

  5. Set the php.ini location or use the default

    A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.

  6. Locate or set the DocumentRoot

    This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites

  7. Create a phpinfo() file

    The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:

    <?php phpinfo(); ?>

  8. Restart Apache, and load the PHP file created above

    To restart, either execute sudo apachectl graceful in the shell or stop/start the "Personal Web Server" option in the OS X System Preferences. By default, loading local files in the browser will have an URL like so: http://localhost/info.php Or using the DocumentRoot in the user directory is another option and would end up looking like: http://localhost/~yourusername/info.php

The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP version of this PHP binary. A call to phpinfo() will also reveal this information.


Compiling for OS X Server

Mac OS X Server install.

  1. Get the latest distributions of Apache and PHP.

  2. Untar them, and run the configure program on Apache like so.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache

  3. If you want the compiler to do some optimization, you may also want to add this line:

    setenv OPTIM=-O2

  4. Next, go to the PHP 4 source directory and configure it.

    ./configure --prefix=/usr \
        --sysconfdir=/etc \
        --localstatedir=/var \
        --mandir=/usr/share/man \
        --with-xml \
        --with-apache=/src/apache_1.3.12
    If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --with-apache string, put in the path to your apache source directory, for example /src/apache_1.3.12.

  5. Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.

  6. Now, reconfigure Apache to build in PHP 4.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a
    You may get a message telling you that libmodphp4.a is out of date. If so, go to the src/modules/php4 directory inside your Apache source directory and run this command: ranlib libmodphp4.a. Then go back to the root of the Apache source directory and run the above configure command again. That'll bring the link table up to date. Run make and make install again.

  7. Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.


Compiling for MacOS X Client

The following instructions will help you install a PHP module for the Apache web server included in MacOS X. This version includes support for the MySQL and PostgreSQL databases. These instructions are graciously provided by Marc Liyanage.

Warning

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

Do this to install:

  1. Open a terminal window.

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

  3. Type gunzip libphp4.so.gz.

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

  5. Now type sudo open -a TextEdit /etc/httpd/httpd.conf. TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)

    #AddType application/x-httpd-php .php 
    #AddType application/x-httpd-php-source .phps
    Remove the two hash marks (#), then save the file and quit TextEdit.

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

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

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


Chapter 6. Installation on Windows systems

This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.

There are two main ways to install PHP for Windows: either manually or by using the installer.

If you have Microsoft Visual Studio, you can also build PHP from the original source code.

Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.

Warning

There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that the manual installation is the best choice to have your system secure and optimised.


Windows Installer (PHP 5.2 and later)

The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix Toolkit (http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.

First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed with one of the following install types.


Normal Install

Run the MSI installer and follow the instructions provided by the installation wizard. You will be prompted to select the Web Server you wish to configure first, along with any configuration details needed.

You will then be prompted to select which features and extensions you wish to install and enable. By selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you will be able to install all sub-features of the included feature ( for example by selecting this options for the feature "PDO" you will install all PDO Drivers ).

Warning

It is not recommended to install all extensions by default, since many other them require dependencies from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after installation.

The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web servers to use PHP. The installer will currently configure IIS (CGI mode only), Apache, Xitami, and Sambar Server; if you are using a different web server you'll need to configure it manually.


Silent Install

The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP easily. To use silent mode:

msiexec.exe /i php-VERSION-win32-install.msi /q

You can control the install directory by passing it as a parameter to the install. For example, to install to e:\php:

msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:\php
You can also use the same syntax to specify the Apache Configuration Directory (APACHEDIR), the Sambar Server directory (SAMBARDIR), and the Xitami Server directory (XITAMIDIR).

You can also specify what features to install. For example, to install the mysqli extension and the CGI executable:

msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli

The current list of Features to install is as follows:

MainExecutable - php.exe executable
ScriptExecutable - php-win.exe executable
ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2,2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
Manual - PHP Manual in CHM Format

For more information on installing MSI installers from the command line, visit http://msdn.microsoft.com/library/en-us/msi/setup/command_line_options.asp


Upgrading PHP with the Install

To upgrade, run the installer either graphically or from the command line as normal. The installer will read your current install options, remove your old installation, and reinstall PHP with the same options as before. It is recommended that you use this method of keeping PHP updated instead of manually replacing the files in the installation directory.


Windows Installer (PHP 5.1.0 and earlier)

The Windows PHP installer is available from the downloads page at http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.

Note: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.

First, install your selected HTTP (web) server on your system, and make sure that it works.

Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.

The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.

Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.

Warning

Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers.


Manual Installation Steps

This install guide will help you manually install and configure PHP with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php.

Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.

Upgrading from a previous PHP version: Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.

MDAC requirements: If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.

The following steps should be completed on all installations before any server specific instructions are performed:

Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.

The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:

Example 6-1. PHP 4 package structure

c:\php
   |
   +--cli
   |  |
   |  |-php.exe           -- CLI executable - ONLY for command line scripting
   |
   +--dlls                -- support DLLs required by some extensions
   |  |
   |  |-expat.dll
   |  |
   |  |-fdftk.dll
   |  |
   |  |-...
   |
   +--extensions          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--mibs                -- support files for SNMP
   |
   +--openssl             -- support files for Openssl
   |
   +--pdf-related         -- support files for PDF
   |
   +--sapi                -- SAPI (server module support) DLLs
   |  |
   |  |-php4apache.dll
   |  |
   |  |-php4apache2.dll
   |  |
   |  |-..
   |
   +--PEAR                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-..
   |
   |-php.exe              -- CGI executable
   |
   |-..
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php4ts.dll           -- core PHP DLL
   | 
   |-...

Or:

Example 6-2. PHP 5 package structure

c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib
   |
   +--ext                 -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--extras
   |  |
   |  +--mibs             -- support files for SNMP
   |  |
   |  +--openssl          -- support files for Openssl
   |  |
   |  +--pdf-related      -- support files for PDF
   |  |
   |  |-mime.magic
   |
   +--pear                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-fdftk.dll
   |
   |-..
   |
   |-php-cgi.exe          -- CGI executable
   |
   |-php-win.exe          -- executes scripts without an opened command prompt
   |
   |-php.exe              -- CLI executable - ONLY for command line scripting
   |
   |-..
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php5activescript.dll
   |
   |-php5apache.dll
   |
   |-php5apache2.dll
   |
   |-..
   |
   |-php5ts.dll           -- core PHP DLL
   | 
   |-...

Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.

Note: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).

Here is a list of server modules shipped with PHP 4 and PHP 5:

  • sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.

  • sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.

  • sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.

  • sapi/php5apache2_2.dll - Apache 2.2.x module.

  • sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.

  • sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.

  • sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.

Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.

Warning

The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP.

The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:

  • The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).

  • Any directory in your Windows PATH environment variable.

To make php4ts.dll / php5ts.dll available you have three options: copy the file to the Windows system directory, copy the file to the web server's directory, or add your PHP directory, C:\php to the PATH. For better maintenance, we advise you to follow the last option, add C:\php to the PATH, because it will be simpler to upgrade PHP in the future. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry (and then don't forget to restart the computer - logoff isn't enough).

The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in the Section called The configuration file in Chapter 9 section.

If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page), otherwise your best option is to set the PHPRC environment variable. This process is explained in the following FAQ entry.

Note: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).

The following steps are optional:

  • Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:

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

  • Choose the extensions you would like to load when PHP starts. See the section about Windows extensions, about how to set up one, and what is already built in. Note that on a new installation it is advisable to first get PHP working and tested without any extensions before enabling them in php.ini.

  • On PWS and IIS, you can set the browscap configuration setting to point to: c:\windows\system\inetsrv\browscap.ini on Windows 9x/Me, c:\winnt\system32\inetsrv\browscap.ini on NT/2000, and c:\windows\system32\inetsrv\browscap.ini on XP. For an up-to-date browscap.ini, read the following FAQ.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.


ActiveScript

This section contains notes specific to the ActiveScript installation.

ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.

As of PHP 5.0.1, ActiveScript has been moved to the PECL repository. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/

Note: You should read the manual installation steps first!

After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).

After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.

To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:

<job id="test">
 
 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>
 
</job>
Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

Note: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.

Note: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.


Microsoft IIS / PWS

This section contains notes and hints specific to IIS (Microsoft Internet Information Server).

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.


General considerations for all installations of PHP with IIS or PWS

  • First, read the Manual Installation Instructions. Do not skip this step as it provides crucial information for installing PHP on Windows.

  • CGI users must set the cgi.force_redirect PHP directive to 0 inside php.ini. Read the faq on cgi.force_redirect for important details. Also, CGI users may want to set the cgi.redirect_status_env directive. When using directives, be sure these directives aren't commented out inside php.ini.

  • The PHP 4 CGI is named php.exe while in PHP 5 it's php-cgi.exe. In PHP 5, php.exe is the CLI, and not the CGI.

  • Modify the Windows PATH environment variable to include the PHP directory. This way the PHP DLL files and PHP executables can all remain in the PHP directory without cluttering up the Windows system directory. For more details, see the FAQ on Setting the PATH.

  • The IIS user (usually IUSR_MACHINENAME) needs permission to read various files and directories, such as php.ini, docroot, and the session tmp directory.

  • Be sure the extension_dir and doc_root PHP directives are appropriately set in php.ini. These directives depend on the system that PHP is being installed on. In PHP 4, the extension_dir is extensions while with PHP 5 it's ext. So, an example PHP 5 extensions_dir value is "c:\php\ext" and an example IIS doc_root value is "c:\Inetpub\wwwroot".

  • PHP extension DLL files, such as php_mysql.dll and php_curl.dll, are found in the zip package of the PHP download (not the PHP installer). In PHP 5, many extensions are part of PECL and can be downloaded in the "Collection of PECL modules" package. Files such as php_zip.dll and php_ssh2.dll. Download PHP files here.

  • When defining the executable, the 'check that file exists' box may also be checked. For a small performance penalty, the IIS (or PWS) will check that the script file exists and sort out authentication before firing up PHP. This means that the web server will provide sensible 404 style error messages instead of CGI errors complaining that PHP did not output any data.


Windows NT/200x/XP and IIS 4 or newer

PHP may be installed as a CGI binary, or with the ISAPI module. In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.

If you want to use the CGI binary, do the following:

  • Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:

  • Change the Execute Permissions to 'Scripts only'

  • Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.

  • Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe / php-cgi.exe.

To use the ISAPI module, do the following:

  • If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll / php5isapi.dll.

  • Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:

  • Change the Execute Permissions to 'Scripts only'

  • Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.

  • Stop IIS completely (NET STOP iisadmin)

  • Start IIS again (NET START w3svc)

With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.

In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.

The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.

If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.


Windows and PWS 4

PWS 4 does not support ISAPI, only PHP CGI should be used.

  • Edit the enclosed pws-php4cgi.reg / pws-php5cgi.reg file (look into the SAPI folder for PHP 4, or in the main folder for PHP 5) to reflect the location of your php.exe / php-cgi.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe" (change to C:\\php\\php-cgi.exe if you are using PHP 5) Now merge this registery file into your system; you may do this by double-clicking it.

  • In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.


Windows and PWS/IIS 3

The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg in the SAPI folder for PHP 4, or pws-php5cgi.reg in the main folder for PHP 5). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.

Warning

These steps involve working directly with the Windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry.

  • Run Regedit.

  • Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.

  • On the edit menu select: New->String Value.

  • Type in the extension you wish to use for your php scripts. For example .php

  • Double click on the new string value and enter the path to php.exe in the value data field. ex: C:\php\php.exe "%s" %s for PHP 4, or C:\php\php-cgi.exe "%s" %s for PHP 5.

  • Repeat these steps for each extension you wish to associate with PHP scripts.

The following steps do not affect the web server installation and only apply if you want your PHP scripts to be executed when they are run from the command line (ex. run C:\myscripts\test.php) or by double clicking on them in a directory viewer window. You may wish to skip these steps as you might prefer the PHP files to load into a text editor when you double click on them.

  • Navigate to: HKEY_CLASSES_ROOT

  • On the edit menu select: New->Key.

  • Name the key to the extension you setup in the previous section. ex: .php

  • Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.

  • Repeat the last step for each extension you set up in the previous section.

  • Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.

  • Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.

  • Right click on the phpfile key and select New->Key, name it Shell.

  • Right click on the Shell key and select New->Key, name it open.

  • Right click on the open key and select New->Key, name it command.

  • Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).

  • Exit Regedit.

  • If using PWS on Windows, reboot to reload the registry.

PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty tool from Steven Genusa to configure their script maps.


Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.

Note: Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext. A trailing slash may also be necessary for directories.


Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Example 6-3. PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps


Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Example 6-4. PHP and Apache 1.3.x as CGI

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

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

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

# specify the directory where php.ini is
SetEnv PHPRC C:/php
Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.


Apache 2.0.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.

Note: You should read the manual installation steps first!

Apache 2.2.x Support: Users of Apache 2.2.x may use the documentation below except the appropriate DLL file is named php5apache2_2.dll and it only exists as of PHP 5.2.0. See also http://snaps.php.net/

Warning

We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM

You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the Windows specific notes for Apache 2.0.x before reading on here.

PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

These versions of PHP are compatible to Apache 2.0.40 and later.

Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.

All mentioned versions of PHP will work still with Apache 1.3.x.

Warning

Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time.

Download the most recent version of Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.

There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.

Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext. A trailing slash may also be necessary for directories.


Installing as a CGI binary

You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:

Example 6-5. PHP and Apache 2.0 as CGI

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

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

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

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.


Installing as an Apache module

You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:

Example 6-6. PHP and Apache 2.0 as Module

# For PHP 4 do something like this:
LoadModule php4_module "c:/php/php4apache2.dll"
# Don't forget to copy the php4apache2.dll file from the sapi directory!
AddType application/x-httpd-php .php

# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

Note: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.

Note: If you want to use content negotiation, read related FAQ.

Warning

Don't mix up your installation with DLL files from different PHP versions. You have the only choice to use the DLL's and extensions that ship with your downloaded PHP version.


Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.


CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

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

  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

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

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

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

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


NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

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

  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

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

  • Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

  • Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:

    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  • This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes

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

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

Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").


CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note: Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On


Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].


Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"
where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!


OmniHTTPd Server

This section contains notes and hints specific to OmniHTTPd on Windows.

Note: You should read the manual installation steps first!

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.

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

Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  1. Install OmniHTTPd server.

  2. Right click on the blue OmniHTTPd icon in the system tray and select Properties

  3. Click on Web Server Global Settings

  4. On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.

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

  6. Click OK

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

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


Sambar Server on Microsoft Windows

This section contains notes and hints specific to the Sambar Server for Windows.

Note: You should read the manual installation steps first!

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar install directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    Example 6-7. ISAPI configuration of Sambar

    #for PHP 4
    *.php = c:\php\php4isapi.dll
    
    #for PHP 5
    *.php = c:\php\php5isapi.dll
    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.

Note: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.


Xitami on Microsoft Windows

This section contains notes and hints specific to Xitami on Windows.

Note: You should read the manual installation steps first!

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

Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.

Warning

By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks.

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

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

  • In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.


Building from source

This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Chapter 4.


Requirements

To compile and build PHP you need a Microsoft Development Environment. Microsoft Visual C++ 6.0 is recommended, though Visual C++ .NET versions will also work. Since PHP 5 the free Microsoft .NET toolchain is also supported (you need to install Windows Platform SDK, Visual C++ Toolkit and .NET Framework SDK).

To extract the downloaded files you will also need a ZIP extraction utility. Windows XP and newer already include this functionality built-in.

Before you get started, you have to download:

Finally, you are going to need the source to PHP itself. You can get the latest development version using anonymous CVS, a snapshot or the most recent released source tarball.


Putting it all together

After downloading the required packages you have to extract them in a proper place:

  • Create a working directory where all files end up after extracting, e.g: C:\work.

  • Create the directory win32build under your working directory (C:\work) and unzip win32build.zip into it.

  • Create the directory bindlib_w32 under your working directory (C:\work) and unzip bindlib_w32.zip into it.

  • Extract the downloaded PHP source code into your working directory (C:\work).

  • Build the libraries you are going to need (or download the binaries if available) and place the headers and libs in the C:\work\win32build\include and C:\work\win32build\lib directories, respectively.

  • If you don't have cygwin installed with bison and flex, you also need to make the C:\work\win32build\bin directory available in the PATH, so that thoses tools can be found by the configure script.

Following this steps your directory structure looks like this:
+--C:\work
|  |
|  +--bindlib_w32
|  |  |
|  |  +--arpa
|  |  |
|  |  +--conf
|  |  |
|  |  +--...
|  |
|  +--php-5.x.x
|  |  |
|  |  +--build
|  |  |
|  |  +--...
|  |  |
|  |  +--win32
|  |  |
|  |  +--...
|  |
|  +--win32build
|  |  |
|  |  +--bin
|  |  |
|  |  +--include
|  |  |
|  |  +--lib

If you aren't using Cygwin, you must also create the directories C:\usr\local\lib and then copy bison.simple from C:\work\win32build\bin to C:\usr\local\lib.

Note: If you want to use PEAR and the comfortable command line installer, the CLI-SAPI is mandatory. For more information about PEAR and the installer read the documentation at the PEAR website.


Build resolv.lib

You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release), but please remember the choice you made, because the debug build will only link with PHP when it is also built in debug mode. Build the appropriate configuration:

  • For GUI users, launch VC++, by double-clicking in C:\work\bindlib_w32\bindlib.dsw. Then select Build=>Rebuild All.

  • For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands:

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

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

At this point, you should have a usable resolv.lib in either your C:\work\bindlib_w32\Debug or Release subdirectories. Copy this file into your C:\work\win32build\lib directory over the file by the same name found in there.


Building PHP using the new build system [PHP >=5 only]

This chapter explains how to compile PHP >=5 using the new build system, which is CLI-based and very similar with the main PHP's Unix build system.

Note: This build system isn't available in PHP 4. Please refer to the Section called Building PHP using DSW files [PHP 4] instead.

Before starting, be sure you have read the Section called Putting it all together and you have built all needed libraries, like Libxml or ICU (needed for PHP >= 6).

First you should open a Visual Studio Command Prompt, which should be available under the Start menu. A regular Command Prompt window shouldn't work, as probably it doesn't have the necessary environment variables set. Then type something like cd C:\work\php-5.x.x to enter in the PHP source dir. Now you are ready to start configuring PHP.

The second step is running the buildconf batch file to make the configure script, by scanning the folder for config.w32 files. By default this command will also search in the following directories: pecl; ..\pecl; pecl\rpc; ..\pecl\rpc. Since PHP 5.1.0, you can change this behaviour by using the --add-modules-dir argument (e.g. cscript /nologo win32/build/buildconf.js --add-modules-dir=../php-gtk2 --add-modules-dir=../pecl).

The third step is configuring. To view the list of the available configuration options type cscript /nologo configure.js --help. After choosing the options that you will enable/disable, type something like: cscript /nologo configure.js --disable-foo --enable-fun-ext. Using --enable-foo=shared will attempt to build the 'foo' extension as a shared, dynamically loadable module.

The last step is compiling. To achieve this just issue the command nmake. The generated files (e.g. .exe and .dll) will be placed in either Release_TS or Debug_TS directories (if built with Thread safety), or in the Release or Debug directories otherwise.

Optionally you may also run PHP's test suite, by typing nmake test. If you want to run just a specific test, you may use the 'TESTS' variable (e.g. nmake /D TESTS=ext/sqlite/tests test - will only run sqlite's tests). To delete the files that were created during the compilation, you can use the nmake clean command.

A very useful configure option to build snapshots is --enable-snapshot-build, which add a new compiling mode (nmake build-snap). This tries to build every extension available (as shared, by default), but it will ignore build errors in individual extensions or SAPI.


Building PHP using DSW files [PHP 4]

Compiling PHP using the DSW files isn't supported as of PHP 5, as a much more flexible system was made available. Anyway, you can still use them, but keep in mind that they are not maintained very often, so you can have compiling problems. To compile PHP 4 for windows, this is the only available way though.


Configure MVC ++

The first step is to configure MVC++ to prepare for compiling. Launch Microsoft Visual C++, and from the menu select Tools => Options. In the dialog, select the directories tab. Sequentially change the dropdown to Executables, Includes, and Library files. Your entries should look like this:

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

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

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


Compiling

The best way to get started is to build the CGI version:

  • For GUI users, launch VC++, and then select File => Open Workspace and select C:\work\php-4.x.x\win32\php4ts.dsw. Then select Build=>Set Active Configuration and select the desired configuration, either php4ts - Win32 Debug_TS or php4ts - Win32 Release_TS. Finally select Build=>Rebuild All.

  • For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands from the C:\work\php-4.x.x\win32 directory:

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

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

    • At this point, you should have a usable php.exe in either your C:\work\php-4.x.x\Debug_TS or Release_TS subdirectories.

It is possible to do minor customization to the build process by editing the main/config.win32.h file. For example you can change the default location of php.ini, the built-in extensions, and the default location for your extensions.

Next you may want to build the CLI version which is designed to use PHP from the command line. The steps are the same as for building the CGI version, except you have to select the php4ts_cli - Win32 Debug_TS or php4ts_cli - Win32 Release_TS project file. After a successful compiling run you will find the php.exe in either the directory Release_TS\cli\ or Debug_TS\cli\.

In order to build the SAPI module (php4isapi.dll) for integrating PHP with Microsoft IIS, set your active configuration to php4isapi-whatever-config and build the desired dll.


Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:

In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML and Zlib

In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL and SQLite. And the following are no longer built in: MySQL and Overload.

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Example 6-8. Enable Bzip2 extension for PHP-Windows

    // change the following line from ...
    ;extension=php_bz2.dll
    
    // ... to
    extension=php_bz2.dll

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Note: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

Table 6-1. PHP Extensions

ExtensionDescriptionNotes
php_bz2.dllbzip2 compression functionsNone
php_calendar.dllCalendar conversion functionsBuilt in since PHP 4.0.3
php_cpdf.dllClibPDF functionsNone
php_crack.dllCrack functionsNone
php_ctype.dllctype family functionsBuilt in since PHP 4.3.0
php_curl.dllCURL, Client URL library functionsRequires: libeay32.dll, ssleay32.dll (bundled)
php_cybercash.dllCybercash payment functionsPHP <= 4.2.0
php_db.dllDBM functionsDeprecated. Use DBA instead (php_dba.dll)
php_dba.dllDBA: DataBase (dbm-style) Abstraction layer functionsNone
php_dbase.dlldBase functionsNone
php_dbx.dlldbx functions 
php_domxml.dllDOM XML functions PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll.NET functionsPHP <= 4.1.1
php_exif.dllEXIF functions php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dllFrontBase functionsPHP <= 4.2.0
php_fdf.dllFDF: Forms Data Format functions.Requires: fdftk.dll (bundled)
php_filepro.dllfilePro functionsRead-only access
php_ftp.dllFTP functionsBuilt-in since PHP 4.0.3
php_gd.dllGD library image functions Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll.
php_gd2.dllGD library image functionsGD2
php_gettext.dllGettext functions PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dllHyperWave functionsNone
php_iconv.dllICONV characterset conversionRequires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dllInformix functionsRequires: Informix libraries
php_iisfunc.dllIIS management functionsNone
php_imap.dllIMAP POP3 and NNTP functionsNone
php_ingres.dllIngres II functionsRequires: Ingres II libraries
php_interbase.dllInterBase functionsRequires: gds32.dll (bundled)
php_java.dllJava functionsPHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dllLDAP functions PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dllMulti-Byte String functionsNone
php_mcrypt.dllMcrypt Encryption functionsRequires: libmcrypt.dll
php_mhash.dllMhash functionsPHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dllMimetype functionsRequires: magic.mime (bundled)
php_ming.dllMing functions for FlashNone
php_msql.dllmSQL functionsRequires: msql.dll (bundled)
php_mssql.dllMSSQL functionsRequires: ntwdblib.dll (bundled)
php_mysql.dllMySQL functionsPHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dllMySQLi functionsPHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dllOracle 8 functionsRequires: Oracle 8.1+ client libraries
php_openssl.dllOpenSSL functionsRequires: libeay32.dll (bundled)
php_oracle.dllOracle functionsRequires: Oracle 7 client libraries
php_overload.dllObject overloading functionsBuilt in since PHP 4.3.0
php_pdf.dllPDF functionsNone
php_pgsql.dllPostgreSQL functionsNone
php_printer.dllPrinter functionsNone
php_shmop.dllShared Memory functionsNone
php_snmp.dllSNMP get and walk functionsNT only!
php_soap.dllSOAP functionsPHP >= 5.0.0
php_sockets.dllSocket functionsNone
php_sybase_ct.dllSybase functionsRequires: Sybase client libraries
php_tidy.dllTidy functionsPHP >= 5.0.0
php_tokenizer.dllTokenizer functionsBuilt in since PHP 4.3.0
php_w32api.dllW32api functionsNone
php_xmlrpc.dllXML-RPC functionsPHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dllXSLT functions PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled).
php_yaz.dllYAZ functionsRequires: yaz.dll (bundled)
php_zip.dllZip File functionsRead only access
php_zlib.dllZLib compression functionsBuilt in since PHP 4.3.0


Chapter 7. Installation of PECL extensions

Introduction to PECL Installations

PECL is a repository of PHP extensions that are made available to you via the PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.

These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the pear command. The information in the PEAR manual for the pear command also applies to the pecl command.

To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.

When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the Anonymous CVS Instructions for details on the required tools, and required versions.


Downloading PECL extensions

There are several options for downloading PECL extensions, such as:

  • http://pecl.php.net/

    The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.

  • pecl download extname

    PECL extensions that have releases listed on the PECL web site are available for download and installation using the pecl command. Specific revisions may also be specified.

  • CVS

    Most PECL extensions also reside in CVS. A web-based view may be seen at http://cvs.php.net/pecl/. To download straight from CVS, the following sequence of commands may be used. Note that phpfi is the password for user cvsread:

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

  • Windows downloads

    Windows users may find compiled PECL binaries by downloading the Collection of PECL modules from the PHP Downloads page, or by retrieving a PECL Snapshot or an extension DLL on PECL4WIN. To compile PHP under Windows, read the appropriate chapter.


PECL for Windows users

As with any other PHP extension DLL, installation is as simple as copying the PECL extension DLLs into the extension_dir folder and loading them from php.ini. For example, add the following line to your php.ini:

extension=php_extname.dll

After doing this, restart the web server.


Compiling shared PECL extensions with the pecl command

PECL makes it easy to create shared PHP extensions. Using the pecl command, do the following:

$ pecl install extname

This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini

By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:

$ pecl install extname-beta

You may also install a specific version using this variant:

$ pecl install extname-0.1


Compiling shared PECL extensions with phpize

Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from CVS. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.

The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:

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

A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.

If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.

Execute phpize --help to display additional usage information.


Compiling PECL extensions statically into PHP

You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.

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

This will result in the following directory:

/your/phpsrcdir/ext/extname

From here, force PHP to rebuild the configure script, and then build PHP as normal:

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

Note: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).

Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:

$ ./configure --help | grep extname


Chapter 8. Problems?

Read the FAQ

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


Other problems

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

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


Bug reports

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

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


Chapter 9. Runtime Configuration

The configuration file

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

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.

  • As of PHP 5.2.0, the following registry locations are searched in order: HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z\IniFilePath, HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y\IniFilePath and HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x\IniFilePath, where x, y and z mean the PHP major, minor and release versions.

  • HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)

  • Current working directory (except 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

If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().

Note: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.

The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the the latest php.ini from CVS helpful too.

Example 9-1. php.ini example

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

Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".


How to change configuration settings

Running PHP as an Apache module

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

With PHP 4 and PHP 5, there are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.

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

php_value name value

Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.

Note: Don't use php_value to set boolean values. php_flag (see below) should be used instead.

php_flag name on|off

Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.

php_admin_value name value

Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.

php_admin_flag name on|off

Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directives.

Example 9-2. Apache configuration example

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

Caution

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


Changing PHP configuration via the Windows registry

When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.


Other interfaces to PHP

Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.

If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().


Chapter 10. Basic syntax

Escaping from HTML

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.

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

You can also use more advanced structures:

Example 10-1. Advanced escaping

<?php
if ($expression) { 
    ?>
    <strong>This is true.</strong>
    <?php 
} else { 
    ?>
    <strong>This is false.</strong>
    <?php 
}
?>
This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().

There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

Example 10-2. PHP Opening and Closing Tags

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

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

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

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

While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two.

Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if php was configured with the --enable-short-tags option.

Note: If you are using PHP 3 you may also enable short tags via the short_tags() function. This is only available in PHP 3!

ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive.

Note: Support for ASP tags was added in 3.0.4.

Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.


Instruction separation

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

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

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

<?php echo 'We omitted the last closing tag';

Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.


Comments

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:

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

The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.

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

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

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


Chapter 11. Types

Introduction

PHP supports eight primitive types.

Four scalar types:

Two compound types:

And finally two special types:

This manual also introduces some pseudo-types for readability reasons:

You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.

The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

Note: If you want to check out the type and value of a certain expression, use var_dump().

Note: If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:

<?php
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

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

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

If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.

Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. Also, you may be interested in viewing the type comparison tables, as they show examples of various type related comparisons.


Booleans

This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Note: The boolean type was introduced in PHP 4.


Syntax

To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.

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

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.

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

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

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


Converting to boolean

To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

Every other value is considered TRUE (including any resource).

Warning

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

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


Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also: Arbitrary length integer / GMP, Floating point numbers, and Arbitrary precision / BCMath


Syntax

Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).

If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.

Example 11-1. Integer literals

<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>
Formally the possible structure for integer literals is:

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

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

octal       : 0[0-7]+

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

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.

Warning

If an invalid digit is passed to octal integer (i.e. 8 or 9), the rest of the number is ignored.

Example 11-2. Octal weirdness

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


Integer overflow

If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.

<?php
$large_number =  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump( 0xffffffff );
// output: float(4294967295)

// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump( 0x100000000 );
// output: int(2147483647)

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

Warning

Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem.

This is solved in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5. You can cast the value to an integer to always round it downwards, or you can use the round() function.

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


Converting to integer

To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().

See also type-juggling.


From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).


From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

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

See for more information the warning about float-precision.


From other types

Caution

Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice.


Floating point numbers

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:

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

Formally:

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

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

Floating point precision

It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999....

This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . ..

So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.


Converting to float

For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information. As of PHP 5, notice is thrown if you try to convert object to float.


Strings

A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.

Note: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.


Syntax

A string literal can be specified in three different ways.


Single quoted

The easiest way to specify a simple string is to enclose it in single quotes (the character ').

To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.

Note: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.

Note: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

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

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

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

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

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

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

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


Double quoted

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

Table 11-1. Escaped characters

sequencemeaning
\nlinefeed (LF or 0x0A (10) in ASCII)
\rcarriage return (CR or 0x0D (13) in ASCII)
\thorizontal tab (HT or 0x09 (9) in ASCII)
\\backslash
\$dollar sign
\"double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

Again, if you try to escape any other character, the backslash will be printed too! Before PHP 5.1.1, backslash in \{$var} hasn't been printed.

But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.


Heredoc

Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier (followed by new line) after <<<, then the string, and then the same identifier to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Warning

It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. Closing delimiter (possibly followed by a semicolon) must be followed by a newline too.

If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script.

It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead.

Example 11-3. Invalid example

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

Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Example 11-4. Heredoc string quoting example

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

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

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

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

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

Note: Heredoc support was added in PHP 4.


Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.


Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.

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

Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.

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

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

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";

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

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

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

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

// Works
echo "This square is $square->width meters broad.";

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

For anything more complex, you should use the complex syntax.


Complex (curly) syntax

This isn't called complex because the syntax is complex, but because you can include complex expressions this way.

In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" to get a literal "{$"). Some examples to make it clear:

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

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

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

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong 
// outside a string.  In other words, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}"; 

// Works.  When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";

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

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

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

Note: Functions and method calls work since PHP 5.

Note: Parsing variables within strings uses more memory than string concatenation. When writing a PHP script in which memory usage is a concern, consider using the concatenation operator (.) rather than variable parsing.


String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.

Note: They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6.

Example 11-5. Some string examples

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

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

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

// Alternative method using {} is deprecated as of PHP 6
$third = $str{2};

?>


Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.

There are a lot of useful functions for string modification.

See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).

There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, if you still didn't find what you're looking for, see also the character type functions.


Converting to string

You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().

A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.

An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).

Note: The decimal point character is defined in the script's locale (category LC_NUMERIC). See setlocale().

Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.

Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.

Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().

NULL is always converted to an empty string.

As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.

You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.


String conversion to numbers

When a string is evaluated as a numeric value, the resulting value and type are determined as follows.

The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.

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). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)     
?>

For more information on this conversion, see the Unix manual page for strtod(3).

If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.


Arrays

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.


Syntax

Specifying with array()

An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.

array( [key =>] value
     , ...
     )
// key may be an integer or string
// value may be any value

<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.

A value can be of any PHP type.

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

Warning

As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.


Creating/modifying with square-bracket syntax

You can also modify an existing array by explicitly setting values in it.

This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value
If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"
                
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.

Warning

As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0 as you
// might expect).
$array[] = 6;
print_r($array);

// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)


Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.


Array do's and don'ts

Why is $foo[bar] wrong?

You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

Note: The above example will output:

Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 2

More examples to demonstrate this fact:

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

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
// 
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Let's define a constant to demonstrate what's going on.  We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay as it's inside a string.  Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]";      // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.

As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.


So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.


Converting to array

For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.

If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names with a few notable exceptions: private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour.

<?php

class A {
	private $A; // This will become '\0A\0A'
}

class B extends A {
	private $A; // This will become '\0B\0A'
	public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

If you convert a NULL value to an array, you get an empty array.


Comparing

It is possible to compare arrays by array_diff() and by Array operators.


Examples

The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.

<?php
// this
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
                       4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>

Example 11-6. Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
            );
            
// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7, 
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
                  );
                  
// empty array
$empty = array();         
?>

Example 11-7. Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?>

The above example will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing values of the array directly is possible since PHP 5 by passing them as reference. Prior versions need workaround:

Example 11-8. Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

The above example will output:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example 11-9. One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example 11-10. Filling an array

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle); 
?>

Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.

Example 11-11. Sorting an array

<?php
sort($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.

Example 11-12. Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"; 
?>

You should be aware that array assignment always involves value copying. It also means that the internal array pointer used by current() and similar functions is reset. You need to use the reference operator to copy an array by reference.

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


Objects

Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, please read the section Classes and Objects.


Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was NULL, the new instance will be empty. Array converts to an object with properties named by array keys and with corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>


Resource

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.

Note: The resource type was introduced in PHP 4

See also get_resource_type().


Converting to resource

As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource.


Freeing resources

Due to the reference-counting system introduced with PHP 4's Zend Engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.

Note: Persistent database links are special, they are not destroyed by the garbage collector. See also the section about persistent connections.


NULL

The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.

Note: The null type was introduced in PHP 4.

A variable is considered to be NULL if

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().


Syntax

There is only one value of type NULL, and that is the case-insensitive keyword NULL.

<?php
$var = NULL;       
?>

See also is_null() and unset().


Pseudo-types used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.


number

number indicates that a parameter can be either integer or float.


callback

Some functions like call_user_func() or usort() accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods.

A PHP function is simply passed by its name as a string. You can pass any built-in or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().

A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.

Apart from common user-defined function, create_function() can be used to create an anonymous callback function.

Example 11-13. Callback function examples

<?php 
// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod')); 

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
?>

Note: In PHP4, you will have to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.


void

void in return type means that the return value is useless. void in parameters list means that the function doesn't accept any parameters.


Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all 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.

<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().

If you would like to test any of the examples in this section, you can use the var_dump() function.

Note: The behaviour of an automatic conversion to array is currently undefined.

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.


Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer

  • (bool), (boolean) - cast to boolean

  • (float), (double), (real) - cast to float

  • (string) - cast to string

  • (binary) - cast to binary string (PHP 6)

  • (array) - cast to array

  • (object) - cast to object

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Casting a literal strings and variables to binary strings:

<?php
$binary = (binary)$string;
$binary = b"binary string";
?>

Note: Instead of casting a variable to string, you can also enclose the variable in double quotes.

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:


Chapter 12. Variables

Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Tip: You may also want to take a look at the Appendix T.

For information on variable related functions, see the Variable Functions Reference.

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?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.
?>

One important thing to note is that only named variables may be assigned by reference.

<?php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array.

Example 12-1. Default values of uninitialized variables

<?php
echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 => 25
echo $unset_string . "abc"; // "" . "abc" => "abc"
$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.


Predefined variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Warning

In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

Variable variables: Superglobals cannot be used as variable variables inside functions or class methods.

Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.

If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

PHP Superglobals

$GLOBALS

Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER

Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET

Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST

Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE

Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES

Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.

$_ENV

Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST

Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().

Caution

Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST.

Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

$_SESSION

Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.


Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a = 1; /* global scope */ 

function Test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

Test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.


The global keyword

First, an example use of global:

Example 12-2. Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;
?>

The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example 12-3. Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
} 

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example 12-4. Example demonstrating superglobals and scope

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require 
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;
    
    echo $HTTP_POST_VARS['name'];
    
    // Superglobals are available in any scope and do 
    // not require 'global'. Superglobals are available 
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    echo $_POST['name'];
}
?>


Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Example 12-5. Example demonstrating need for static variables

<?php
function Test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example 12-6. Example use of static variables

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, every time the Test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Example 12-7. Static variables with recursive functions

<?php
function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test();
    }
    $count--;
}
?>

Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.

Example 12-8. Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct 
    static $int = 1+2;        // wrong  (as it is an expression)
    static $int = sqrt(121);  // wrong  (as it is an expression too)

    $int++;
    echo $int;
}
?>


References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

<?php
function test_global_ref() {
    global $obj;
    $obj = &new stdclass;
}

function test_global_noref() {
    global $obj;
    $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

Executing this example will result in the following output:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign a reference to the static variable
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign the object to the static variable
        $obj = new stdclass;
    }
    $obj->property++;
    return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

Executing this example will result in the following output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
  ["property"]=>
  int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods.


Variables from outside PHP

HTML Forms (GET and POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:

Example 12-9. A simple HTML form

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Example 12-10. Accessing data from a simple POST HTML form

<?php 
// Available since PHP 4.1.0

   echo $_POST['username'];
   echo $_REQUEST['username'];

   import_request_variables('p', 'p_');
   echo $p_username;

// Available since PHP 3. As of PHP 5.0.0, these long predefined
// variables can be disabled with the register_long_arrays directive.

   echo $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on. As of 
// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

   echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().

Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0

As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.

Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example 12-11. More complex form variables

<?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äu</option>
    </select><br />
    <input type="hidden" name="action" value="submitted" />
    <input type="submit" name="submit" value="submit me!" />
</form>
<?php
}
?>

In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies.


IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.


HTTP Cookies

PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two 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.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example 12-12. A setcookie() example

<?php
if (isset($_COOKIE['count'])) {
    $count = $_COOKIE['count'] + 1;
} else {
    $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

<?php
$varname.ext;  /* invalid variable name */
?>
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.


Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.


Chapter 13. Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tip: You may also want to take a look at the Appendix T.

Example 13-1. Valid and invalid constant names

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something"); 

?>

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.


Syntax

You can define a constant by using the define()-function. Once a constant is defined, it can never be changed or undefined.

Only scalar data (boolean, integer, float and string) can be contained in constants. Do not define resource constants.

You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.

Note: Constants and (global) variables are in a different namespace. This implies that for example TRUE and $TRUE are generally different.

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 (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). If you simply want to check if a constant is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ($) before them;

  • Constants may only be defined using the define() function, not by simple assignment;

  • Constants may be defined and accessed anywhere without regard to variable scoping rules;

  • Constants may not be redefined or undefined once they have been set; and

  • Constants may only evaluate to scalar values.

Example 13-2. Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

See also Class Constants.


Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:

Table 13-1. A few "magical" PHP constants

NameDescription
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

See also get_class(), get_object_vars(), file_exists() and function_exists().


Chapter 14. Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

<?php
function foo ()
{
    return 5;
}
?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a 
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of 
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the 
                       value of 24. the value of the assignment (24) is 
                       then assigned into $h, and $h ends with the value 
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.


Chapter 15. Operators

An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.

There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.

The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.


Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.

The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.

Table 15-1. Operator Precedence

AssociativityOperatorsAdditional Information
non-associativenewnew
left[array()
non-associative++ -- increment/decrement
non-associative~ - (int) (float) (string) (array) (object) @ types
non-associativeinstanceof types
right! logical
left* / % arithmetic
left+ - . arithmetic and string
left<< >> bitwise
non-associative< <= > >= comparison
non-associative== != === !== comparison
left& bitwise and references
left^ bitwise
left| bitwise
left&& logical
left|| logical
left? : ternary
right = += -= *= /= .= %= &= |= ^= <<= >>= assignment
leftand logical
leftxor logical
leftor logical
left,many uses

Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

Example 15-1. Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Use parentheses to increase readability of the code.

Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.


Arithmetic Operators

Remember basic arithmetic from school? These work just like those.

Table 15-2. Arithmetic Operators

ExampleNameResult
-$aNegationOpposite of $a.
$a + $bAdditionSum of $a and $b.
$a - $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bDivisionQuotient of $a and $b.
$a % $bModulusRemainder of $a divided by $b.

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Note: Remainder $a % $b is negative for negative $a.

See also the manual page on Math functions.


Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Since PHP 4, assignment by reference has been supported, using the $var = &$othervar; syntax, but this is not possible in PHP 3. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.


Bitwise Operators

Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

<?php
echo 12 ^ 9; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4
?>

Table 15-3. Bitwise Operators

ExampleNameResult
$a & $bAndBits that are set in both $a and $b are set.
$a | $bOrBits that are set in either $a or $b are set.
$a ^ $bXor Bits that are set in $a or $b but not both are set.
~ $aNot Bits that are set in $a are not set, and vice versa.
$a << $bShift left Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $bShift right Shift the bits of $a $b steps to the right (each step means "divide by two")

Warning

Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits.


Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Table 15-4. Comparison Operators

ExampleNameResult
$a == $bEqualTRUE if $a is equal to $b.
$a === $bIdentical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $bNot equalTRUE if $a is not equal to $b.
$a <> $bNot equalTRUE if $a is not equal to $b.
$a !== $bNot identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $bLess thanTRUE if $a is strictly less than $b.
$a > $bGreater thanTRUE if $a is strictly greater than $b.
$a <= $bLess than or equal to TRUE if $a is less than or equal to $b.
$a >= $bGreater than or equal to TRUE if $a is greater than or equal to $b.

If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?>

For various types, comparison is done according to the following table (in order).

Table 15-5. Comparison with Various Types

Type of Operand 1Type of Operand 2Result
null or stringstringConvert NULL to "", numerical or lexical comparison
bool or nullanythingConvert to bool, FALSE < TRUE
objectobjectBuilt-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or numberstring, resource or numberTranslate strings and resources to numbers, usual math
arrayarrayArray with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
arrayanythingarray is always greater
objectanythingobject is always greater

Example 15-2. Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
    if (count($op1) < count($op2)) {
        return -1; // $op1 < $op2
    } elseif (count($op1) > count($op2)) {
        return 1; // $op1 > $op2
    }
    foreach ($op1 as $key => $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val < $op2[$key]) {
            return -1;
        } elseif ($val > $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?>

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.


Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example 15-3. Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example 15-4. Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : 'false') ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>


Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key]; 
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Warning

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.


Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.


Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

Table 15-6. Increment/decrement Operators

ExampleNameEffect
++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.
--$aPre-decrementDecrements $a by one, then returns $a.
$a--Post-decrementReturns $a, then decrements $a by one.

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Example 15-5. Arithmetic Operations on Character Variables

<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$i . "\n";
}
?>

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.


Logical Operators

Table 15-7. Logical Operators

ExampleNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

Example 15-6. Logical operators illustrated

<?php

// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// "||" 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);

The above example will output something similar to:

bool(true)
bool(false)
bool(false)
bool(true)

String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

See also the manual sections on the String type and String functions.


Array Operators

Table 15-8. Array Operators

ExampleNameResult
$a + $bUnionUnion of $a and $b.
$a == $bEqualityTRUE if $a and $b have the same key/value pairs.
$a === $bIdentityTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $bInequalityTRUE if $a is not equal to $b.
$a <> $bInequalityTRUE if $a is not equal to $b.
$a !== $bNon-identityTRUE if $a is not identical to $b.

The + operator appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

When executed, this script will print the following:
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"
}

Elements of arrays are equal for the comparison if they have the same key and value.

Example 15-7. Comparing arrays

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

See also the manual sections on the Array type and Array functions.


Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Example 15-8. Using instanceof with classes

<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

The above example will output:

bool(true)
bool(false)
instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example 15-9. Using instanceof with inherited classes

<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

The above example will output:

bool(true)
bool(true)
Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Example 15-10. Using instanceof for class

<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

The above example will output:

bool(true)
bool(true)

Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Example 15-11. Using instanceof with other variables

<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

The above example will output:

bool(true)
bool(true)
bool(false)

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

Example 15-12. Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

The above example will output:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof.

See also get_class() and is_a().


Chapter 16. Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.


if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
    statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
    echo "a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
    echo "a is bigger than b";
    $b = $a;
}
?>

If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.


else

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:

<?php
if ($a > $b) {
    echo "a is bigger than b";
} else {
    echo "a is NOT bigger than b";
}
?>

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).


elseif

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or 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";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.


Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

<?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;
?>

See also while, for, and if for further examples.


while

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>


do-while

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

<?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);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'.


for

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. Comma separated expressions in expr2 are treated similarly to being separated by the || operator but has a lower precedence than ||. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;


foreach

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

As of PHP 5, it is possible to iterate objects too.

Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>

This is possible only if iterated array can be referenced (i.e. is variable).

Note: foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br />\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>

The following are also functionally identical:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usages:

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
   echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with key printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>


break

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?>


continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "&nbsp;&nbsp;Middle<br />\n";
        while (1) {
            echo "&nbsp;&nbsp;Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
  for ($i = 0; $i < 5; ++$i) {
      if ($i == 2)
          continue
      print "$i\n";
  }
?>

One can expect the result to be :

0
1
3
4

but this script will output :

2

because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.


switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Example 16-1. switch structure

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
}
?>

Example 16-2. switch structure allows usage of strings

<?php
switch ($i) {
case "apple":
    echo "i is apple";
    break;
case "bar":
    echo "i is bar";
    break;
case "cake":
    echo "i is cake";
    break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
case 0:
    echo "i equals 0";
case 1:
    echo "i equals 1";
case 2:
    echo "i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next 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";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases, and should be the last case statement. For example:

<?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";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
default:
    echo "i is not equal to 0, 1 or 2";
endswitch;
?>


declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
    statement

The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive. (See below for more information on the ticks directive)

The statement part of the declare block will be executed -- how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it.

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    // entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>


Ticks

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example 16-3. Profile a section of PHP code

<?php
// A function that records the time when it is called
function profile($dump = FALSE)
{
    static $profile;

    // Return the times stored in profile, then erase it
    if ($dump) {
        $temp = $profile;
        unset($profile);
        return $temp;
    }

    $profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?>
The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.

Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.

See also register_tick_function() and unregister_tick_function().


return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).


require()

The require() statement includes and evaluates the specific file.

require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include().

require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

Example 16-4. Basic require() examples

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>

See the include() documentation for more examples.

Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

See also include(), require_once(), include_once(), get_included_files(), eval(), file(), readfile(), virtual() and include_path.


include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.

Files for including are first looked in include_path relative to the current working directory and then in the directory of the current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in include_path relative to the current working directory.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example 16-5. Basic include() example

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

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

Example 16-6. Including within functions

<?php

function foo()
{
    global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
 * $fruit is NOT available outside of this  *
 * scope.  $color is because we declared it *
 * as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Appendix O for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Example 16-7. include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
 * files and not .txt files. Also, 'Works' here means that the variables
 * $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Works.
include 'file.php';  // Works.

?>

Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example 16-8. Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

Note: In PHP 3, the return may not appear inside a block unless it's a function block, in which case the return() applies to that function and not the whole file.

Example 16-9. include() and the return() statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Example 16-10. Using output buffering to include a PHP file into a string

<?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;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), and include_path.


require_once()

The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again. See the documentation for require() for more information on how this statement works.

require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

For examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.

Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: require_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example 16-11. require_once() is case insensitive on Windows

<?php
require_once("a.php"); // this will include a.php
require_once("A.php"); // this will include a.php again on Windows! (PHP 4 only)
?>
This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is required just once.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

See also require(), include(), include_once(), get_required_files(), get_included_files(), readfile(), and virtual().


include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

For more examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.

Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: include_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of include_once() and require_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example 16-12. include_once() is case insensitive on Windows

<?php
include_once("a.php"); // this will include a.php
include_once("A.php"); // this will include a.php again on Windows! (PHP 4 only)
?>
This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

See also include(), require(), require_once(), get_required_files(), get_included_files(), readfile(), and virtual().


Chapter 17. Functions

User-defined functions

A function may be defined using syntax such as the following:

Example 17-1. Pseudo code to demonstrate function uses

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tip: You may also want to take a look at the Appendix T.

In PHP 3, functions must be defined before they are referenced. No such requirement exists since PHP 4. Except when a function is conditionally defined such as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example 17-2. Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here 
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar() 
{
  echo "I exist immediately upon program start.\n";
}

?>

Example 17-3. Functions within functions

<?php
function foo() 
{
  function bar() 
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processesing has
   made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

PHP 3 does not support variable numbers of arguments to functions, although default arguments are supported (see Default argument values for more information). Both are supported, as of PHP 4: see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

Example 17-4. Recursive functions

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>


Function arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. A similar effect can be achieved in PHP 3 by passing an array of arguments to a function:

Example 17-5. Passing arrays to functions

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>


Making arguments be passed by reference

By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference.

If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition:

Example 17-6. Passing function parameters by reference

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>


Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example 17-7. Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

The output from the above snippet is:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

Also PHP allows you to use arrays and special type NULL as default values, for example:

Example 17-8. Using non-scalar types as default values

<?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");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example 17-9. Incorrect usage of default function arguments

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}
 
echo makeyogurt("raspberry");   // won't work as expected
?>

The output of the above example is:

Warning: Missing argument 2 in call to makeyogurt() in 
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

Now, compare the above with this:

Example 17-10. Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}
 
echo makeyogurt("raspberry");   // works as expected
?>

The output of this example is:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, default values may be passed by reference.


Variable-length argument lists

PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.

No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.


Returning values

Values are returned by using the optional return statement. Any type may be returned, including lists and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return() for more information.

Example 17-11. Use of return()

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?>

You can't return multiple values from a function, but similar results can be obtained by returning a list.

Example 17-12. Returning an array to get multiple values

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

To return a reference from a function, you have to use the reference operator & in both the function declaration and when assigning the returned value to a variable:

Example 17-13. Returning a reference from a function

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

For more information on references, please check out References Explained.


Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. You need to use your own wrapper function to utilize any of these constructs as variable functions.

Example 17-14. Variable function example

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

You can also call an object's method by using the variable functions feature.

Example 17-15. Variable method example

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }
    
    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

See also call_user_func(), variable variables and function_exists().


Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in otherwise you'll get fatal "undefined function" errors. For example, to use image functions such as imagecreatetruecolor(), you'll need your PHP compiled with GD support. Or, to use mysql_connect() you'll need your PHP compiled in with MySQL support. There are many core functions that are included in every version of PHP like the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show you which extensions are loaded into your PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to setup your PHP.

Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.

Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return NULL but this is just a convention, and cannot be relied upon.

See also function_exists(), the function reference, get_extension_funcs(), and dl().


Chapter 18. Classes and Objects (PHP 4)

class

A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:

<?php
class Cart {
    var $items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart

    function add_item($artnr, $num) {
        $this->items[$artnr] += $num;
    }

    // Take $num articles of $artnr out of the cart

    function remove_item($artnr, $num) {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } elseif ($this->items[$artnr] == $num) {
            unset($this->items[$artnr]);
            return true;
        } else {
            return false;
        }
    }
}
?>

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Warning

You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

However, the following is allowed:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

The following cautionary notes are valid for PHP 4.

Caution

The name stdClass is used internally by Zend and is reserved. You cannot have a class named stdClass in PHP.

Caution

The function names __sleep and __wakeup are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. See below for more information.

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).

<?php
class Cart {
    /* None of these will work in PHP 4. */
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    /* Arrays containing constant values will, though. */
    var $items = array("VCR", "TV");
}

/* This is how it should be done. */
class Cart {
    var $todays_date;
    var $name;
    var $owner;
    var $items = array("VCR", "TV");

    function Cart() {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

<?php
$cart = new Cart;
$cart->add_item("10", 1);

$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>

This creates the objects $cart and $another_cart, both of the class Cart. The function add_item() of the $cart object is being called to add 1 item of article number 10 to the $cart. 3 items of article number 0815 are being added to $another_cart.

Both, $cart and $another_cart, have functions add_item(), remove_item() and a variable items. These are distinct functions and variables. You can think of the objects as something similar to directories in a filesystem. In a filesystem you can have two different files README.TXT, as long as they are in different directories. Just like with directories where you'll have to type the full pathname in order to reach each file from the toplevel directory, you have to specify the complete name of the function you want to call: in PHP terms, the toplevel directory would be the global namespace, and the pathname separator would be ->. Thus, the names $cart->items and $another_cart->items name two different variables. Note that the variable is named $cart->items, not $cart->$items, that is, a variable name in PHP has only a single dollar sign.

<?php
// correct, single $
$cart->items = array("10" => 1); 

// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);

// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);  
?>

Within a class definition, you do not know under which name the object will be accessible in your program: at the time the Cart class was written, it was unknown whether the object would be named $cart, $another_cart, or something else later. Thus, you cannot write $cart->items within the Cart class itself. Instead, in order to be able to access its own functions and variables from within a class, one can use the pseudo-variable $this which can be read as 'my own' or 'current object'. Thus, '$this->items[$artnr] += $num' can be read as 'add $num to the $artnr counter of my own items array' or 'add $num to the $artnr counter of the items array within the current object'.

Note: The $this pseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule: $this is defined if a method is called statically from within another object. In this case, the value of $this is that of the calling object. This is illustrated in the following example:

<?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();
?>

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.


extends

Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition. It is not possible to subtract from a class, that is, to undefine any existing functions or variables. An extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.

<?php
class Named_Cart extends Cart {
    var $owner;
  
    function set_owner ($name) {
        $this->owner = $name;
    }
}
?>

This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:

<?php
$ncart = new Named_Cart;    // Create a named cart
$ncart->set_owner("kris");  // Name that cart
print $ncart->owner;        // print the cart owners name
$ncart->add_item("10", 1);  // (inherited functionality from cart)
?>

This is also called a "parent-child" relationship. You create a class, parent, and use extends to create a new class based on the parent class: the child class. You can even use this new child class and create another class based on this child class.

Note: Classes must be defined before they are used! If you want the class Named_Cart to extend the class Cart, you will have to define the class Cart first. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.


Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.

<?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this->add_item("10", 1);
    }
}
?>

This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can take arguments and these arguments can be optional, which makes them much more useful. To be able to still use the class without parameters, all parameters to constructors should be made optional by providing default values.

<?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1) {
        $this->add_item ($item, $num);
    }
}
 
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
 
// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?>

You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.

<?php
class A
{
    function A()
    {
        echo "I am the constructor of A.<br />\n";
    }

    function B()
    {
        echo "I am a regular function named B in class A.<br />\n";
        echo "I am not a constructor in A.<br />\n";
    }
}

class B extends A
{
}

// This will call B() as a constructor
$b = new B;
?>

The function B() in class A will suddenly become a constructor in class B, although it was never intended to be. PHP 4 does not care if the function is being defined in class B, or if it has been inherited.

Caution

PHP 4 doesn't call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate.

Destructors are functions that are called automatically when an object is destroyed, either with unset() or by simply going out of scope. There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors.


Scope Resolution Operator (::)

Caution

The following is valid for PHP 4 and later only.

Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.

<?php
class A {
    function example() {
        echo "I am the original function A::example().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().<br />
A::example();

// create an object of class B.
$b = new B;

// this will print 
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();
?>

The above example calls the function example() in class A, but there is no object of class A, so that we cannot write $a->example() or similar. Instead we call example() as a 'class function', that is, as a function of the class itself, not any object of that class.

There are class functions, but there are no class variables. In fact, there is no object at all at the time of the call. Thus, a class function may not use any object variables (but it can use local and global variables), and it may not use $this at all.

In the above example, class B redefines the function example(). The original definition in class A is shadowed and no longer available, unless you are referring specifically to the implementation of example() in class A using the ::-operator. Write A::example() to do this (in fact, you should be writing parent::example(), as shown in the next section).

In this context, there is a current object and it may have object variables. Thus, when used from WITHIN an object function, you may use $this and object variables.


parent

You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.

Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>


Serializing objects - objects in sessions

Note: In PHP 3, objects will lose their class association throughout the process of serialization and unserialization. The resulting variable is of type object, but has no class and no methods, thus it is pretty useless (it has become just like an array with a funny syntax).

Caution

The following information is valid for PHP >= 4 only.

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The functions in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class definition of class A in an include file and including this file in both page1.php and page2.php.

<?php
// classa.inc:
  
  class A {
      var $one = 1;
    
      function show_one() {
          echo $this->one;
      }
  }
  
// page1.php:

  include("classa.inc");
  
  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  $fp = fopen("store", "w");
  fwrite($fp, $s);
  fclose($fp);

// page2.php:
  
  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // now use the function show_one() of the $a object.  
  $a->show_one();
?>

If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.

It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class stdClass without any functions available at all, that is, it will become quite useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.


The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.


References inside the constructor

Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

<?php
class Foo {
    function Foo($name) {
        // create a reference inside the global array $globalref
        global $globalref;
        $globalref[] = &$this;
        // set name to passed value
        $this->setName($name);
        // and put it out
        $this->echoName();
    }

    function echoName() {
        echo "<br />", $this->name;
    }
 
    function setName($name) {
        $this->name = $name;
    }
}
?>

Let us check out if there is a difference between $bar1 which has been created using the copy = operator and $bar2 which has been created using the reference =& operator...

<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?>

Apparently there is no difference, but in fact there is a very significant one: $bar1 and $globalref[0] are _NOT_ referenced, they are NOT the same variable. This is because "new" does not return a reference by default, instead it returns a copy.

Note: There is no performance loss (since PHP 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).

To prove what is written above let us watch the code below.

<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
?>

Another final example, try to understand it.

<?php
class A {
    function A($i) {
        $this->value = $i;
        // try to figure out why we do not need a reference here
        $this->b = new B($this);
    }

    function createRef() {
        $this->c = new B($this);
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->value;
    }
}


class B {
    function B(&$a) {
        $this->a = &$a;
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->a->value;
    }
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

?>

The above example will output:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11


Comparing objects

In PHP 4, objects are compared in a very simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. Similar rules are applied when comparing two objects using the identity operator (===).

If we were to execute the code in the example below:

Example 18-1. Example of object comparison in PHP 4

<?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2) {
    echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class Flag {
    var $flag;

    function Flag($flag=true) {
            $this->flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this->flag = true;
    }

    function turnOff() {
        $this->flag = false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo "Compare instances created with the same parameters\n";
compareObjects($o, $q);

echo "\nCompare instances created with different parameters\n";
compareObjects($o, $p);

echo "\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o, $r);
?>

The above example will output:

Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Which is the output we will expect to obtain given the comparison rules above. Only instances with the same values for their attributes and from the same class are considered equal and identical.

Even in the cases where we have object composition, the same comparison rules apply. In the example below we create a container class that stores an associative array of Flag objects.

Example 18-2. Compound object comparisons in PHP 4

<?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this->set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this->set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this->set)) {
            unset($this->set[$name]);
        }
    }
}


$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo "\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u, $v);

echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>

The above example will output:

Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Chapter 19. Classes and Objects (PHP 5)

Introduction

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features.

Tip: You may also want to take a look at the Appendix T.


The Basics

class

Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples:

Example 19-1. $this variable in object-oriented language

<?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();
?>

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Example 19-2. Simple Class definition

<?php
class SimpleClass
{
    // member declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Example 19-3. Class members' default value

<?php
class SimpleClass
{
    // invalid member declarations:
    public $var1 = 'hello '.'world';
    public $var2 = <<<EOD
hello world
EOD;
    public $var3 = 1+2;
    public $var4 = self::myStaticMethod();
    public $var5 = $myVar;

    // valid member declarations:
    public $var6 = myConstant;
    public $var7 = self::classConstant;
    public $var8 = array(true, false);
    
    
}
?>

Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.


new

To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example 19-4. Creating an instance

<?php
$instance = new SimpleClass();
?>

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example 19-5. Object Assignment

<?php
$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overridden methods or members by referencing them with parent::

Example 19-6. Simple Class Inheritance

<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value

Autoloading Objects

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Note: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.

Note: Autoloading is not available if using PHP in CLI interactive mode.

Example 19-7. Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>


Constructors and Destructors

Constructor

void __construct ( [mixed args [, ...]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Example 19-8. using new unified constructors

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.


Destructor

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed.

Example 19-9. Destructor Example

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

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

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

Note: Destructor is called during the script shutdown so headers are always already sent.

Note: Attempting to throw an exception from a destructor causes a fatal error.


Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.


Members Visibility

Class members must be defined with public, private, or protected.

Example 19-10. Member declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, not Private

?>

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.


Method Visibility

Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.

Example 19-11. Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Contructors must be public
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This is public
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // Fatal Error
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private

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
?>


Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Example 19-12. :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access members or methods from inside the class definition.

Example 19-13. :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Example 19-14. Calling a parent's method

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.

Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.

In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Example 19-15. Static member example

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static 

// $foo::my_static is not possible

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

Example 19-16. Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
?>

Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).

The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.

Example 19-17. Defining and using a constant

<?php
class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}

echo MyClass::constant . "\n";

$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Example 19-18. Abstract class example

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>

The above example will output:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.


implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.


Examples

Example 19-19. Interface example

<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}

?>

See also the instanceof operator.


Overloading

Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static. All overloading methods must be defined as public.

Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively. Method __isset is called also with empty().


Member overloading

void __set ( string name, mixed value )

mixed __get ( string name )

bool __isset ( string name )

void __unset ( string name )

Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.

Example 19-20. overloading with __get, __set, __isset and __unset example

<?php
class Setter
{
    public $n;
    private $x = array("a" => 1, "b" => 2, "c" => 3);

    public function __get($nm)
    {
        echo "Getting [$nm]\n";

        if (isset($this->x[$nm])) {
            $r = $this->x[$nm];
            print "Returning: $r\n";
            return $r;
        } else {
            echo "Nothing!\n";
        }
    }

    public function __set($nm, $val)
    {
        echo "Setting [$nm] to $val\n";

        if (isset($this->x[$nm])) {
            $this->x[$nm] = $val;
            echo "OK!\n";
        } else {
            echo "Not OK!\n";
        }
    }

    public function __isset($nm)
    {
        echo "Checking if $nm is set\n";

        return isset($this->x[$nm]);
    }

    public function __unset($nm)
    {
        echo "Unsetting $nm\n";

        unset($this->x[$nm]);
    }
}

$foo = new Setter();
$foo->n = 1;
$foo->a = 100;
$foo->a++;
$foo->z++;

var_dump(isset($foo->a)); //true
unset($foo->a);
var_dump(isset($foo->a)); //false

// this doesn't pass through the __isset() method
// because 'n' is a public property
var_dump(isset($foo->n));

var_dump($foo);
?>

The above example will output:

Setting [a] to 100
OK!
Getting [a]
Returning: 100
Setting [a] to 101
OK!
Getting [z]
Nothing!
Setting [z] to 1
Not OK!

Checking if a is set
bool(true)
Unsetting a
Checking if a is set
bool(false)
bool(true)

object(Setter)#1 (2) {
  ["n"]=>
  int(1)
  ["x:private"]=>
  array(2) {
    ["b"]=>
    int(2)
    ["c"]=>
    int(3)
  }
}

Method overloading

mixed __call ( string name, array arguments )

The magic method __call() allows to capture invocation of non existing methods. That way __call() can be used to implement user defined method handling that depends on the name of the actual method being called. This is for instance useful for proxy implementations. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.

Example 19-21. overloading with __call example

<?php
class Caller
{
    private $x = array(1, 2, 3);

    public function __call($m, $a)
    {
        print "Method $m called:\n";
        var_dump($a);
        return $this->x;
    }
}

$foo = new Caller();
$a = $foo->test(1, "2", 3.4, true);
var_dump($a);
?>

The above example will output:

Method test called:
array(4) {
    [0]=>
    int(1)
    [1]=>
    string(1) "2"
    [2]=>
    float(3.4)
    [3]=>
    bool(true)
}
array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
}

Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Example 19-22. Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";


$class->iterateVisible();

?>

The above example will output:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Example 19-23. Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

    public function rewind() {
        echo "rewinding\n";
        reset($this->var);
    }

    public function current() {
        $var = current($this->var);
        echo "current: $var\n";
        return $var;
    }

    public function key() {
        $var = key($this->var);
        echo "key: $var\n";
        return $var;
    }

    public function next() {
        $var = next($this->var);
        echo "next: $var\n";
        return $var;
    }

    public function valid() {
        $var = $this->current() !== false;
        echo "valid: {$var}\n";
        return $var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n";
}
?>

The above example will output:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

Example 19-24. Object Iteration implementing IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this->items);
    }

    public function add($value) {
        $this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach ($coll as $key => $val) {
    echo "key/value: [$key -> $val]\n\n";
}
?>

The above example will output:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Note: For more examples of iterators, see the SPL Extension.


Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.


Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example 19-25. Parameterized Factory Method

<?php
class Example
{
    // The parameterized factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Example 19-26. Singleton Function

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;
    
    // A private constructor; prevents direct creation of object
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }
    
    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone $test;

?>

Magic Methods

The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.


__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

The __sleep method should return the value to serialize (usually $this), otherwise NULL is serialized.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example 19-27. Sleep and 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();
    }
}
?>

__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

Example 19-28. Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().


__set_state

This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).


Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example 19-29. Final methods example

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }
   
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example 19-30. Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Object cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Example 19-31. Cloning an object

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // Force a copy of this->object, otherwise
        // it will point to same object.
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

The above example will output:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)

Comparing objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

Example 19-32. Example of object comparison in PHP 5

<?php
function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function Flag($flag = true) {
        $this->flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this->flag = $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

The above example will output:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Reflection

Introduction

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:

<?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?>

Note: For details on these classes, have a look at the next chapters.

If we were to execute the code in the example below:

Example 19-33. Basic usage of the reflection API

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

The above example will output:

Class [ <internal> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [6] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
  }

  - Methods [9] {
    Method [ <internal> final private method __clone ] {
    }

    Method [ <internal> <ctor> public method __construct ] {

      - Parameters [2] {
        Parameter #0 [ <required> $message ]
        Parameter #1 [ <required> $code ]
      }
    }

    Method [ <internal> final public method getMessage ] {
    }

    Method [ <internal> final public method getCode ] {
    }

    Method [ <internal> final public method getFile ] {
    }

    Method [ <internal> final public method getLine ] {
    }

    Method [ <internal> final public method getTrace ] {
    }

    Method [ <internal> final public method getTraceAsString ] {
    }

    Method [ <internal> public method __toString ] {
    }
  }
}


ReflectionException

ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.


ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
    final private __clone()
    public void __construct(string name)
    public string __toString()
    public static string export(string name, bool return)
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public array getStaticVariables()
    public mixed invoke(mixed args)
    public mixed invokeArgs(array args)
    public bool returnsReference()
    public ReflectionParameter[] getParameters()
    public int getNumberOfParameters()
    public int getNumberOfRequiredParameters()
}
?>

Note: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.

To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.

Example 19-34. Using the ReflectionFunction class

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter() 
{
    static $c = 0;
    return $c++;
}

// Create an instance of the Reflection_Function class
$func = new ReflectionFunction('counter');

// Print out basic information
printf(
    "===> The %s function '%s'\n".
    "     declared in %s\n".
    "     lines %d to %d\n",
    $func->isInternal() ? 'internal' : 'user-defined',
    $func->getName(),
    $func->getFileName(),
    $func->getStartLine(),
    $func->getEndline()
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

// Print static variables if existant
if ($statics = $func->getStaticVariables())
{
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the function
printf("---> Invokation results in: ");
var_dump($func->invoke());


// you may prefer to use the export() method
echo "\nReflectionFunction::export() results:\n";
echo ReflectionFunction::export('counter');
?>

Note: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().


ReflectionParameter

The ReflectionParameter class retrieves information about a function's or method's parameters.

<?php
class ReflectionParameter implements Reflector
{
    final private __clone()
    public void __construct(string function, string parameter)
    public string __toString()
    public static string export(mixed function, mixed parameter, bool return)
    public string getName()
    public bool isPassedByReference()
    public ReflectionClass getDeclaringClass()
    public ReflectionClass getClass()
    public bool isArray()
    public bool allowsNull()
    public bool isPassedByReference()
    public bool isOptional()
    public bool isDefaultValueAvailable()
    public mixed getDefaultValue()
}
?>

Note: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0.

To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.

Example 19-35. Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

// Create an instance of Reflection_Function with the
// parameter given from the command line.    
$reflect = new ReflectionFunction($argv[1]);

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, 
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

ReflectionClass

The ReflectionClass class lets you reverse-engineer classes.

<?php
class ReflectionClass implements Reflector
{
    final private __clone()
    public void __construct(string name)
    public string __toString()
    public static string export(mixed class, bool return)
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public bool isInstantiable()
    public bool hasConstant(string name)
    public bool hasMethod(string name)
    public bool hasProperty(string name)
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public ReflectionMethod getConstructor()
    public ReflectionMethod getMethod(string name)
    public ReflectionMethod[] getMethods()
    public ReflectionProperty getProperty(string name)
    public ReflectionProperty[] getProperties()
    public array getConstants()
    public mixed getConstant(string name)
    public ReflectionClass[] getInterfaces()
    public bool isInterface()
    public bool isAbstract()
    public bool isFinal()
    public int getModifiers()
    public bool isInstance(stdclass object)
    public stdclass newInstance(mixed args)
    public stdclass newInstanceArgs(array args)
    public ReflectionClass getParentClass()
    public bool isSubclassOf(ReflectionClass class)
    public array getStaticProperties()
    public mixed getStaticPropertyValue(string name [, mixed default])
    public void setStaticPropertyValue(string name, mixed value)
    public array getDefaultProperties()
    public bool isIterateable()
    public bool implementsInterface(string name)
    public ReflectionExtension getExtension()
    public string getExtensionName()
}
?>

Note: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0, while newInstanceArgs() was added in PHP 5.1.3.

To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.

Example 19-36. Using the ReflectionClass class

<?php
interface Serializable
{
    // ...
}

class Object
{
    // ...
}

/**
 * A counter class
 */
class Counter extends Object implements Serializable 
{
    const START = 0;
    private static $c = Counter::START;

    /**
     * Invoke counter
     *
     * @access  public
     * @return  int
     */
    public function count() {
        return self::$c++;
    }
}

// Create an instance of the ReflectionClass class
$class = new ReflectionClass('Counter');

// Print out basic information
printf(
    "===> The %s%s%s %s '%s' [extends %s]\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d [%s]\n",
        $class->isInternal() ? 'internal' : 'user-defined',
        $class->isAbstract() ? ' abstract' : '',
        $class->isFinal() ? ' final' : '',
        $class->isInterface() ? 'interface' : 'class',
        $class->getName(),
        var_export($class->getParentClass(), 1),
        $class->getFileName(),
        $class->getStartLine(),
        $class->getEndline(),
        $class->getModifiers(),
        implode(' ', Reflection::getModifierNames($class->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($class->getDocComment(), 1));

// Print which interfaces are implemented by this class
printf("---> Implements:\n %s\n", var_export($class->getInterfaces(), 1));

// Print class constants
printf("---> Constants: %s\n", var_export($class->getConstants(), 1));

// Print class properties
printf("---> Properties: %s\n", var_export($class->getProperties(), 1));

// Print class methods
printf("---> Methods: %s\n", var_export($class->getMethods(), 1));

// If this class is instantiable, create an instance
if ($class->isInstantiable()) {
    $counter = $class->newInstance();

    echo '---> $counter is instance? '; 
    echo $class->isInstance($counter) ? 'yes' : 'no';

    echo "\n---> new Object() is instance? ";
    echo $class->isInstance(new Object()) ? 'yes' : 'no';
}
?>

Note: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().

Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').


ReflectionObject

The ReflectionObject class lets you reverse-engineer objects.

<?php
class ReflectionObject extends ReflectionClass
{
    final private __clone()
    public void __construct(mixed object)
    public string __toString()
    public static string export(mixed object, bool return)
}
?>


ReflectionMethod

The ReflectionMethod class lets you reverse-engineer class methods.

<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
    public void __construct(mixed class, string name)
    public string __toString()
    public static string export(mixed class, string name, bool return)
    public mixed invoke(stdclass object, mixed args)
    public mixed invokeArgs(stdclass object, array args)
    public bool isFinal()
    public bool isAbstract()
    public bool isPublic()
    public bool isPrivate()
    public bool isProtected()
    public bool isStatic()
    public bool isConstructor()
    public bool isDestructor()
    public int getModifiers()
    public ReflectionClass getDeclaringClass()

    // Inherited from ReflectionFunction
    final private __clone()
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public array getStaticVariables()
    public bool returnsReference()
    public ReflectionParameter[] getParameters()
    public int getNumberOfParameters()
    public int getNumberOfRequiredParameters()
}
?>

To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.

Example 19-37. Using the ReflectionMethod class

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the Reflection_Method class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));

// Print static variables if existant
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the method
printf("---> Invokation results in: ");
var_dump($method->invoke(NULL));
?>

Note: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.

Note: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.


ReflectionProperty

The ReflectionProperty class lets you reverse-engineer class properties.

<?php
class ReflectionProperty implements Reflector
{
    final private __clone()
    public void __construct(mixed class, string name)
    public string __toString()
    public static string export(mixed class, string name, bool return)
    public string getName()
    public bool isPublic()
    public bool isPrivate()
    public bool isProtected()
    public bool isStatic()
    public bool isDefault()
    public int getModifiers()
    public mixed getValue(stdclass object)
    public void setValue(stdclass object, mixed value)
    public ReflectionClass getDeclaringClass()
    public string getDocComment()
}
?>

Note: getDocComment() was added in PHP 5.1.0.

To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.

Example 19-38. Using the ReflectionProperty class

<?php
class String
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

Note: Trying to get or set private or protected class property's values will result in an exception being thrown.


ReflectionExtension

The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().

<?php
class ReflectionExtension implements Reflector {
    final private __clone()
    public void __construct(string name)
    public string __toString()
    public static string export(string name, bool return)
    public string getName()
    public string getVersion()
    public ReflectionFunction[] getFunctions()
    public array getConstants()
    public array getINIEntries()
    public ReflectionClass[] getClasses()
    public array getClassNames()
}
?>

To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.

Example 19-39. Using the ReflectionExtension class

<?php
// Create an instance of the ReflectionProperty class
$ext = new ReflectionExtension('standard');

// Print out basic information
printf(
    "Name        : %s\n" .
    "Version     : %s\n" .
    "Functions   : [%d] %s\n" .
    "Constants   : [%d] %s\n" .
    "INI entries : [%d] %s\n" .
    "Classes     : [%d] %s\n",
        $ext->getName(),
        $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
        sizeof($ext->getFunctions()),
        var_export($ext->getFunctions(), 1),

        sizeof($ext->getConstants()),
        var_export($ext->getConstants(), 1),

        sizeof($ext->getINIEntries()),
        var_export($ext->getINIEntries(), 1),

        sizeof($ext->getClassNames()),
        var_export($ext->getClassNames(), 1)
);
?>

Extending the reflection classes

In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

Example 19-40. Extending the built-in classes

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = '';

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility= Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Demo class #2
 *
 */
class U extends T {
    function x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U', 'x'));
?>

Note: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object


Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).

Example 19-41. Type Hinting examples

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

Failing to satisfy the type hint results in a fatal error.

<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.


Chapter 20. Exceptions

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. 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. Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. 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().

Example 20-1. Throwing an Exception

<?php
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

Extending Exceptions

A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.

Example 20-2. The Built in Exception class

<?php
class Exception
{
    protected $message = 'Unknown exception';   // exception message
    protected $code = 0;                        // user defined exception code
    protected $file;                            // source filename of exception
    protected $line;                            // source line of exception

    function __construct($message = null, $code = 0);

    final function getMessage();                // message of exception 
    final function getCode();                   // code of exception
    final function getFile();                   // source filename
    final function getLine();                   // source line
    final function getTrace();                  // an array of the backtrace()
    final function getTraceAsString();          // formated string of trace

    /* Overrideable */
    function __toString();                       // formated string for display
}
?>

If a class extends the built-in Exception class and re-defines the constructor, it is highly recomended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overriden to provide a custom output when the object is presented as a string.

Example 20-3. Extending the Exception class

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
        // some code
    
        // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A Custom function for this type of exception\n";
    }
}


/**
 * Create a class to test the 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 custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 isnt allowed as a parameter', 6);
                break;

            default: 
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}


// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Will be caught
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 3
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {        // Will be caught
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 4
try {
    $o = new TestException();
} catch (Exception $e) {        // Skipped, no exception
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";
?>

Chapter 21. References Explained

What References Are

References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.


What References Do

PHP references allow you to make two variables to refer to the same content. Meaning, when you do:

<?php
$a =& $b;
?>

it means that $a and $b point to the same content.

Note: $a and $b are completely equal here, that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place.

Note: If array with references is copied, its values are not dereferenced. This is valid also for arrays passed by value to functions.

Note: If you assign, pass or return an undefined variable by reference, it will get created.

Example 21-1. Using references with undefined variables

<?php
function foo(&$var) { }

foo($a); // $a is "created" and assigned to 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)
?>

The same syntax can be used with functions, that return references, and with new operator (in PHP 4.0.4 and later):

<?php
$bar =& new fooclass();
$foo =& find_var($bar);
?>

Since PHP 5, new return reference automatically so using =& in this context is deprecated and produces E_STRICT level message.

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.

While you can use the @ operator to mute any errors in the constructor when using it as @new, this does not work when using the &new statement. This is a limitation of the Zend Engine and will therefore result in a parser error.

Warning

If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array.

Example 21-2. Referencing global variables inside function

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning other reference to $var only changes the local variable's reference.

Note: If you assign a value to a variable with references in a foreach statement, the references are modified too.

Example 21-3. References and foreach statement

<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
    // do something
}
echo $ref; // 3 - last element of the iterated array
?>

The second thing references do is to pass variables by-reference. This is done by making a local variable in a function and a variable in the calling scope reference to the same content. Example:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>

will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. See also more detailed explanations about passing by reference.

The third thing reference can do is return by reference.


What References Are Not

As said before, references aren't pointers. That means, the following construct won't do what you expect:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar); 
?>

What happens is that $var in foo will be bound with $bar in caller, but then it will be re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the calling scope to something else using the reference mechanism, since $bar is not available in the function foo (it is represented by $var, but $var has only variable contents and not name-to-value binding in the calling symbol table). You can use returning references to reference variables selected by the function.


Passing by Reference

You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

Note that there's no reference sign on function call - only on function definition. Function definition alone is enough to correctly pass the argument by reference. In recent versions of PHP you will get a warning saying that "Call-time pass-by-reference" is deprecated when you use a & in foo(&$a);.

The following things can be passed by reference:

  • Variable, i.e. foo($a)

  • New statement, i.e. foo(new foobar())

  • Reference, returned from a function, i.e.:

    <?php
    function &bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());
    ?>

    See also explanations about returning by reference.

Any other expression should not be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

<?php
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error since PHP 5.0.5

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>

These requirements are for PHP 4.0.4 and later.


Returning References

Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. Do not use return-by-reference to increase performance, the engine is smart enough to optimize this on its own. Only return references when you have a valid technical reason to do it! To return references, use this syntax:

<?php
function &find_var($param)
{
    /* ...code... */
    return $found_var;
}

$foo =& find_var($bar);
$foo->x = 2;
?>

In this example, the property of the object returned by the find_var function would be set, not the copy, as it would be without using reference syntax.

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you return by-reference, not a copy as usual, and to indicate that reference binding, rather than usual assignment, should be done for $foo.

Note: If you try to return a reference from a function with the syntax: return ($found_var); 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. E_NOTICE error is issued since PHP 4.4.0 and PHP 5.1.0 if the code tries to return a dynamic expression or a result of the new operator.


Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a); 
?>

won't unset $b, just $a.

Again, it might be useful to think about this as analogous to Unix unlink call.


Spotting References

Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are:


global References

When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

That means, for example, that unsetting $var won't unset global variable.


$this

In an object method, $this is always a reference to the caller object.


Chapter 22. Introduction

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

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

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

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


Chapter 23. General considerations

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

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

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

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

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


Chapter 24. Installed as CGI binary

Possible attacks

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

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

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

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

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

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

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


Case 1: only public files served

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

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


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

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

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

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

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


Case 3: setting doc_root or user_dir

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

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

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

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

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

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


Case 4: PHP parser outside of web tree

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

#!/usr/local/bin/php

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

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


Chapter 25. Installed as an Apache module

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

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

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

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

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


Chapter 26. Filesystem Security

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

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

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

Example 26-1. Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir  = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";
?>
Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Example 26-2. ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_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!";
?>
There are two important measures you should take to prevent these issues.

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

  • Check all variables which are submitted.

Here is an improved script:

Example 26-3. More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$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, $lo gstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

?>
However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

Example 26-4. More secure file name checking

<?php
$username     = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$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");
}

//etc...
?>

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


Null bytes related issues

As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:

Example 26-5. Script vulnerable to null bytes

<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
    include '/home/wwwrun/'.$file.'.php';
    // the file /etc/passwd will be included
}
?>

Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:

Example 26-6. Correctly validating the input

<?php
$file = $_GET['file']; 

// Whitelisting possible values
switch ($file) {
    case 'main':
    case 'foo':
    case 'bar':
        include '/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include '/home/wwwrun/include/main.php';
}
?>

Chapter 27. Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.

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

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

Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.


Designing Databases

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

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

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

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


Connecting to Database

You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.


Encrypted Storage Model

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

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

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

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

Example 27-1. Using hashed password field

<?php

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

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

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

?>

SQL Injection

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

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

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

Example 27-2. Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

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

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

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

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

Example 27-3. Listing out articles ... and some passwords (any database server)

<?php

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);

?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:

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

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

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

Example 27-4. From resetting a password ... to gaining more privileges (any database server)

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

<?php

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;";

?>

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

Example 27-5. Attacking the database hosts operating system (MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

<?php

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

?>

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

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


Avoiding techniques

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

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

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

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

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

    Example 27-6. A more secure way to compose a query for paging

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

  • Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_escape_string(), sql_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.

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

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

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


Chapter 28. Error Reporting

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

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

Example 28-1. Attacking Variables with a custom HTML page

<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>

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

Example 28-2. Exploiting common debugging variables

<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>

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

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

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

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

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

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.

Example 28-3. Finding dangerous variables with E_ALL

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


Chapter 29. Using Register Globals

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

Example 29-1. Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Example 29-2. Example use of sessions with register_globals on or off

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from outside of PHP.

Example 29-3. Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Superglobals: availability note: Since PHP 4.1.0, superglobal arrays such as $_GET , $_POST, and $_SERVER, etc. have been available. For more information, read the manual section on superglobals


Chapter 30. User Submitted Data

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

Example 30-1. Dangerous Variable Usage

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

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

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

?>

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

  • Will this script only affect the intended files?

  • Can unusual or undesirable data be acted upon?

  • Can this script be used in unintended ways?

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

  • Will any transactions be adequately logged?

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

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


Chapter 31. Magic Quotes

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.


What are Magic Quotes

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

  • magic_quotes_gpc

    Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP.

    See also get_magic_quotes_gpc().

  • magic_quotes_runtime

    If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP.

    See also set_magic_quotes_runtime() and get_magic_quotes_runtime().

  • magic_quotes_sybase

    If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped.

    See also ini_get() for retrieving its value.


Why use Magic Quotes

  • Useful for beginners

    Magic quotes are implemented in PHP to help code written by beginners from being dangerous. Although SQL Injection is still possible with magic quotes on, the risk is reduced.

  • Convenience

    For inserting data into a database, magic quotes essentially runs addslashes() on all Get, Post, and Cookie data, and does so automagically.


Why not to use Magic Quotes

  • Portability

    Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.

  • Performance

    Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient.

    Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.

  • Inconvenience

    Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().


Disabling Magic Quotes

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.

Example 31-1. Disabling magic quotes server side

An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.

Example 31-2. Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>


Chapter 32. Hiding PHP

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

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

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

Example 32-1. Hiding PHP as another language

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

Example 32-2. Using unknown types for PHP extensions

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

Example 32-3. Using HTML types for PHP extensions

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


Chapter 33. Keeping Current

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

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


Chapter 34. HTTP authentication with PHP

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.

PHP Version Note: Superglobals, such as $_SERVER, became available in PHP 4.1.0. $HTTP_SERVER_VARS has been available since PHP 3.

An example script fragment which would force client authentication on a page is as follows:

Example 34-1. Basic HTTP Authentication example

<?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 34-2. Digest HTTP Authentication example

This example shows you how to implement a simple Digest HTTP authentication script. For more information read the 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 'Your 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();

    preg_match_all('@(\w+)=(?:([\'"])([^\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;
}
?>

Compatibility Note: Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

Configuration Note: PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Example 34-3. HTTP Authentication example forcing a new name/password

<?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";
}
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

IIS Note:: For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).

Note: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.


Chapter 35. Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security. $HTTP_COOKIE_VARS is also set in earlier versions of PHP when the track_vars configuration variable is set. (This setting is always on since PHP 4.0.3.)

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.


Chapter 36. Sessions

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.


Chapter 37. Dealing with XForms

XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.

The first key difference in XForms is how the form is sent to the client. XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.

Example 37-1. A simple XForms search form

<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>

The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.

Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.

If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.

If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.

Example 37-2. Using an XForm to populate $_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: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.


Chapter 38. Handling file uploads

POST method uploads

This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch).

Related Configurations Note: See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini

PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

Example 38-1. File Upload Form

A file upload screen can be built by creating a special form which looks something like this:

<!-- 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>

The __URL__ in the above example should be replaced, and point to a PHP file.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. Fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. The PHP settings for maximum-size, however, cannot be fooled. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too big and the transfer failed.

Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.

The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_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.

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

The error code associated with this file upload. This element was added in PHP 4.2.0

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Example 38-2. Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

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.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

Example 38-3. Uploading array of files

PHP supports HTML array feature even with files.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>

Error Messages Explained

Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.

Note: These became PHP constants in PHP 4.3.0.


Common Pitfalls

The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize ini-setting. The default is 2 Megabytes.

If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.

If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough.

Note: max_execution_time only affects 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, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running.

Warning

max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded.

If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough.

Not validating which file you operate on may mean that users can access sensitive information in other directories.

Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.

Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.

A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).


Uploading multiple files

Multiple files can be uploaded using different name for input.

It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:

Note: Support for multiple file uploads was added in PHP 3.0.10.

Example 38-4. Uploading multiple files

<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>

When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.


PUT method support

PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:

PUT /path/filename.html HTTP/1.1

This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <Virtualhost> block. A line like this would do the trick:

Script PUT /put.php

This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. 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 4 and following 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 38-5. Saving HTTP PUT files with PHP 4

<?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);
?>

Note: All documentation below applies to PHP 3 only.

Example 38-6. Saving HTTP PUT files with PHP 3

<?php copy($PHP_UPLOADED_FILE_NAME, $DOCUMENT_ROOT . $REQUEST_URI); ?>

The only trick here is that when PHP sees a PUT-method request it stores the uploaded file in a temporary file just like those handled by the POST-method. When the request ends, this temporary file is deleted. So, your PUT handling PHP script has to copy that file somewhere. The filename of this temporary file is in the $PHP_PUT_FILENAME variable, and you can see the suggested destination filename in the $REQUEST_URI (may vary on non-Apache web servers). This destination filename is the one that the remote client specified. You do not have to listen to this client. You could, for example, copy all uploaded files to a special uploads directory.


Chapter 39. Using remote files

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements. See Appendix O for more information about the protocols supported by PHP.

Note: In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopen-wrapper.

Note: The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the Reference LXV, Image Functions extension.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example 39-1. Getting the title of a remote page

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (eregi ("<title>(.*)</title>", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Example 39-2. Storing data on a remote server

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Note: You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().


Chapter 40. Connection handling

Note: The following applies to 3.0.7 and later.

Internally in PHP a connection status is maintained. There are 3 possible states:

  • 0 - NORMAL

  • 1 - ABORTED

  • 2 - TIMEOUT

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding "php_value ignore_user_abort" Apache .conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache .conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.


Chapter 41. Persistent Database Connections

Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.

Warning

There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is 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. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!

See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), ora_plogon(), pfsockopen(), pg_pconnect(), and sybase_pconnect().


Chapter 42. Safe Mode

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.

Warning

Safe Mode was removed in PHP 6.0.0.


Security and Safe Mode

Table 42-1. Security and Safe Mode Configuration Directives

NameDefaultChangeableChangelog
safe_mode"0"PHP_INI_SYSTEM 
safe_mode_gid"0"PHP_INI_SYSTEMAvailable since PHP 4.1.0.
safe_mode_include_dirNULLPHP_INI_SYSTEMAvailable since PHP 4.1.0.
safe_mode_exec_dir""PHP_INI_SYSTEM 
safe_mode_allowed_env_vars"PHP_"PHP_INI_SYSTEM 
safe_mode_protected_env_vars"LD_LIBRARY_PATH"PHP_INI_SYSTEM 
open_basedirNULLPHP_INI_SYSTEM 
disable_functions""php.ini onlyAvailable since PHP 4.0.1.
disable_classes""php.ini onlyAvailable since PHP 4.3.2.
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode.

safe_mode_gid boolean

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. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

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

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

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

If the value of this directive is empty, no files with different UID/GID can be included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions, all files could be included.

safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Note: If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

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

The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().

In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".

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

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

Note: Support for multiple directories was added in 3.0.7.

The default is to allow all files to be opened.

disable_functions string

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

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

disable_classes string

This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode.

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

Availability note: This directive became available in PHP 4.3.2

See also: register_globals, display_errors, and log_errors.

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php 
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
Running script.php:
<?php
 readfile('/etc/passwd'); 
?>
results in this error when safe mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not 
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):

<Directory /docroot>
  php_admin_value open_basedir /docroot 
</Directory>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in 
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:

disable_functions = readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in 
/docroot/script.php on line 2

Warning

These PHP restrictions are not valid in executed binaries, of course.


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Table 42-2. Safe mode limited functions

FunctionLimitations
dbmopen()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
dbase_open()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
filepro()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
filepro_rowcount()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
filepro_retrieve()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
ifx_*sql_safe_mode restrictions, (!= safe mode)
ingres_*sql_safe_mode restrictions, (!= safe mode)
mysql_*sql_safe_mode restrictions, (!= safe mode)
pg_lo_import()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
posix_mkfifo()Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
putenv()Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv()
move_uploaded_file()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
chdir()Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
dl()This function is disabled in safe mode.
backtick operatorThis function is disabled in safe mode.
shell_exec() (functional equivalent of backticks)This function is disabled in safe mode.
exec()You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
system()You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
passthru()You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
popen()You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
fopen()Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
mkdir()Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
rmdir()Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
rename()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
unlink()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
copy()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (on source and target)
chgrp()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
chown()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
chmod()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits
touch()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
symlink()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only the target is checked)
link()Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only the target is checked)
apache_request_headers()In safe mode, headers beginning with 'authorization' (case-insensitive) will not be returned.
header()In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).
PHP_AUTH variables In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0)
highlight_file(), show_source() Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1)
parse_ini_file() Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1)
set_time_limit() Has no effect when PHP is running in safe mode.
max_execution_time Has no effect when PHP is running in safe mode.
mail() In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3)
Any function that uses php4/main/fopen_wrappers.c ??


Chapter 43. Using PHP from the command line

As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It's worth mentioning that CLI and CGI are different SAPI's although they do share many of the same behaviors.

The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with --enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental and the option --enable-cli is on by default. You may use --disable-cli to disable it.

As of PHP 4.3.0, the name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if --with--apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.

Note: Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.

The Windows packages between PHP 4.2.0 and PHP 4.2.3 distributed the CLI as php-cli.exe, living in the same folder as the CGI php.exe. Starting with PHP 4.3.0 the Windows package distributes the CLI as php.exe in a separate folder named cli, so cli/php.exe . Starting with PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.

As of PHP 5, a new php-win.exe file is distributed. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk. You should configure with --enable-cli-win32.

What SAPI do I have?: From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.

Note: A Unix manual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.

Remarkable differences of the CLI SAPI compared to other SAPIs:

  • Unlike the CGI SAPI, no headers are written to the output.

    Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.

    CLI is started up in quiet mode by default, though the -q and --no-header switches are kept for compatibility so that you can use older CGI scripts.

    It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)

    Plain text error messages (no HTML formatting).

  • There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:

    Table 43-1. Overridden php.ini directives

    DirectiveCLI SAPI default valueComment
    html_errorsFALSE It can be quite hard to read the error message in your shell when it's cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE.
    implicit_flushTRUE It is desired that any output coming from print(), echo() and friends is immediately written to the output and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output.
    max_execution_time0 (unlimited) Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time.
    register_argc_argvTRUE

    Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI.

    As of PHP 4.3.0, the PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI. Prior to this version, the creation of these variables behaved as they do in CGI and MODULE versions which requires the PHP directive register_globals to be on. Regardless of version or register_globals setting, you can always go through either $_SERVER or $HTTP_SERVER_VARS. Example: $_SERVER['argv']

    Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).

  • To ease working in the shell environment, the following constants are defined:

    Table 43-2. CLI specific Constants

    ConstantDescription
    STDIN An already opened stream to stdin. This saves opening it with
    <?php
    
    $stdin = fopen('php://stdin', 'r');
    
    ?>
    If you want to read single line from stdin, you can use
    <?php
    $line = trim(fgets(STDIN)); // reads one line from STDIN
    fscanf(STDIN, "%d\n", $number); // reads number from STDIN
    ?>
    STDOUT An already opened stream to stdout. This saves opening it with
    <?php
    
    $stdout = fopen('php://stdout', 'w');
    
    ?>
    STDERR An already opened stream to stderr. This saves opening it with
    <?php
    
    $stderr = fopen('php://stderr', 'w');
    
    ?>

    Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

    php -r 'fwrite(STDERR, "stderr\n");'
    You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

  • The CLI SAPI does not change the current directory to the directory of the executed script!

    Example showing the difference to the CGI SAPI:

    <?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?>

    When using the CGI version, the output is:

    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp/another_directory

    This clearly shows that PHP changes its current directory to the one of the executed script.

    Using the CLI SAPI yields:

    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp

    This allows greater flexibility when writing shell tools in PHP.

    Note: The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.

The list of command line options provided by the PHP binary can be queried anytime by running PHP with the -h switch:

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               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --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>.
  --ri <name>      Show configuration for extension <name>.

The CLI SAPI has three different ways of getting the PHP code you want to execute:

  1. Telling PHP to execute a certain file.

    php my_script.php
    
    php -f my_script.php

    Both ways (whether using the -f switch or not) execute the file my_script.php. You can choose any file to execute - your PHP scripts do not have to end with the .php extension but can have any name or extension you wish.

  2. Pass the PHP code to execute directly on the command line.

    php -r 'print_r(get_defined_constants());'

    Special care has to be taken in regards of shell variable substitution and quoting usage.

    Note: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.

  3. Provide the PHP code to execute via standard input (stdin).

    This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:

    $ some_application | some_filter | php | sort -u >final_output.txt

You cannot combine any of the three ways to execute code.

Like every shell application, the PHP binary accepts a number of arguments but your PHP script can also receive arguments. The number of arguments which can be passed to your script is not limited by PHP (the shell has a certain size limit in the number of characters which can be passed; usually you won't hit this limit). The arguments passed to your script are available in the global array $argv. The zero index always contains the script name (which is - in case the PHP code is coming from either standard input or from the command line switch -r). The second registered global variable is $argc which contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments you want to pass to your script do not start with the - character, there's nothing special to watch out for. Passing an argument to your script which starts with a - will cause trouble because PHP itself thinks it has to handle it. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every argument following it is passed untouched to your script.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

However, there's another way of using PHP for shell scripting. You can write a script where the first line starts with #!/usr/bin/php. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set the execution attributes of the file appropriately (e.g. chmod +x test) your script can be executed like a normal shell or perl script:

Example 43-1. Execute PHP script as shell script

#!/usr/bin/php
<?php
var_dump($argv);
?>

Assuming this file is named test in the current directory, we can now do the following:

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

As you see, in this case no care needs to be taken when passing parameters which start with - to your script.

Long options are available since PHP 4.3.3.

Table 43-3. Command line options

OptionLong OptionDescription
-a--interactive

Runs PHP interactively. If you compile PHP with the Readline extension (which is not available on Windows), you'll have a nice shell, including a completion feature (e.g. you can start typing a variable name, hit the TAB key and PHP completes its name) and a typing history that can be accessed using the arrow keys. The history is saved in the ~/.php_history file.

Note: Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.

Note: Autoloading is not available if using PHP in CLI interactive mode.

-c--php-ini

This option can either specify a directory where to look for php.ini or specify a custom INI file (which does not need to be named php.ini), e.g.:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

If you don't specify this option, file is searched in default locations.

-n--no-php-ini

Ignore php.ini at all. This switch is available since PHP 4.3.0.

-d--define

This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is:

-d configuration_directive[=value]

Examples (lines are wrapped for layout reasons):

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e--profile-info

Activate the extended information mode, to be used by a debugger/profiler.

-f--file

Parses and executed the given filename to the -f option. This switch is optional and can be left out. Only providing the filename to execute is sufficient.

-h and -?--help and --usage With this option, you can get information about the actual list of command line options and some one line descriptions about what they do.
-i--info This command line option calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore quite huge.
-l--syntax-check

This option provides a convenient way to only perform a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to 255.

This option won't find fatal errors (like undefined functions). Use -f if you would like to test for fatal errors too.

Note: This option does not work together with the -r option.

-m--modules

Using this option, PHP prints out the built in (and loaded) PHP and Zend modules:

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r--run

This option allows execution of PHP right from within the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parser error if present.

Note: Care has to be taken when using this form of PHP to not collide with command line variable substitution done by the shell.

Example showing a parser error

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

The problem here is that the sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:

$ php -r " = get_defined_constants();"

The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]

If you are using a shell different from sh/bash, you might experience further issues. Feel free to open a bug report at http://bugs.php.net/. One can still easily run into troubles when trying to get shell variables into the code or using backslashes for escaping. You've been warned.

Note: -r is available in the CLI SAPI and not in the CGI SAPI.

Note: This option is meant for a very basic stuff. Thus some configuration directives (e.g. auto_prepend_file and auto_append_file) are ignored in this mode.

-B--process-begin

PHP code to execute before processing stdin. Added in PHP 5.

-R--process-code

PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.

-F--process-file

PHP file to execute for every input line. Added in PHP 5.

-E--process-end

PHP code to execute after processing the input. Added in PHP 5.

Example 43-2. Using the -B, -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-s--syntax-highlight and --syntax-highlight

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of <code> [...] </code> HTML tags, no HTML headers.

Note: This option does not work together with the -r option.

-v--version

Writes the PHP, PHP SAPI, and Zend version to standard output, e.g.

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-w--strip

Display source with stripped comments and whitespace.

Note: This option does not work together with the -r option.

-z--zend-extension

Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory.

 --ini

Shows configuration file names and scanned directories. Available as of PHP 5.2.3.

Example 43-3. --ini example

$ 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

Shows information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example 43-4. basic --rf usage

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}

--rc--rclass

Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example 43-5. --rc example

$ 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

Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example 43-6. --re example

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}

--ri--rextinfo

Shows the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information are available using "main" as extension name.

Example 43-7. --ri example

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2007.5
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.22482 => 59.22482
date.default_longitude => 11.018084 => 11.018084
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.

Example 43-8. Script intended to be run from command line (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];
}
?>

In the script above, we used the special first line to indicate that this file should be run by PHP. We work with a CLI version here, so there will be no HTTP header printouts. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

In the program above we checked if there are less or more than one arguments. Also if the argument was --help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.

If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:

Example 43-9. Batch file to run a command line PHP script (script.bat)

@C:\php\php.exe script.php %1 %2 %3 %4

Assuming you named the above program script.php, and you have your CLI php.exe in C:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.

VI. Function Reference

See also Appendix K.

Table of Contents
I. .NET Functions
II. Apache-specific Functions
III. Alternative PHP Cache
IV. Advanced PHP debugger
V. Array Functions
VI. Aspell functions [deprecated]
VII. BCMath Arbitrary Precision Mathematics Functions
VIII. PHP bytecode Compiler
IX. Bzip2 Compression Functions
X. Calendar Functions
XI. CCVS API Functions [deprecated]
XII. Class/Object Functions
XIII. Classkit Functions
XIV. ClibPDF Functions
XV. COM and .Net (Windows)
XVI. Crack Functions
XVII. Character Type Functions
XVIII. CURL, Client URL Library Functions
XIX. Cybercash Payment Functions
XX. Credit Mutuel CyberMUT functions
XXI. Cyrus IMAP administration Functions
XXII. Date and Time Functions
XXIII. DB++ Functions
XXIV. Database (dbm-style) Abstraction Layer Functions
XXV. dBase Functions
XXVI. DBM Functions [deprecated]
XXVII. dbx Functions
XXVIII. Direct IO Functions
XXIX. Directory Functions
XXX. DOM Functions
XXXI. DOM XML Functions
XXXII. enchant Functions
XXXIII. Error Handling and Logging Functions
XXXIV. Exif Functions
XXXV. Expect Functions
XXXVI. File Alteration Monitor Functions
XXXVII. Forms Data Format Functions
XXXVIII. Fileinfo Functions
XXXIX. filePro Functions
XL. Filesystem Functions
XLI. Filter Functions
XLII. Firebird/InterBase Functions
XLIII. Firebird/Interbase Functions (PDO_FIREBIRD)
XLIV. FriBiDi Functions
XLV. FrontBase Functions
XLVI. FTP Functions
XLVII. Function Handling Functions
XLVIII. GeoIP Functions
XLIX. Gettext Functions
L. GMP Functions
LI. gnupg Functions
LII. Net_Gopher
LIII. Haru PDF Functions
LIV. hash Functions
LV. HTTP
LVI. Hyperwave Functions
LVII. Hyperwave API Functions
LVIII. i18n Functions
LIX. IBM Functions (PDO_IBM)
LX. IBM DB2, Cloudscape and Apache Derby Functions
LXI. ICAP Functions [removed]
LXII. iconv Functions
LXIII. ID3 Functions
LXIV. IIS Administration Functions
LXV. Image Functions
LXVI. Imagick Image Library
LXVII. IMAP, POP3 and NNTP Functions
LXVIII. Informix Functions
LXIX. Informix Functions (PDO_INFORMIX)
LXX. Ingres II Functions
LXXI. IRC Gateway Functions
LXXII. PHP / Java Integration
LXXIII. JSON Functions
LXXIV. KADM5
LXXV. LDAP Functions
LXXVI. libxml Functions
LXXVII. Lotus Notes Functions
LXXVIII. LZF Functions
LXXIX. Mail Functions
LXXX. Mailparse Functions
LXXXI. Mathematical Functions
LXXXII. MaxDB PHP Extension
LXXXIII. MCAL Functions
LXXXIV. Mcrypt Encryption Functions
LXXXV. MCVE (Monetra) Payment Functions
LXXXVI. Memcache Functions
LXXXVII. Mhash Functions
LXXXVIII. Mimetype Functions
LXXXIX. Ming functions for Flash
XC. Miscellaneous Functions
XCI. mnoGoSearch Functions
XCII. Microsoft SQL Server Functions
XCIII. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
XCIV. Mohawk Software Session Handler Functions
XCV. mSQL Functions
XCVI. Multibyte String Functions
XCVII. muscat Functions
XCVIII. MySQL Functions
XCIX. MySQL Functions (PDO_MYSQL)
C. MySQL Improved Extension
CI. Ncurses Terminal Screen Control Functions
CII. Network Functions
CIII. Newt Functions
CIV. NSAPI-specific Functions
CV. Object Aggregation/Composition Functions
CVI. Object property and method call overloading
CVII. Oracle Functions
CVIII. ODBC Functions (Unified)
CIX. ODBC and DB2 Functions (PDO_ODBC)
CX. oggvorbis
CXI. OpenAL Audio Bindings
CXII. OpenSSL Functions
CXIII. Oracle Functions [deprecated]
CXIV. Oracle Functions (PDO_OCI)
CXV. Output Control Functions
CXVI. Ovrimos SQL Functions
CXVII. Paradox File Access
CXVIII. Parsekit Functions
CXIX. Process Control Functions
CXX. Regular Expression Functions (Perl-Compatible)
CXXI. PDF Functions
CXXII. PDO Functions
CXXIII. Phar archive stream and classes
CXXIV. PHP Options&Information
CXXV. POSIX Functions
CXXVI. Regular Expression Functions (POSIX Extended)
CXXVII. PostgreSQL Functions
CXXVIII. PostgreSQL Functions (PDO_PGSQL)
CXXIX. Printer Functions
CXXX. Program Execution Functions
CXXXI. PostScript document creation
CXXXII. Pspell Functions
CXXXIII. qtdom Functions
CXXXIV. Radius
CXXXV. Rar Functions
CXXXVI. GNU Readline
CXXXVII. GNU Recode Functions
CXXXVIII. RPM Header Reading Functions
CXXXIX. runkit Functions
CXL. SAM - Simple Asynchronous Messaging
CXLI. Satellite CORBA client extension [deprecated]
CXLII. SCA Functions
CXLIII. SDO Functions
CXLIV. SDO XML Data Access Service Functions
CXLV. SDO Relational Data Access Service Functions
CXLVI. Semaphore, Shared Memory and IPC Functions
CXLVII. SESAM Database Functions
CXLVIII. PostgreSQL Session Save Handler
CXLIX. Session Handling Functions
CL. Shared Memory Functions
CLI. SimpleXML functions
CLII. SNMP Functions
CLIII. SOAP Functions
CLIV. Socket Functions
CLV. Standard PHP Library (SPL) Functions
CLVI. SQLite Functions
CLVII. SQLite Functions (PDO_SQLITE)
CLVIII. Secure Shell2 Functions
CLIX. Statistics Functions
CLX. Stream Functions
CLXI. String Functions
CLXII. Shockwave Flash Functions
CLXIII. Swish Functions
CLXIV. Sybase Functions
CLXV. TCP Wrappers Functions
CLXVI. Tidy Functions
CLXVII. Tokenizer Functions
CLXVIII. Unicode Functions
CLXIX. URL Functions
CLXX. Variable Handling Functions
CLXXI. Verisign Payflow Pro Functions
CLXXII. vpopmail Functions
CLXXIII. W32api Functions
CLXXIV. WDDX Functions
CLXXV. win32ps Functions
CLXXVI. win32service Functions
CLXXVII. xattr Functions
CLXXVIII. xdiff Functions
CLXXIX. XML Parser Functions
CLXXX. XML-RPC Functions
CLXXXI. XMLReader functions
CLXXXII. XMLWriter Functions
CLXXXIII. XSL functions
CLXXXIV. XSLT Functions
CLXXXV. YAZ Functions
CLXXXVI. YP/NIS Functions
CLXXXVII. Zip File Functions
CLXXXVIII. Zlib Compression Functions

I. .NET Functions

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Table of Contents
dotnet_load -- Loads a DOTNET module

dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]] )

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Warning

This function is currently not documented; only the argument list is available.

ChangeLog

VersionDescription
4.1.0 The codepage parameter was added

II. Apache-specific Functions

Introduction

These functions are only available when running PHP as an Apache module.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined.

Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.


Installation

For PHP installation on Apache see the installation chapter.


Runtime Configuration

The behaviour of the Apache PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by php_flag settings in the server configuration file or local .htaccess files.

Example 1. Turning off PHP parsing for a directory using .htaccess

php_flag engine off

Table 1. Apache configuration options

NameDefaultChangeableChangelog
engine"1"PHP_INI_ALLAvailable since PHP 4.0.5.
child_terminate"0"PHP_INI_ALLAvailable since PHP 4.0.5.
last_modified"0"PHP_INI_ALLAvailable since PHP 4.0.5.
xbithack"0"PHP_INI_ALLAvailable since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

engine boolean

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

child_terminate boolean

Specify whether PHP scripts may request child process termination on end of request, see also apache_child_terminate().

last_modified boolean

Send PHP scripts modification date as Last-Modified: header for this request.

xbithack boolean

Parse files with executable bit set as PHP regardless of their file ending.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.

Table of Contents
apache_child_terminate -- Terminate apache process after this request
apache_get_modules -- Get a list of loaded Apache modules
apache_get_version -- Fetch Apache version
apache_getenv -- Get an Apache subprocess_env variable
apache_lookup_uri -- Perform a partial request for the specified URI and return all info about it
apache_note -- Get and set apache request notes
apache_request_headers -- Fetch all HTTP request headers
apache_reset_timeout -- Reset the Apache write timer
apache_response_headers -- Fetch all HTTP response headers
apache_setenv -- Set an Apache subprocess_env variable
ascii2ebcdic -- Translate string from ASCII to EBCDIC
ebcdic2ascii -- Translate string from EBCDIC to ASCII
getallheaders -- Fetch all HTTP request headers
virtual -- Perform an Apache sub-request

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate -- Terminate apache process after this request

Description

bool apache_child_terminate ( void )

apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code it is completed. It may be used to terminate a process after a script with high memory consumption has been run as memory will usually only be freed internally but not given back to the operating system.

Return Values

Returns TRUE if PHP is running as an Apache 1 module, the Apache version is non-multithreaded, and the child_terminate PHP directive is enabled (disabled by default). If these conditions are not met, FALSE is returned and an error of level E_WARNING is generated.

Notes

Note: This function is not implemented on Windows platforms.

See Also

exit()

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5)

apache_get_modules -- Get a list of loaded Apache modules

Description

array apache_get_modules ( void )

Get a list of loaded Apache modules.

Return Values

An array of loaded Apache modules.

ChangeLog

VersionDescription
5.0.0 Became available when using Apache 1, or the PHP Apache 2 filter API. Before this time, it was only available when using the Apache 2 handler API.

Examples

Example 1. apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

The above example will output something similar to:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version -- Fetch Apache version

Description

string apache_get_version ( void )

Fetch the Apache version.

Return Values

Returns the Apache version on success, or FALSE on failure.

ChangeLog

VersionDescription
4.3.4 Became available with Apache 1.
5.0.0 Became available with the Apache 2 filter API.

Examples

Example 1. apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

The above example will output something similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See Also

phpinfo()

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv -- Get an Apache subprocess_env variable

Description

string apache_getenv ( string variable [, bool walk_to_top] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parameters

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Return Values

The value of the Apache environment variable on success, or FALSE on failure

Examples

Example 1. apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

The above example will output something similar to:

42.24.42.240

apache_lookup_uri

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

apache_lookup_uri -- Perform a partial request for the specified URI and return all info about it

Description

object apache_lookup_uri ( string filename )

This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource.

This function is only supported when PHP is installed as an Apache module.

Parameters

filename

The filename (URI) that's being requested.

Return Values

An object of related URI information. The properties of this object are:

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

Examples

Example 1. apache_lookup_uri() example

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

The above example will output something similar to:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

apache_note

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

apache_note -- Get and set apache request notes

Description

string apache_note ( string note_name [, string note_value] )

apache_note() is an Apache-specific function which gets and sets values in a request's notes table.

Parameters

note_name

The name of the note.

note_value

The value of the note.

Return Values

If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name. If the note cannot be retrieved, FALSE is returned.

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_request_headers -- Fetch all HTTP request headers

Description

array apache_request_headers ( void )

Fetches all HTTP requests from the current request.

This function is only supported when PHP is installed as an Apache module.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Examples

Example 1. apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

The above example will output something similar to:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

Notes

Note: Prior to PHP 4.3.0, apache_request_headers() was called getallheaders(). After PHP 4.3.0, getallheaders() is an alias for apache_request_headers().

Note: You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

apache_reset_timeout

(no version information, might be only in CVS)

apache_reset_timeout -- Reset the Apache write timer

Description

bool apache_reset_timeout ( void )

apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.

This function requires Apache 1.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is disabled in safe mode.

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_response_headers -- Fetch all HTTP response headers

Description

array apache_response_headers ( void )

Fetch all HTTP response headers.

Return Values

An array of all Apache response headers on success, or FALSE on failure.

Examples

Example 1. apache_response_headers() example

<?php
print_r(apache_response_headers());
?>

The above example will output something similar to:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

Notes

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

apache_setenv

(PHP 4 >= 4.2.0, PHP 5)

apache_setenv -- Set an Apache subprocess_env variable

Description

bool apache_setenv ( string variable, string value [, bool walk_to_top] )

apache_setenv() sets the value of the Apache environment variable specified by variable.

Note: When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.

Parameters

variable

The environment variable that's being set.

value

The new variable value.

walk_to_top

Whether to set the top-level variable available to all Apache layers.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Setting an Apache environment variable using apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

Notes

Note: apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.

See Also

apache_getenv()

ascii2ebcdic

(PHP 3 >= 3.0.17)

ascii2ebcdic -- Translate string from ASCII to EBCDIC

Description

int ascii2ebcdic ( string ascii_str )

ascii2ebcdic() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the ASCII encoded string ascii_str to its equivalent EBCDIC representation (binary safe), and returns the result.

Parameters

ascii_str

The ASCII string that will be translated.

Return Values

The EBCDIC representation of an ASCII string.

See Also

ebcdic2ascii()

ebcdic2ascii

(PHP 3 >= 3.0.17)

ebcdic2ascii -- Translate string from EBCDIC to ASCII

Description

int ebcdic2ascii ( string ebcdic_str )

ebcdic2ascii() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the EBCDIC encoded string ebcdic_str to its equivalent ASCII representation (binary safe), and returns the result.

Parameters

ebcdic_str

The EBCDIC string that will be translated.

Return Values

The ASCII representation of an EBCDIC string.

See Also

ascii2ebcdic()

getallheaders

(PHP 3, PHP 4, PHP 5)

getallheaders -- Fetch all HTTP request headers

Description

array getallheaders ( void )

Fetches all HTTP requests from the current request.

This function is an alias for apache_request_headers(). Please read the apache_request_headers() documentation for more information on how this function works.

This function is only supported when PHP is installed as an Apache module.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

ChangeLog

VersionDescription
4.3.0 Became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works with Apache.

Notes

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

virtual

(PHP 3, PHP 4, PHP 5)

virtual -- Perform an Apache sub-request

Description

bool virtual ( string filename )

virtual() is an Apache-specific function which is similar to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

This function is only supported when PHP is installed as an Apache module.

Parameters

filename

The file that the virtual command will be performed on.

Return Values

Performs the virtual command on success, or returns FALSE on failure.

ChangeLog

VersionDescription
4.0.6 This function may be used on PHP files. However, it is typically better to use include() or require() for PHP files.

Notes

Warning

The query string can be passed to the included file but $_GET is copied from the parent script and only $_SERVER['QUERY_STRING'] is filled with the passed query string. The query string may only be passed when using Apache 2. The requested file will not be listed in the Apache access log.

Note: Environment variables set in the requested file are not visible to the calling script.

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

III. Alternative PHP Cache

Introduction

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.


Installation

This PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/apc.

The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/

Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, 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 .


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

There are two main decisions you have to make. First, how much shared memory do you want to set aside for APC, and second, whether you want APC to check if a file has been modified on every request. The two ini directives involved here are apc.shm_size and apc.stat. Read the sections on these two directives carefully below.

Once you have a running server, you should copy the apc.php script that comes with the extension to somewhere in your docroot and load it up in your browser. It provides you with a detailed look at what is happening in your cache. If you have GD enabled in PHP, it will even have pretty graphs. First thing to check is of course that it is actually caching files. Assuming it is working you should then pay close attention to the Cache full count number on the left. That tells you the number of times the cache has filled up and has had to forcefully clean up any entries not accessed within the last apc.ttl seconds. You should configure your cache to minimize this number. If you are constantly filling your cache, the resulting cache churn is going to hurt performance. You should either set more memory aside for APC, or use apc.filters to cache fewer scripts.

Table 1. APC configuration options

NameDefaultChangeableChangelog
apc.enabled"1"PHP_INI_SYSTEMPHP_INI_ALL in APC <= 3.0.12p2
apc.shm_segments"1"PHP_INI_SYSTEM 
apc.shm_size"30"PHP_INI_SYSTEM 
apc.optimization"0"PHP_INI_ALL 
apc.num_files_hint"1000"PHP_INI_SYSTEM 
apc.user_entries_hint"4096"PHP_INI_SYSTEM 
apc.ttl"0"PHP_INI_SYSTEM 
apc.user_ttl"0"PHP_INI_SYSTEM 
apc.gc_ttl"3600"PHP_INI_SYSTEM 
apc.cache_by_default"1"PHP_INI_ALLPHP_INI_SYSTEM in APC <= 3.0.12p2
apc.filtersNULLPHP_INI_SYSTEM 
apc.mmap_file_maskNULLPHP_INI_SYSTEM 
apc.slam_defense"0"PHP_INI_SYSTEM 
apc.file_update_protection"2"PHP_INI_SYSTEM 
apc.enable_cli"0"PHP_INI_SYSTEM> APC 3.0.6
apc.max_file_size"1M"PHP_INI_SYSTEM> APC 3.0.6
apc.stat"1"PHP_INI_SYSTEM> APC 3.0.9
apc.write_lock"1"PHP_INI_SYSTEM>= APC 3.0.11
apc.report_autofilter"0"PHP_INI_SYSTEM>= APC 3.0.11
apc.include_once_override"0"PHP_INI_SYSTEM>= APC 3.0.12
apc.rfc1867"0"PHP_INI_SYSTEM>= APC 3.0.13
apc.rfc1867_prefix"upload_"PHP_INI_SYSTEM>= APC 3.0.15
apc.rfc1867_name"APC_UPLOAD_PROGRESS"PHP_INI_SYSTEM>= APC 3.0.15
apc.rfc1867_freq"0"PHP_INI_SYSTEM>= APC 3.0.15
apc.localcache"0"PHP_INI_SYSTEM>= APC 3.0.14
apc.localcache.size"512"PHP_INI_SYSTEM>= APC 3.0.14
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.

apc.shm_size integer

The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.user_ttl integer

The number of seconds a user cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a 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.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

apc.file_update_protection integer

When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful if you change this setting. The default is for this to be On which means that APC will stat (check) the script on each request to see if it has been modified. If it has been modified it will recompile and cache the new version. If you turn this setting off, it will not check. That means that in order to have changes become active you need to restart your web server. On a production server where you rarely change the code, turning stats off can produce a significant performance boost.

For included/required files this option applies as well, but note that if you are using relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers when you first start up the server, or when many files are modified, you can end up with all your processes trying to compile and cache the same files. With write_lock enabled, only one process at a time will try to compile an uncached script while the other processes will run uncached instead of sitting around waiting on a lock.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if you compiled APC against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Example 1. An apc.rfc1867 example

<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

The above example will output something similar to:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with 'k', 'm', or 'g' for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficently large value, approximately half of apc.num_files_hint.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.

Table of Contents
apc_add --  Cache a variable in the data store (only if it's not stored)
apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store
apc_clear_cache --  Clears the APC cache
apc_compile_file --  Stores a file in the bytecode cache, bypassing all filters.
apc_define_constants --  Defines a set of constants for retrieval and mass-definition
apc_delete --  Removes a stored variable from the cache
apc_fetch --  Fetch a stored variable from the cache
apc_load_constants --  Loads a set of constants from the cache
apc_sma_info --  Retrieves APC's Shared Memory Allocation information
apc_store --  Cache a variable in the data store

apc_add

(no version information, might be only in CVS)

apc_add --  Cache a variable in the data store (only if it's not stored)

Description

bool apc_add ( string key, mixed var [, int ttl] )

Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. keys are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A apc_add() example

<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>

The above example will output:

string(3) "BAR"
string(3) "BAR"

apc_cache_info

(PECL)

apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store

Description

array apc_cache_info ( [string cache_type [, bool limited]] )

Return Values

Array of cached data (and meta-data), or FALSE on failure

Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Parameters

cache_type

If cache_type is "user", information about the user cache will be returned; otherwise, information about the system cache (cached files) will be returned.

limited

If limited is TRUE, the return value will exclude the individual list of cache entries. This is usefull when trying to optimize calls for statistics gathering.

ChangeLog

VersionDescription
3.0.11 The limited parameter was introduced.

Examples

Example 1. A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

The above example will output something similar to:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

apc_clear_cache

(PECL)

apc_clear_cache --  Clears the APC cache

Description

bool apc_clear_cache ( [string cache_type] )

Return Values

Returns TRUE on success or FALSE on failure.

Parameters

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

apc_compile_file

(no version information, might be only in CVS)

apc_compile_file --  Stores a file in the bytecode cache, bypassing all filters.

Description

bool apc_compile_file ( string filename )

Return Values

Returns TRUE on success or FALSE on failure.

Parameters

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

apc_define_constants

(PECL)

apc_define_constants --  Defines a set of constants for retrieval and mass-definition

Description

bool apc_define_constants ( string key, array constants [, bool case_sensitive] )

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the hidef extension from PECL.

Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

Parameters

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>

The above example will output:

123

apc_delete

(PECL)

apc_delete --  Removes a stored variable from the cache

Description

bool apc_delete ( string key )

Parameters

key

The key used to store the value (with apc_store()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>

apc_fetch

(PECL)

apc_fetch --  Fetch a stored variable from the cache

Description

mixed apc_fetch ( string key )

Parameters

key

The key used to store the value (with apc_store()).

Return Values

The stored variable on success; FALSE on failure

Examples

Example 1. A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

apc_load_constants

(PECL)

apc_load_constants --  Loads a set of constants from the cache

Description

bool apc_load_constants ( string key [, bool case_sensitive] )

Parameters

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

The above example will output:

123

apc_sma_info

(PECL)

apc_sma_info --  Retrieves APC's Shared Memory Allocation information

Description

array apc_sma_info ( [bool limited] )

Parameters

limited

Return Values

Array of Shared Memory Allocation data; FALSE on failure.

Examples

Example 1. A apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

The above example will output something similar to:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

apc_store

(PECL)

apc_store --  Cache a variable in the data store

Description

bool apc_store ( string key, mixed var [, int ttl] )

Note: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

IV. Advanced PHP debugger

Introduction

APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.

Caution

APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).


Installation

APD is currently available as a PECL extension from http://pecl.php.net/package/apd. Make sure you have installed the CGI version of PHP and it is available in your current path along with the phpize script.

Run the following command to download, build, and install the latest stable version of APD:

pear install apd

This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.

Windows users can download the extension dll php_apd.dll from http://snaps.php.net/win32/PECL_STABLE/.

In your INI file, add the following lines:

zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0

Depending on your PHP build, the zend_extension directive can be one of the following:

zend_extension              (non ZTS, non debug build)
zend_extension_ts           (    ZTS, non debug build)
zend_extension_debug        (non ZTS,     debug build)
zend_extension_debug_ts     (    ZTS,     debug build)


Building on Win32

To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. APD Configuration Options

NameDefaultChangeableChangelog
apd.dumpdirNULLPHP_INI_ALL 
apd.statement_tracing"0"PHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

apd.dumpdir string

Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.

You can specify a different directory as an argument to apd_set_pprof_trace().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 2. APD constants

ConstantValueDescription
FUNCTION_TRACE (integer) 1 
ARGS_TRACE (integer) 2 
ASSIGNMENT_TRACE (integer) 4 
STATEMENT_TRACE (integer) 8 
MEMORY_TRACE (integer) 16 
TIMING_TRACE (integer) 32 
SUMMARY_TRACE (integer) 64 
ERROR_TRACE (integer) 128 
PROF_TRACE (integer) 256 
APD_VERSION (string) example: 1.0.2-dev 

How to use PHP-APD in your scripts

  1. As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:

    apd_set_pprof_trace();

    You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    Tip: If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php

  3. To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:

    bash-2.05b$ pprofp -R /tmp/pprof.22141.0
    
    Trace for /home/dan/testapd.php
    Total Elapsed Time = 0.00
    Total System Time  = 0.00
    Total User Time    = 0.00
    
    
    Real         User        System             secs/    cumm
    %Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
    --------------------------------------------------------------------------------------
    100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
    56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
    28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
    14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace

    The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.


Contact information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to apd@mail.communityconnect.com. Any help is very welcome.

Table of Contents
apd_breakpoint -- Stops the interpreter and waits on a CR from the socket
apd_callstack -- Returns the current call stack as an array
apd_clunk -- Throw a warning and a callstack
apd_continue -- Restarts the interpreter
apd_croak -- Throw an error, a callstack and then exit
apd_dump_function_table -- Outputs the current function table
apd_dump_persistent_resources -- Return all persistent resources as an array
apd_dump_regular_resources -- Return all current regular resources as an array
apd_echo -- Echo to the debugging socket
apd_get_active_symbols -- Get an array of the current variables names in the local scope
apd_set_pprof_trace -- Starts the session debugging
apd_set_session_trace -- Starts the session debugging
apd_set_session -- Changes or sets the current debugging level
apd_set_socket_session_trace -- Starts the remote session debugging
override_function -- Overrides built-in functions
rename_function -- Renames orig_name to new_name in the global function table

apd_breakpoint

(PECL)

apd_breakpoint -- Stops the interpreter and waits on a CR from the socket

Description

bool apd_breakpoint ( int debug_level )

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Typical session using tcplisten

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test. 
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes 
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed ( 
-2089521468.1073275368)
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);

apd_callstack

(no version information, might be only in CVS)

apd_callstack -- Returns the current call stack as an array

Description

array apd_callstack ( void )

Returns the current call stack as an array

Return Values

An array containing the current call stack.

Examples

Example 1. apd_callstack() example

<?php
print_r(apd_callstack());
?>

apd_clunk

(no version information, might be only in CVS)

apd_clunk -- Throw a warning and a callstack

Description

void apd_clunk ( string warning [, string delimiter] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example 1. apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

See Also

apd_croak()

apd_continue

(PECL)

apd_continue -- Restarts the interpreter

Description

bool apd_continue ( int debug_level )

Usually sent via the socket to restart the interpreter.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. apd_continue() example

<?php
apd_continue(0);
?>

apd_croak

(no version information, might be only in CVS)

apd_croak -- Throw an error, a callstack and then exit

Description

void apd_croak ( string warning [, string delimiter] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example 1. apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

See Also

apd_clunk()

apd_dump_function_table

(no version information, might be only in CVS)

apd_dump_function_table -- Outputs the current function table

Description

void apd_dump_function_table ( void )

Outputs the current function table.

Return Values

No value is returned.

Examples

Example 1. apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

apd_dump_persistent_resources

(no version information, might be only in CVS)

apd_dump_persistent_resources -- Return all persistent resources as an array

Description

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Return Values

An array containing the current call stack.

Examples

Example 1. apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

See Also

apd_dump_regular()

apd_dump_regular_resources

(no version information, might be only in CVS)

apd_dump_regular_resources -- Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Return Values

An array containing the current regular resources.

Examples

Example 1. apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

apd_echo

(PECL)

apd_echo -- Echo to the debugging socket

Description

bool apd_echo ( string output )

Usually sent via the socket to request information about the running script.

Parameters

output

The debugged variable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. apd_echo() example

<?php
apd_echo($i);
?>

apd_get_active_symbols

(no version information, might be only in CVS)

apd_get_active_symbols -- Get an array of the current variables names in the local scope

Description

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Return Values

A multidimensional array with all the variables.

Examples

Example 1. apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

apd_set_pprof_trace

(PECL)

apd_set_pprof_trace -- Starts the session debugging

Description

string apd_set_pprof_trace ( [string dump_directory [, string fragment]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parameters

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment

Return Values

Returns path of the destination file.

Examples

Example 1. apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

apd_set_session_trace

(no version information, might be only in CVS)

apd_set_session_trace -- Starts the session debugging

Description

void apd_set_session_trace ( int debug_level [, string dump_directory] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

Return Values

No value is returned.

Examples

Example 1. apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

apd_set_session

(no version information, might be only in CVS)

apd_set_session -- Changes or sets the current debugging level

Description

void apd_set_session ( int debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

No value is returned.

Examples

Example 1. apd_set_session() example

<?php
apd_set_session(9);
?>

apd_set_socket_session_trace

(no version information, might be only in CVS)

apd_set_socket_session_trace -- Starts the remote session debugging

Description

bool apd_set_socket_session_trace ( string tcp_server, int socket_type, int port, int debug_level )

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

Parameters

tcp_server

IP or Unix Domain socket (like a file) of the TCP server.

socket_type

Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port

You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. apd_set_socket_session_trace() example

<?php
  apd_set_socket_session_trace("127.0.0.1",APD_AF_INET,7112,0);
?>

override_function

(PECL)

override_function -- Overrides built-in functions

Description

bool override_function ( string function_name, string function_args, string function_code )

Overrides built-in functions by replacing them in the symbol table.

Parameters

function_name

The function to override.

function_args

The function arguments, as a coma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code

The new code for the function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

rename_function

(PECL)

rename_function -- Renames orig_name to new_name in the global function table

Description

bool rename_function ( string original_name, string new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parameters

original_name

The original function name.

new_name

The new name for the original_name function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

V. Array Functions

Introduction

These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.

Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays.


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are always available as part of the PHP core.

CASE_LOWER (integer)

CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)

SORT_ASC is used with array_multisort() to sort in ascending order.

SORT_DESC (integer)

SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)

SORT_REGULAR is used to compare items normally.

SORT_NUMERIC (integer)

SORT_NUMERIC is used to compare items numerically.

SORT_STRING (integer)

SORT_STRING is used to compare items as strings.

SORT_LOCALE_STRING (integer)

SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2.

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

EXTR_REFS (integer)

Table of Contents
array_change_key_case -- Changes all keys in an array
array_chunk -- Split an array into chunks
array_combine -- Creates an array by using one array for keys and another for its values
array_count_values -- Counts all the values of an array
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff_key -- Computes the difference of arrays using keys for comparison
array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison
array_diff -- Computes the difference of arrays
array_fill_keys -- Fill an array with values, specifying keys
array_fill -- Fill an array with values
array_filter -- Filters elements of an array using a callback function
array_flip -- Exchanges all keys with their associated values in an array
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect_key -- Computes the intersection of arrays using keys for comparison
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect -- Computes the intersection of arrays
array_key_exists -- Checks if the given key or index exists in the array
array_keys -- Return all the keys of an array
array_map -- Applies the callback to the elements of the given arrays
array_merge_recursive -- Merge two or more arrays recursively
array_merge -- Merge one or more arrays
array_multisort -- Sort multiple or multi-dimensional arrays
array_pad -- Pad array to the specified length with a value
array_pop -- Pop the element off the end of array
array_product -- Calculate the product of values in an array
array_push -- Push one or more elements onto the end of array
array_rand -- Pick one or more random entries out of an array
array_reduce -- Iteratively reduce the array to a single value using a callback function
array_reverse -- Return an array with elements in reverse order
array_search -- Searches the array for a given value and returns the corresponding key if successful
array_shift -- Shift an element off the beginning of array
array_slice -- Extract a slice of the array
array_splice -- Remove a portion of the array and replace it with something else
array_sum -- Calculate the sum of values in an array
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function
array_udiff -- Computes the difference of arrays by using a callback function for data comparison
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
array_uintersect -- Computes the intersection of arrays, compares data by a callback function
array_unique -- Removes duplicate values from an array
array_unshift -- Prepend one or more elements to the beginning of an array
array_values -- Return all the values of an array
array_walk_recursive -- Apply a user function recursively to every member of an array
array_walk -- Apply a user function to every member of an array
array -- Create an array
arsort -- Sort an array in reverse order and maintain index association
asort -- Sort an array and maintain index association
compact -- Create array containing variables and their values
count -- Count elements in an array, or properties in an object
current -- Return the current element in an array
each -- Return the current key and value pair from an array and advance the array cursor
end -- Set the internal pointer of an array to its last element
extract -- Import variables into the current symbol table from an array
in_array -- Checks if a value exists in an array
key -- Fetch a key from an associative array
krsort -- Sort an array by key in reverse order
ksort -- Sort an array by key
list -- Assign variables as if they were an array
natcasesort -- Sort an array using a case insensitive "natural order" algorithm
natsort -- Sort an array using a "natural order" algorithm
next -- Advance the internal array pointer of an array
pos -- Alias of current()
prev -- Rewind the internal array pointer
range -- Create an array containing a range of elements
reset -- Set the internal pointer of an array to its first element
rsort -- Sort an array in reverse order
shuffle -- Shuffle an array
sizeof -- Alias of count()
sort -- Sort an array
uasort -- Sort an array with a user-defined comparison function and maintain index association
uksort -- Sort an array by keys using a user-defined comparison function
usort -- Sort an array by values using a user-defined comparison function

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case -- Changes all keys in an array

Description

array array_change_key_case ( array input [, int case] )

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

Parameters

input

The array to work on

case

Either CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or false if input is not an array.

Errors/Exceptions

Throws E_WARNING if input is not an array.

Examples

Example 1. array_change_key_case() example

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

The above example will output:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Notes

Note: If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices.

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk -- Split an array into chunks

Description

array array_chunk ( array input, int size [, bool preserve_keys] )

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Parameters

input

The array to work on

size

The size of each chunk

preserve_keys

When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions

If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

Example 1. array_chunk() example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_combine

(PHP 5)

array_combine -- Creates an array by using one array for keys and another for its values

Description

array array_combine ( array keys, array values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parameters

keys

Array of keys to be used

values

Array of values to be used

Return Values

Returns the combined array, FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Errors/Exceptions

Throws E_WARNING if keys and values are either empty or the number of elements does not match.

Examples

Example 1. A simple array_combine() example

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

The above example will output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

array_count_values

(PHP 4, PHP 5)

array_count_values -- Counts all the values of an array

Description

array array_count_values ( array input )

array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

Parameters

input

The array of values to count

Return Values

Returns an assosiative array of values from input as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or integer.

Examples

Example 1. array_count_values() example

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc -- Computes the difference of arrays with additional index check

Description

array array_diff_assoc ( array array1, array array2 [, array ...] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arrays.

Examples

Example 1. array_diff_assoc() example

In this example you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 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);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Example 2. array_diff_assoc() example

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 1
    )

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

array_diff_key

(PHP 5 >= 5.1.0RC1)

array_diff_key -- Computes the difference of arrays using keys for comparison

Description

array array_diff_key ( array array1, array array2 [, array ...] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example 1. array_diff_key() example

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

array_diff_uassoc

(PHP 5)

array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Description

array array_diff_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Unlike array_diff_assoc() an user supplied callback function is used for the indices comparision, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example 1. array_diff_uassoc() example

The "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

The equality of 2 indices is checked by the user supplied callback function.

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

array_diff_ukey

(PHP 5 >= 5.1.0RC1)

array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison

Description

array array_diff_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() an user supplied callback function is used for the indices comparision, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example 1. array_diff_ukey() example

<?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'));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff -- Computes the difference of arrays

Description

array array_diff ( array array1, array array2 [, array ...] )

Compares array1 against array2 and returns the difference.

Examples

Example 1. array_diff() example

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
    [1] => blue
)

Notes

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Note: 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]);.

Warning

This was broken in PHP 4.0.4!

array_fill_keys

(no version information, might be only in CVS)

array_fill_keys -- Fill an array with values, specifying keys

Description

array array_fill_keys ( array keys, mixed value )

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Parameters

keys

Array of values that will be used as keys

value

Either an string or an array of values

Return Values

Returns the filled array

Examples

Example 1. array_fill_keys() example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

The above example will output:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill -- Fill an array with values

Description

array array_fill ( int start_index, int num, mixed value )

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Parameters

start_index

The first index of the returned array

num

Number of elements to insert

value

Values to use filling

Return Values

Returns the filled array

Errors/Exceptions

Throws a E_WARNING if num is less than one.

Examples

Example 1. array_fill() example

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

The above example will output:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter -- Filters elements of an array using a callback function

Description

array array_filter ( array input [, callback callback] )

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

Parameters

input

The array to iterate over

callback

The callback function to use

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

Return Values

Returns the filtered array.

Examples

Example 1. array_filter() example

<?php
function odd($var)
{
    return($var & 1);
}

function even($var)
{
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

The above example will output:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Example 2. array_filter() without callback

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

The above example will output:

Array
(
    [0] => foo
    [2] => -1
)

Notes

Caution

If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined.

array_flip

(PHP 4, PHP 5)

array_flip -- Exchanges all keys with their associated values in an array

Description

array array_flip ( array trans )

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.

If a value has several occurrences, the latest key will be used as its values, and all others will be lost.

array_flip() returns FALSE if it fails.

Example 1. array_flip() example

<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>

Example 2. array_flip() example : collision

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

now $trans is:

Array
(
    [1] => b
    [2] => c
)

See also array_values(), array_keys(), and array_reverse().

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc -- Computes the intersection of arrays with additional index check

Description

array array_intersect_assoc ( array array1, array array2 [, array ...] )

array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

Example 1. array_intersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

The above example will output:

Array
(
    [a] => green
)

In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1.

The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.

See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc(), array_uintersect_uassoc(), array_diff() and array_diff_assoc().

array_intersect_key

(PHP 5 >= 5.1.0RC1)

array_intersect_key -- Computes the intersection of arrays using keys for comparison

Description

array array_intersect_key ( array array1, array array2 [, array ...] )

array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

Example 1. array_intersect_key() example

<?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));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

See also 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() and array_intersect_ukey().

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function

Description

array array_intersect_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Example 1. array_intersect_uassoc() example

<?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"));
?>

The above example will output:

Array
(
    [b] => brown
)

See also array_intersect(), array_intersect_assoc(), array_uintersect_assoc(), array_uintersect_uassoc(), array_intersect_key() and array_intersect_ukey().

array_intersect_ukey

(PHP 5 >= 5.1.0RC1)

array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison

Description

array array_intersect_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.

Example 1. array_intersect_ukey() example

<?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'));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

See also 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() and array_intersect_key().

array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect -- Computes the intersection of arrays

Description

array array_intersect ( array array1, array array2 [, array ...] )

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Example 1. array_intersect() example

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
)

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

See also array_intersect_assoc(), array_diff(), and array_diff_assoc().

array_key_exists

(PHP 4 >= 4.1.0, PHP 5)

array_key_exists -- Checks if the given key or index exists in the array

Description

bool array_key_exists ( mixed key, array search )

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index. array_key_exists() also works on objects.

Example 1. array_key_exists() example

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Note: The name of this function is key_exists() in PHP 4.0.6.

Example 2. array_key_exists() vs isset()

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

See also isset(), array_keys(), and in_array().

array_keys

(PHP 4, PHP 5)

array_keys -- Return all the keys of an array

Description

array array_keys ( array input [, mixed search_value [, bool strict]] )

array_keys() returns the keys, numeric and string, from the input array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. As of PHP 5, you can use strict parameter for comparison including type (===).

Example 1. array_keys() example

<?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));
?>

The above example will output:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

See also array_values() and array_key_exists().

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map -- Applies the callback to the elements of the given arrays

Description

array array_map ( callback callback, array arr1 [, array ...] )

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Example 1. array_map() example

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example 2. array_map() - using more arrays

<?php
function show_Spanish($n, $m)
{
    return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

The above example will output:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

Example 3. Creating an array of arrays

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The above example will output:

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
        )

)

See also array_filter(), array_reduce(), array_walk(), create_function(), and information about the callback type.

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive -- Merge two or more arrays recursively

Description

array array_merge_recursive ( array array1 [, array ...] )

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Example 1. array_merge_recursive() example

<?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);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

See also array_merge().

array_merge

(PHP 4, PHP 5)

array_merge -- Merge one or more arrays

Description

array array_merge ( array array1 [, array array2 [, array ...]] )

array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

Example 1. array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example 2. Simple array_merge() example

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to completely preserve the arrays and just want to append them to each other, use the + operator:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>

The numeric key will be preserved and thus the association remains.

Array
(
    [1] => data
)

Warning

The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge() now only accepts parameters of type array. However, you can use typecasting to merge other types. See the example below for details.

Example 3. array_merge() PHP 5 example

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

Array
(
    [0] => foo
    [1] => bar
)

See also array_merge_recursive(), array_combine() and array operators.

array_multisort

(PHP 4, PHP 5)

array_multisort -- Sort multiple or multi-dimensional arrays

Description

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )

Returns TRUE on success or FALSE on failure.

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.

The argument structure of this function is a bit unusual, but flexible. The first argument has to be an array. Subsequently, each argument can be either an array or a sorting flag from the following lists.

Sorting order flags:

  • SORT_ASC - Sort in ascending order

  • SORT_DESC - Sort in descending order

Sorting type flags:

  • SORT_REGULAR - Compare items normally

  • SORT_NUMERIC - Compare items numerically

  • SORT_STRING - Compare items as strings

No two sorting flags of the same type can be specified after each array. The sorting flags specified after an array argument apply only to that array - they are reset to default SORT_ASC and SORT_REGULAR before each new array argument.

Example 1. Sorting multiple arrays

<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain "10", "a", 100, 100. The second array will contain 1, 1, "2", 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(1)
  [1]=> int(1)
  [2]=> string(1) "2"
  [3]=> int(3)
}

Example 2. Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

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. Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data. This would usually, for example, be obtained by looping with 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);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example 4. Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original array.

<?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);
?>

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

array_pad

(PHP 4, PHP 5)

array_pad -- Pad array to the specified length with a value

Description

array array_pad ( array input, int pad_size, mixed pad_value )

array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place. It is possible to add most 1048576 elements at a time.

Example 1. array_pad() example

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

See also array_fill() and range().

array_pop

(PHP 4, PHP 5)

array_pop -- Pop the element off the end of array

Description

mixed array_pop ( array &array )

array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.

Note: This function will reset() the array pointer after use.

Example 1. array_pop() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

After this, $stack will have only 3 elements:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

and raspberry will be assigned to $fruit.

See also array_push(), array_shift(), and array_unshift().

array_product

(PHP 5 >= 5.1.0RC1)

array_product -- Calculate the product of values in an array

Description

number array_product ( array array )

array_product() returns the product of values in an array as an integer or float.

Example 1. array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>

The above example will output:

product(a) = 384

array_push

(PHP 4, PHP 5)

array_push -- Push one or more elements onto the end of array

Description

int array_push ( array &array, mixed var [, mixed ...] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
repeated for each var.

Returns the new number of elements in the array.

Example 1. array_push() example

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

The above example will output:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

See also array_pop(), array_shift(), and array_unshift().

array_rand

(PHP 4, PHP 5)

array_rand -- Pick one or more random entries out of an array

Description

mixed array_rand ( array input [, int num_req] )

array_rand() is rather useful when you want to pick one or more random entries out of an array. It takes an input array and an optional argument num_req which specifies how many entries you want to pick - if not specified, it defaults to 1.

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

Example 1. array_rand() example

<?php
srand((float) microtime() * 10000000);
$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";
?>

See also shuffle().

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce -- Iteratively reduce the array to a single value using a callback function

Description

mixed array_reduce ( array input, callback function [, int initial] )

array_reduce() applies iteratively the function function to the elements of the array input, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. If the array is empty and initial is not passed, array_reduce() returns NULL.

Example 1. array_reduce() example

<?php
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

function rmul($v, $w)
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

This will result in $b containing 15, $c containing 1200 (= 10*1*2*3*4*5), and $d containing 1.

See also array_filter(), array_map(), array_unique(), and array_count_values().

array_reverse

(PHP 4, PHP 5)

array_reverse -- Return an array with elements in reverse order

Description

array array_reverse ( array array [, bool preserve_keys] )

array_reverse() takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE.

Example 1. array_reverse() example

<?php
$input  = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?>

This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:

Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

Note: The second parameter was added in PHP 4.0.3.

See also array_flip().

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search -- Searches the array for a given value and returns the corresponding key if successful

Description

mixed array_search ( mixed needle, array haystack [, bool strict] )

Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.

If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Example 1. array_search() example

<?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;
?>

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See also array_keys(), array_values(), array_key_exists(), and in_array().

array_shift

(PHP 4, PHP 5)

array_shift -- Shift an element off the beginning of array

Description

mixed array_shift ( array &array )

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned.

Note: This function will reset() the array pointer after use.

Example 1. array_shift() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

This would result in $stack having 3 elements left:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

and orange will be assigned to $fruit.

See also array_unshift(), array_push(), and array_pop().

array_slice

(PHP 4, PHP 5)

array_slice -- Extract a slice of the array

Description

array array_slice ( array array, int offset [, int length [, bool preserve_keys]] )

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

Note that array_slice() will reorder and reset the array indices by default. Since PHP 5.0.2, you can change this behaviour by setting preserve_keys to TRUE.

Example 1. array_slice() examples

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

The above example will output:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

See also array_splice() and unset().

array_splice

(PHP 4, PHP 5)

array_splice -- Remove a portion of the array and replace it with something else

Description

array array_splice ( array &input, int offset [, int length [, array replacement]] )

array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. It returns an array containing the extracted elements. Note that numeric keys in input are not preserved.

If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.

If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Note that keys in replacement array are not preserved. If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.

The following statements change the values of $input the same way:

Table 1. array_splice() equivalents

array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y))
array_pop($input) array_splice($input, -1)
array_shift($input) array_splice($input, 0, 1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // for arrays where key equals offset array_splice($input, $x, 1, $y)

Returns the array consisting of removed elements.

Example 1. array_splice() examples

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

See also array_slice(), unset(), and array_merge().

array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum -- Calculate the sum of values in an array

Description

number array_sum ( array array )

array_sum() returns the sum of values in an array as an integer or float.

Example 1. array_sum() examples

<?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";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9

Note: PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which most of the time converted them to zero, depending on their value).

array_udiff_assoc

(PHP 5)

array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function

Description

array array_udiff_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.

Example 1. array_udiff_assoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

The above example will output:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Description

array array_udiff_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_udiff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.

Example 1. array_udiff_uassoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

The above example will output:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_udiff

(PHP 5)

array_udiff -- Computes the difference of arrays by using a callback function for data comparison

Description

array array_udiff ( array array1, array array2 [, array ..., callback data_compare_func] )

array_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved. For the comparison of the data data_compare_func is used. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff() which uses an internal function for comparing the data.

Example 1. array_udiff() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

The above example will output:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

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_udiff($array1[0], $array2[0], "data_compare_func");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function

Description

array array_uintersect_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_uintersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.

Example 1. array_uintersect_assoc() example

<?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"));
?>

The above example will output:

Array
(
    [a] => green
)

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

Description

array array_uintersect_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_uintersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). Both the data and the indexes are compared by using a callback functions.

Example 1. array_uintersect_uassoc() example

<?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"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
)

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_assoc().

array_uintersect

(PHP 5)

array_uintersect -- Computes the intersection of arrays, compares data by a callback function

Description

array array_uintersect ( array array1, array array2 [, array ..., callback data_compare_func] )

array_uintersect() returns an array containing all the values of array1 that are present in all the arguments. The data is compared by using a callback function.

Example 1. array_uintersect() example

<?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"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique -- Removes duplicate values from an array

Description

array array_unique ( array array )

array_unique() takes input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

The first element will be used.

Example 1. array_unique() example

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example 2. array_unique() and types

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

The above example will output:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

array_unshift

(PHP 4, PHP 5)

array_unshift -- Prepend one or more elements to the beginning of an array

Description

int array_unshift ( array &array, mixed var [, mixed ...] )

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Returns the new number of elements in the array.

Example 1. array_unshift() example

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

The above example will output:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

See also array_shift(), array_push(), and array_pop().

array_values

(PHP 4, PHP 5)

array_values -- Return all the values of an array

Description

array array_values ( array input )

array_values() returns all the values from the input array and indexes numerically the array.

Example 1. array_values() example

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

The above example will output:

Array
(
    [0] => XL
    [1] => gold
)

See also array_keys().

array_walk_recursive

(PHP 5)

array_walk_recursive -- Apply a user function recursively to every member of an array

Description

bool array_walk_recursive ( array &input, callback funcname [, mixed userdata] )

Applies the user-defined function funcname to each element of the input array. This function will recur into deeper arrays. Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

Returns TRUE on success or FALSE on failure.

Note: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

Example 1. array_walk_recursive() example

<?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');
?>

The above example will output:

a holds apple
b holds banana
sour holds lemon

You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.

See also array_walk(), and information about the callback type.

array_walk

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

array_walk -- Apply a user function to every member of an array

Description

bool array_walk ( array &array, callback funcname [, mixed userdata] )

Returns TRUE on success or FALSE on failure.

Applies the user-defined function funcname to each element of the array array. Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

If function funcname requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls funcname. These warnings may be suppressed by prepending the PHP error operator @ to the array_walk() call, or by using error_reporting().

Note: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

Note: Passing the key and userdata to funcname was added in 4.0.0

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Users may not change the array itself from the callback function. e.g. Add/delete elements, unset elements, etc. If the array that array_walk() is applied to is changed, the behavior of this function is undefined, and unpredictable.

Example 1. array_walk() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

The above example will output:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

See also array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array(), and array_map(), and information about the callback type.

array

(PHP 3, PHP 4, PHP 5)

array -- Create an array

Description

array array ( [mixed ...] )

Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.

Note: array() is a language construct used to represent literal arrays, and not a regular function.

Syntax "index => values", separated by commas, define index and values. index may be of type string or numeric. 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. Note that when two identical index are defined, the last overwrite the first.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example 1. array() example

<?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. Automatic index with array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example 3. 1-based index with array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.

Example 4. Accessing an array inside double quotes

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

See also array_pad(), list(), count(), foreach, and range().

arsort

(PHP 3, PHP 4, PHP 5)

arsort -- Sort an array in reverse order and maintain index association

Description

bool arsort ( array &array [, int sort_flags] )

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.

Returns TRUE on success or FALSE on failure.

Example 1. arsort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
d = lemon
b = banana
c = apple

The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also asort(), rsort(), ksort(), and sort().

asort

(PHP 3, PHP 4, PHP 5)

asort -- Sort an array and maintain index association

Description

bool asort ( array &array [, int sort_flags] )

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.

Returns TRUE on success or FALSE on failure.

Example 1. asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also arsort(), rsort(), ksort(), and sort().

compact

(PHP 4, PHP 5)

compact -- Create array containing variables and their values

Description

array compact ( mixed varname [, mixed ...] )

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.

Any strings that are not set will simply be skipped.

Gotcha: Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

Example 1. compact() example

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>

The above example will output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

See also extract().

count

(PHP 3, PHP 4, PHP 5)

count -- Count elements in an array, or properties in an object

Description

int count ( mixed var [, int mode] )

Returns the number of elements in var, which is typically an array, since anything else will have one element.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, count(), which returns the return value for the count() function.

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Note: The optional mode parameter is available as of PHP 4.2.0.

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0. count() does not detect infinite recursion.

Caution

count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.

Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Example 1. count() example

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Example 2. Recursive count() example (PHP >= 4.2.0)

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

See also is_array(), isset(), and strlen().

current

(PHP 3, PHP 4, PHP 5)

current -- Return the current element in an array

Description

mixed current ( array &array )

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

Example 1. Example use of current() and friends

<?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';
?>

See also end(), key(), next(), prev(), reset(), and each().

each

(PHP 3, PHP 4, PHP 5)

each -- Return the current key and value pair from an array and advance the array cursor

Description

array each ( array &array )

Returns the current key and value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

If the internal pointer for the array points past the end of the array contents, each() returns FALSE.

Example 1. each() examples

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() is typically used in conjunction with list() to traverse an array, here's an example:

Example 2. Traversing an array with each()

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

The above example will output:

a => apple
b => banana
c => cranberry

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

Caution

Because assigning an array to another variable resets the original arrays pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.

See also key(), list(), current(), reset(), next(), prev(), and foreach.

end

(PHP 3, PHP 4, PHP 5)

end -- Set the internal pointer of an array to its last element

Description

mixed end ( array &array )

end() advances array's internal pointer to the last element, and returns its value.

Example 1. A simple end() example

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

See also current(), each(), prev(), next() and reset().

extract

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

extract -- Import variables into the current symbol table from an array

Description

int extract ( array var_array [, int extract_type [, string prefix]] )

This function is used to import variables from an array into the current symbol table. It takes an associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_type and prefix parameters.

Note: Beginning with version 4.0.5, this function returns the number of variables extracted.

Note: EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS were introduced in version 4.2.0.

Note: EXTR_REFS was introduced in version 4.3.0.

extract() checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. The way invalid/numeric keys and collisions are treated is determined by the extract_type. It can be one of the following values:

EXTR_OVERWRITE

If there is a collision, overwrite the existing variable.

EXTR_SKIP

If there is a collision, don't overwrite the existing variable.

EXTR_PREFIX_SAME

If there is a collision, prefix the variable name with prefix.

EXTR_PREFIX_ALL

Prefix all variable names with prefix. Beginning with PHP 4.0.5, this includes numeric variables as well.

EXTR_PREFIX_INVALID

Only prefix invalid/numeric variable names with prefix. This flag was added in PHP 4.0.5.

EXTR_IF_EXISTS

Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example. This flag was added in PHP 4.2.0.

EXTR_PREFIX_IF_EXISTS

Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. This flag was added in PHP 4.2.0.

EXTR_REFS

Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the var_array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the extract_type. This flag was added in PHP 4.3.0.

If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.

Note that prefix is only required if extract_type is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

extract() returns the number of variables successfully imported into the symbol table.

Warning

Do not use extract() on untrusted data, like user-input ($_GET, ...). If you do, for example, if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().

Example 1. extract() example

<?php

/* Suppose that $var_array is an array returned from
   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";

?>

The above example will output:

blue, large, sphere, medium

The $size wasn't overwritten, because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.

You must use an associative array, a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

See also compact().

in_array

(PHP 4, PHP 5)

in_array -- Checks if a value exists in an array

Description

bool in_array ( mixed needle, array haystack [, bool strict] )

Searches haystack for needle and returns TRUE if it is found in the array, FALSE otherwise.

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

Note: In PHP versions before 4.2.0 needle was not allowed to be an array.

Example 1. in_array() example

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example 2. in_array() with strict example

<?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";
}
?>

The above example will output:

1.13 found with strict check

Example 3. in_array() with an array as 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";
}
?>

The above example will output:

'ph' was found
  'o' was found

See also array_search(), array_key_exists(), and isset().

key

(PHP 3, PHP 4, PHP 5)

key -- Fetch a key from an associative array

Description

mixed key ( array &array )

key() returns the index element of the current array position.

Example 1. key() example

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

See also current() and next().

krsort

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

krsort -- Sort an array by key in reverse order

Description

bool krsort ( array &array [, int sort_flags] )

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.

Example 1. krsort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

d = lemon
c = apple
b = banana
a = orange

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also asort(), arsort(), ksort(), sort(), natsort(), and rsort().

ksort

(PHP 3, PHP 4, PHP 5)

ksort -- Sort an array by key

Description

bool ksort ( array &array [, int sort_flags] )

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.

Example 1. ksort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
b = banana
c = apple
d = lemon

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also asort(), arsort(), krsort(), uksort(), sort(), natsort(), and rsort().

Note: The second parameter was added in PHP 4.

list

(PHP 3, PHP 4, PHP 5)

list -- Assign variables as if they were an array

Description

void list ( mixed varname, mixed ... )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.

Example 1. list() examples

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example 2. An example use of list()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php

$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

Warning

list() assigns the values starting with the right-most parameter. If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order.

Example 3. Using list() with array indices

<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

See also each(), array() and extract().

natcasesort

(PHP 4, PHP 5)

natcasesort -- Sort an array using a case insensitive "natural order" algorithm

Description

bool natcasesort ( array &array )

This function 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".

Returns TRUE on success or FALSE on failure.

natcasesort() is a case insensitive version of natsort().

Example 1. natcasesort() example

<?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);
?>

The above example will output:

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
)

For more information see: Martin Pool's Natural Order String Comparison page.

See also sort(), natsort(), strnatcmp(), and strnatcasecmp().

natsort

(PHP 4, PHP 5)

natsort -- Sort an array using a "natural order" algorithm

Description

bool natsort ( array &array )

This function 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 sort()) can be seen below:

Returns TRUE on success or FALSE on failure.

Example 1. natsort() example

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

The above example will output:

Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's Natural Order String Comparison page.

See also natcasesort(), strnatcmp(), and strnatcasecmp().

next

(PHP 3, PHP 4, PHP 5)

next -- Advance the internal array pointer of an array

Description

mixed next ( array &array )

Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

Example 1. Example use of next() and friends

<?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';
?>

See also current(), end(), prev(), reset(), and each().

pos

(PHP 3, PHP 4, PHP 5)

pos -- Alias of current()

Description

This function is an alias of: current()

prev

(PHP 3, PHP 4, PHP 5)

prev -- Rewind the internal array pointer

Description

mixed prev ( array &array )

Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Note: You won't be able to distinguish the beginning of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

Example 1. Example use of prev() and friends

<?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';
?>

See also current(), end(), next(), reset(), and each().

range

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

range -- Create an array containing a range of elements

Description

array range ( mixed low, mixed high [, number step] )

range() returns an array of elements from low to high, inclusive. If low > high, the sequence will be from high to low.

New parameter: The optional step parameter was added in 5.0.0.

If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.

Example 1. range() examples

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// The step parameter was introduced in 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Use of character sequences introduced in 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}
?>

Note: Prior to PHP 4.1.0, range() only generated incrementing integer arrays. Support for character sequences and decrementing arrays was added in 4.1.0. Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

Caution

In PHP versions 4.1.0 through 4.3.2, range() sees numeric strings as strings and not integers. Instead, they will be used for character sequences. For example, "4242" is treated as "4".

See also shuffle(), array_fill(), and foreach.

reset

(PHP 3, PHP 4, PHP 5)

reset -- Set the internal pointer of an array to its first element

Description

mixed reset ( array &array )

reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.

Example 1. reset() example

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

See also current(), each(), end(), next(), and prev().

rsort

(PHP 3, PHP 4, PHP 5)

rsort -- Sort an array in reverse order

Description

bool rsort ( array &array [, int sort_flags] )

This function sorts an array in reverse order (highest to lowest).

Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.

Returns TRUE on success or FALSE on failure.

Example 1. rsort() example

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

0 = orange
1 = lemon
2 = banana
3 = apple

The fruits have been sorted in reverse alphabetical order.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also arsort(), asort(), ksort(), krsort(), sort(), and usort().

shuffle

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

shuffle -- Shuffle an array

Description

bool shuffle ( array &array )

This function shuffles (randomizes the order of the elements in) an array.

Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.

Example 1. shuffle() example

<?php
$numbers = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

See also arsort(), asort(), ksort(), rsort(), sort(), and usort().

sizeof

(PHP 3, PHP 4, PHP 5)

sizeof -- Alias of count()

Description

This function is an alias of: count().

sort

(PHP 3, PHP 4, PHP 5)

sort -- Sort an array

Description

bool sort ( array &array [, int sort_flags] )

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.

Returns TRUE on success or FALSE on failure.

Example 1. sort() example

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

The fruits have been sorted in alphabetical order.

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)

  • SORT_NUMERIC - compare items numerically

  • SORT_STRING - compare items as strings

  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2. Before PHP 6, it uses the system locale, which can be changed using setlocale(). Since PHP 6, you must use the i18n_loc_set_default() function.

Note: The second parameter was added in PHP 4.

Warning

Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.

See also arsort(), asort(), ksort(), krsort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort().

uasort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uasort -- Sort an array with a user-defined comparison function and maintain index association

Description

bool uasort ( array &array, callback cmp_function )

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. The comparison function is user-defined.

Returns TRUE on success or FALSE on failure.

Note: Please see usort() and uksort() for examples of user-defined comparison functions.

See also usort(), uksort(), sort(), asort(), arsort(), ksort(), and rsort().

uksort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uksort -- Sort an array by keys using a user-defined comparison function

Description

bool uksort ( array &array, callback cmp_function )

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Function cmp_function should accept two parameters which will be filled by pairs of array keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Returns TRUE on success or FALSE on failure.

Example 1. uksort() example

<?php
function cmp($a, $b)
{
    $a = ereg_replace('^(a|an|the) ', '', $a);
    $b = ereg_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";
}
?>

The above example will output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

See also usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort(), and rsort().

usort

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

usort -- Sort an array by values using a user-defined comparison function

Description

bool usort ( array &array, callback cmp_function )

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Note: If two members compare as equal, their order in the sorted array is undefined. Up to PHP 4.0.6 the user defined functions would keep the original order for those elements, but with the new sort algorithm introduced with 4.1.0 this is no longer the case as there is no solution to do so in an efficient way.

Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.

Returns TRUE on success or FALSE on failure.

Example 1. usort() example

<?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";
}
?>

The above example will output:

0: 1
1: 2
2: 3
3: 5
4: 6

Note: Obviously in this trivial case the sort() function would be more appropriate.

Example 2. usort() example using multi-dimensional array

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.

The above example will output:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example 3. usort() example using a member function of an object

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

The above example will output:

b
c
d

See also uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort(), and rsort().

VI. Aspell functions [deprecated]

Introduction

The aspell() functions allows you to check the spelling on a word and offer suggestions.

Note: This extension has been removed from PHP and is no longer available as of PHP 4.3.0. If you want to use spell-checking capabilities in PHP, use pspell instead. It uses pspell library and works with newer versions of aspell.


Requirements

aspell works only with very old (up to .27.* or so) versions of aspell library. Neither this module, nor those versions of aspell library are supported any longer. You need the aspell library, available from: http://aspell.sourceforge.net/.


Installation

In PHP 4, these functions are only available if PHP was configured with --with-aspell=[DIR].


See Also

See also pspell.

Table of Contents
aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]
aspell_check -- Check a word [deprecated]
aspell_new -- Load a new dictionary [deprecated]
aspell_suggest -- Suggest spellings of a word [deprecated]

aspell_check_raw

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]

Description

bool aspell_check_raw ( int dictionary_link, string word )

aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way.

Parameters

dictionary_link

The dictionnary link identifier returned by aspell_new().

word

The tested word.

Return Values

Returns TRUE if the spelling is correct, FALSE if not.

Examples

Example 1. aspell_check_raw() Example

<?php

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?>

See Also

aspell_check()

aspell_check

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_check -- Check a word [deprecated]

Description

bool aspell_check ( int dictionary_link, string word )

aspell_check() checks the spelling of a word.

Parameters

dictionary_link

The dictionnary link identifier returned by aspell_new().

word

The tested word.

Return Values

Returns TRUE if the spelling is correct, FALSE if not.

Examples

Example 1. aspell_check() Example

<?php

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?>

aspell_new

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_new -- Load a new dictionary [deprecated]

Description

int aspell_new ( string master [, string personal] )

aspell_new() opens up a new dictionary for use with the other aspell functions.

Parameters

master

Language.

personal

Default to empty string.

Return Values

Returns a dictionary link identifier or FALSE on error.

Examples

Example 1. aspell_new() Example

<?php
$aspell_link = aspell_new("english");
?>

aspell_suggest

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_suggest -- Suggest spellings of a word [deprecated]

Description

array aspell_suggest ( int dictionary_link, string word )

aspell_suggest() suggest spellings for the given word.

Parameters

dictionary_link

The dictionnary link identifier returned by aspell_new().

word

The tested word.

Return Values

Returns an array of suggestions.

Examples

Example 1. aspell_suggest() Example

<?php

$aspell_link = aspell_new("english");

if (!aspell_check($aspell_link, "test")) {
    $suggestions = aspell_suggest($aspell_link, "test");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />\n"; 
    }
}

?>

VII. BCMath Arbitrary Precision Mathematics Functions

Introduction

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.


Requirements

Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.


Installation

These functions are only available if PHP was configured with --enable-bcmath. In PHP 3, these functions are only available if PHP was not configured with --disable-bcmath.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. BC math configuration options

NameDefaultChangeableChangelog
bcmath.scale"0"PHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

bcmath.scale integer

Number of decimal digits for all bcmath functions. See also bcscale().


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.

Table of Contents
bcadd -- Add two arbitrary precision numbers
bccomp -- Compare two arbitrary precision numbers
bcdiv -- Divide two arbitrary precision numbers
bcmod -- Get modulus of an arbitrary precision number
bcmul -- Multiply two arbitrary precision number
bcpow -- Raise an arbitrary precision number to another
bcpowmod -- Raise an arbitrary precision number to another, reduced by a specified modulus
bcscale -- Set default scale parameter for all bc math functions
bcsqrt -- Get the square root of an arbitrary precision number
bcsub -- Subtract one arbitrary precision number from another

bcadd

(PHP 3, PHP 4, PHP 5)

bcadd -- Add two arbitrary precision numbers

Description

string bcadd ( string left_operand, string right_operand [, int scale] )

Sums left_operand and right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The sum of the two operands, as a string.

Examples

Example 1. bcadd() example

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

See Also

bcsub()

bccomp

(PHP 3, PHP 4, PHP 5)

bccomp -- Compare two arbitrary precision numbers

Description

int bccomp ( string left_operand, string right_operand [, int scale] )

Compares the left_operand to the right_operand and returns the result as an integer.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Return Values

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

Examples

Example 1. bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

bcdiv

(PHP 3, PHP 4, PHP 5)

bcdiv -- Divide two arbitrary precision numbers

Description

string bcdiv ( string left_operand, string right_operand [, int scale] )

Divides the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result of the division as a string, or NULL if right_operand is 0.

Examples

Example 1. bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

See Also

bcmul()

bcmod

(PHP 3, PHP 4, PHP 5)

bcmod -- Get modulus of an arbitrary precision number

Description

string bcmod ( string left_operand, string modulus )

Get the modulus of the left_operand using modulus.

Parameters

left_operand

The left operand, as a string.

modulus

The modulus, as a string.

Return Values

Returns the modulus as a string, or NULL if modulus is 0.

Examples

Example 1. bcmod() example

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

See Also

bcdiv()

bcmul

(PHP 3, PHP 4, PHP 5)

bcmul -- Multiply two arbitrary precision number

Description

string bcmul ( string left_operand, string right_operand [, int scale] )

Multiply the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example 1. bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

See Also

bcdiv()

bcpow

(PHP 3, PHP 4, PHP 5)

bcpow -- Raise an arbitrary precision number to another

Description

string bcpow ( string left_operand, string right_operand [, int scale] )

Raise left_operand to the power right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example 1. bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

bcpowmod

(PHP 5)

bcpowmod -- Raise an arbitrary precision number to another, reduced by a specified modulus

Description

string bcpowmod ( string left_operand, string right_operand, string modulus [, int scale] )

Use the fast-exponentiation method to raise left_operand to the power right_operand with respect to the modulus modulus.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

modulus

The modulus, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string, or NULL if modulus is 0.

Notes

Note: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

Examples

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.

?>

See Also

bcpow()
bcmod()

bcscale

(PHP 3, PHP 4, PHP 5)

bcscale -- Set default scale parameter for all bc math functions

Description

bool bcscale ( int scale )

Sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.

Parameters

scale

The scale factor.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcscale() example

<?php

// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>

bcsqrt

(PHP 3, PHP 4, PHP 5)

bcsqrt -- Get the square root of an arbitrary precision number

Description

string bcsqrt ( string operand [, int scale] )

Return the square root of the operand.

Parameters

operand

The operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the square root as a string, or NULL if operand is negative.

Examples

Example 1. bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

See Also

bcpow()

bcsub

(PHP 3, PHP 4, PHP 5)

bcsub -- Subtract one arbitrary precision number from another

Description

string bcsub ( string left_operand, string right_operand [, int scale] )

Subtracts the right_operand from the left_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The result of the substraction, as a string.

Examples

Example 1. bcsub() example

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

See Also

bcadd()

VIII. PHP bytecode Compiler

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Bcompiler was written for several reasons:

To encode entire script in a proprietary PHP application
To encode some classes and/or functions in a proprietary PHP application
To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
To do the feasibility study for a PHP to C converter

The first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.

The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.

To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.

bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...

In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.


Installation

short installation note:

  • You need at least PHP 4.3.0 for the compression to work

  • To install on PHP 4.3.0 and later at the Unix command prompt type pear install bcompiler

  • To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)

  • To install on older versions you need to make some slight changes to the build.

  • untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL http://pecl.php.net/get/bcompiler)

  • If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).

  • If you are using versions before PHP 4.3.0, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.

  • run phpize in ext/bcompiler

  • run ./buildconf in php4

  • run configure with --enable-bcompiler (and your other options)

  • make; make install

  • that's it.


Contact Information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at alan_k@php.net. Any help is very welcome.

Table of Contents
bcompiler_load_exe -- Reads and creates classes from a bcompiler exe file
bcompiler_load -- Reads and creates classes from a bz compressed file
bcompiler_parse_class -- Reads the bytecodes of a class and calls back to a user function
bcompiler_read -- Reads and creates classes from a filehandle
bcompiler_write_class -- Writes an defined class as bytecodes
bcompiler_write_constant -- Writes a defined constant as bytecodes
bcompiler_write_exe_footer -- Writes the start pos, and sig to the end of a exe type file
bcompiler_write_file -- Writes a php source file as bytecodes
bcompiler_write_footer -- Writes the single character \x00 to indicate End of compiled data
bcompiler_write_function -- Writes an defined function as bytecodes
bcompiler_write_functions_from_file -- Writes all functions defined in a file as bytecodes
bcompiler_write_header -- Writes the bcompiler header
bcompiler_write_included_filename -- Writes an included file as bytecodes

bcompiler_load_exe

(PECL)

bcompiler_load_exe -- Reads and creates classes from a bcompiler exe file

Description

bool bcompiler_load_exe ( string filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parameters

filename

The exe file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_load() example

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_load

(PECL)

bcompiler_load -- Reads and creates classes from a bz compressed file

Description

bool bcompiler_load ( string filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parameters

filename

The bzcompressed file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.

bcompiler_parse_class

(PECL)

bcompiler_parse_class -- Reads the bytecodes of a class and calls back to a user function

Description

bool bcompiler_parse_class ( string class, string callback )

Reads the bytecodes of a class and calls back to a user function.

Parameters

class

The class name, as a string.

callback

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Note: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.

bcompiler_read

(PECL)

bcompiler_read -- Reads and creates classes from a filehandle

Description

bool bcompiler_read ( resource filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.

bcompiler_write_class

(PECL)

bcompiler_write_class -- Writes an defined class as bytecodes

Description

bool bcompiler_write_class ( resource filehandle, string className [, string extends] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Note: This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

bcompiler_write_constant

(PECL)

bcompiler_write_constant -- Writes a defined constant as bytecodes

Description

bool bcompiler_write_constant ( resource filehandle, string constantName )

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_exe_footer

(PECL)

bcompiler_write_exe_footer -- Writes the start pos, and sig to the end of a exe type file

Description

bool bcompiler_write_exe_footer ( resource filehandle, int startpos )

An EXE (or self executable) file consists of 3 parts:

The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main)
The Bytecodes (uncompressed only for the moment)
The bcompiler EXE footer

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Parameters

filehandle

A file handle as returned by fopen().

startpos

The file position at which the Bytecodes start, and can be obtained using ftell().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_footer() example

<?php

/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");

/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);

/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);

/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);

/* closing the output file */
fclose($fh);
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_file

(PECL)

bcompiler_write_file -- Writes a php source file as bytecodes

Description

bool bcompiler_write_file ( resource filehandle, string filename )

This function complies specified source file into bytecodes, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_footer

(PECL)

bcompiler_write_footer -- Writes the single character \x00 to indicate End of compiled data

Description

bool bcompiler_write_footer ( resource filehandle )

Writes the single character \x00 to indicate End of compiled data.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_footer() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_function

(PECL)

bcompiler_write_function -- Writes an defined function as bytecodes

Description

bool bcompiler_write_function ( resource filehandle, string functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parameters

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_functions_from_file

(PECL)

bcompiler_write_functions_from_file -- Writes all functions defined in a file as bytecodes

Description

bool bcompiler_write_functions_from_file ( resource filehandle, string fileName )

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_header

(PECL)

bcompiler_write_header -- Writes the bcompiler header

Description

bool bcompiler_write_header ( resource filehandle [, string write_ver] )

Writes the header part of a bcompiler file.

Parameters

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

bcompiler_write_included_filename

(PECL)

bcompiler_write_included_filename -- Writes an included file as bytecodes

Description

bool bcompiler_write_included_filename ( resource filehandle, string filename )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

IX. Bzip2 Compression Functions

Introduction

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.


Requirements

This module uses the functions of the bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.


Installation

Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2[=DIR] configuration option when compiling PHP to enable bzip2 support.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension defines one resource type: a file pointer identifying the bz2-file to work on.


Predefined Constants

This extension has no constants defined.


Examples

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

Example 1. Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
echo bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.  
echo bzread($bz);

bzclose($bz);

?>
Table of Contents
bzclose -- Close a bzip2 file
bzcompress -- Compress a string into bzip2 encoded data
bzdecompress -- Decompresses bzip2 encoded data
bzerrno -- Returns a bzip2 error number
bzerror --  Returns the bzip2 error number and error string in an array
bzerrstr -- Returns a bzip2 error string
bzflush -- Force a write of all buffered data
bzopen -- Opens a bzip2 compressed file
bzread -- Binary safe bzip2 file read
bzwrite -- Binary safe bzip2 file write

bzclose

(PHP 4 >= 4.3.3, PHP 5)

bzclose -- Close a bzip2 file

Description

int bzclose ( resource bz )

Closes the given bzip2 file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

bzopen()

bzcompress

(PHP 4 >= 4.3.3, PHP 5)

bzcompress -- Compress a string into bzip2 encoded data

Description

mixed bzcompress ( string source [, int blocksize [, int workfactor]] )

bzcompress() compresses the given string and returns it as bzip2 encoded data.

Parameters

source

The string to compress.

blocksize

Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so. blocksize defaults to 4.

workfactor

Controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case and 30 being the default value.

Regardless of the workfactor, the generated output is the same.

Return Values

The compressed string or number of error in case of error.

Examples

Example 1. Compressing data

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

See Also

bzdecompress()

bzdecompress

(PHP 4 >= 4.3.3, PHP 5)

bzdecompress -- Decompresses bzip2 encoded data

Description

mixed bzdecompress ( string source [, int small] )

bzdecompress() decompresses the given string containing bzip2 encoded data.

Parameters

source

The string to decompress.

small

If TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.

See the bzip2 documentation for more information about this feature.

Return Values

The decompressed string or number of error in case of error.

Examples

Example 1. Decompressing a String

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>

See Also

bzcompress()

bzerrno

(PHP 4 >= 4.3.3, PHP 5)

bzerrno -- Returns a bzip2 error number

Description

int bzerrno ( resource bz )

Returns the error number of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns the error number as an integer.

bzerror

(PHP 4 >= 4.3.3, PHP 5)

bzerror --  Returns the bzip2 error number and error string in an array

Description

array bzerror ( resource bz )

Returns the error number and error string of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

Examples

Example 1. bzerror() example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

bzerrstr

(PHP 4 >= 4.3.3, PHP 5)

bzerrstr -- Returns a bzip2 error string

Description

string bzerrstr ( resource bz )

Gets the error string of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns a string containing the error message.

bzflush

(PHP 4 >= 4.3.3, PHP 5)

bzflush -- Force a write of all buffered data

Description

int bzflush ( resource bz )

Forces a write of all buffered bzip2 data for the file pointer bz.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns TRUE on success or FALSE on failure.

bzopen

(PHP 4 >= 4.3.3, PHP 5)

bzopen -- Opens a bzip2 compressed file

Description

resource bzopen ( string filename, string mode )

bzopen() opens a bzip2 (.bz2) file for reading or writing.

Parameters

filename

The name of the file to open.

mode

Similar to the fopen() function ('r' for read, 'w' for write, etc.).

Return Values

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

Examples

Example 1. bzopen() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

See Also

bzclose()

bzread

(PHP 4 >= 4.3.3, PHP 5)

bzread -- Binary safe bzip2 file read

Description

string bzread ( resource bz [, int length] )

bzread() reads from the given bzip2 file pointer.

Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

length

If not specified, bzread() will read 1024 (uncompressed) bytes at a time.

Return Values

Returns the uncompressed data, or FALSE on error.

Examples

Example 1. bzread() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
  $decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

bzwrite

(PHP 4 >= 4.3.3, PHP 5)

bzwrite -- Binary safe bzip2 file write

Description

int bzwrite ( resource bz, string data [, int length] )

bzwrite() writes a string into the given bzip2 file stream.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

data

The written data.

length

If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written, or FALSE on error.

Examples

Example 1. bzwrite() example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

X. Calendar Functions

Introduction

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.


Installation

To get these functions to work, you have to compile PHP with --enable-calendar.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

The following constants are available since PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)

CAL_JEWISH_ADD_ALAFIM (integer)

CAL_JEWISH_ADD_GERESHAYIM (integer)

Table of Contents
cal_days_in_month -- Return the number of days in a month for a given year and calendar
cal_from_jd -- Converts from Julian Day Count to a supported calendar
cal_info -- Returns information about a particular calendar
cal_to_jd -- Converts from a supported calendar to Julian Day Count
easter_date -- Get Unix timestamp for midnight on Easter of a given year
easter_days -- Get number of days after March 21 on which Easter falls for a given year
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Count
GregorianToJD -- Converts a Gregorian date to Julian Day Count
JDDayOfWeek -- Returns the day of the week
JDMonthName -- Returns a month name
JDToFrench -- Converts a Julian Day Count to the French Republican Calendar
JDToGregorian -- Converts Julian Day Count to Gregorian date
jdtojewish -- Converts a Julian day count to a Jewish calendar date
JDToJulian -- Converts a Julian Day Count to a Julian Calendar Date
jdtounix -- Convert Julian Day to Unix timestamp
JewishToJD -- Converts a date in the Jewish Calendar to Julian Day Count
JulianToJD -- Converts a Julian Calendar date to Julian Day Count
unixtojd -- Convert Unix timestamp to Julian Day

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month -- Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int calendar, int month, int year )

This function will return the number of days in the month of year for the specified calendar.

Parameters

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Return Values

The length in days of the selected month in the given calendar

Examples

Example 1. cal_days_in_month() example

<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd -- Converts from Julian Day Count to a supported calendar

Description

array cal_from_jd ( int jd, int calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

jd

Julian day as integer

calendar

Calendar to convert to

Return Values

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

Examples

Example 1. cal_from_jd() example

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

The above example will output:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( [int calendar] )

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar

  • 1 or CAL_JULIAN - Julian Calendar

  • 2 or CAL_JEWISH - Jewish Calendar

  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parameters

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Return Values

ChangeLog

VersionDescription
Since 5.0 The calendar parameter becomes optional and defaults to "all calendars" if omitted.

Examples

Example 1. cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

The above example will output:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

Return Values

A Julian Day number.

easter_date

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_date -- Get Unix timestamp for midnight on Easter of a given year

Description

int easter_date ( [int year] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Warning

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parameters

year

The year as a number between 1970 an 2037

Return Values

The easter date as a unix timestamp.

ChangeLog

VersionDescription
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.

Examples

Example 1. easter_date() example

<?php

echo date("M-d-Y", easter_date(1999));        // Apr-04-1999
echo date("M-d-Y", easter_date(2000));        // Apr-23-2000
echo date("M-d-Y", easter_date(2001));        // Apr-15-2001

?>

See Also

easter_days() for calculating Easter before 1970 or after 2037

See Also

easter_days()

easter_days

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_days -- Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ( [int year [, int method]] )

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parameters

year

The year as a number between 1970 an 2037

Return Values

The number of days after March 21st that the Easter Sunday is in the given year.

ChangeLog

VersionDescription
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.
Since 4.3.0 The method parameter was introduced and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Examples

Example 1. easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

See Also

easter_date()

FrenchToJD

(PHP 3, PHP 4, PHP 5)

FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int month, int day, int year )

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

Parameters

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

Return Values

The julian day for the given french revolution date as an integer.

GregorianToJD

(PHP 3, PHP 4, PHP 5)

GregorianToJD -- Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int month, int day, int year )

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4714 and 9999

Return Values

The julian day for the given gregorian date as an integer.

Examples

Example 1. Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

JDDayOfWeek

(PHP 3, PHP 4, PHP 5)

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek ( int julianday [, int mode] )

Returns the day of the week. Can return a string or an integer depending on the mode.

Parameters

julianday

A julian day number as integer

mode

Table 1. Calendar week modes

ModeMeaning
0 (Default) Return the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Return a string containing the abbreviated day of week (English-Gregorian)

Return Values

The gregorian weekday as either an integer or string.

JDMonthName

(PHP 3, PHP 4, PHP 5)

JDMonthName -- Returns a month name

Description

string jdmonthname ( int julianday, int mode )

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Table 1. Calendar modes

ModeMeaningValues
0Gregorian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1GregorianJanuary, February, March, April, May, June, July, August, September, October, November, December
2Julian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3JulianJanuary, February, March, April, May, June, July, August, September, October, November, December
4JewishTishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5French RepublicanVendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

Parameters

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

Return Values

The month name for the given Julian Day and calendar.

JDToFrench

(PHP 3, PHP 4, PHP 5)

JDToFrench -- Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

Parameters

julianday

A julian day number as integer

Return Values

The french revolution date as a string in the form "month/day/year"

JDToGregorian

(PHP 3, PHP 4, PHP 5)

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The gregorian date as a string in the form "month/day/year"

jdtojewish

(PHP 3, PHP 4, PHP 5)

jdtojewish -- Converts a Julian day count to a Jewish calendar date

Description

string jdtojewish ( int juliandaycount [, bool hebrew [, int fl]] )

Converts a Julian Day Count to the Jewish Calendar.

Parameters

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format.

fl

The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

Return Values

The jewish date as a string in the form "month/day/year"

ChangeLog

VersionDescription
5.0.0 The hebrew and fl parameters were added

Examples

Example 1. jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH); 
?>

JDToJulian

(PHP 3, PHP 4, PHP 5)

JDToJulian -- Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The julian date as a string in the form "month/day/year"

jdtounix

(PHP 4, PHP 5)

jdtounix -- Convert Julian Day to Unix timestamp

Description

int jdtounix ( int jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

Parameters

jday

A julian day number between 2440588 and 2465342.

Return Values

The unix timestamp for the start of the given julian day.

See Also

unixtojd()

JewishToJD

(PHP 3, PHP 4, PHP 5)

JewishToJD -- Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int month, int day, int year )

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

Parameters

month

The month as a number from 1 to 13

day

The day as a number from 1 to 30

year

The year as a number between 1 and 9999

Return Values

The julian day for the given jewish date as an integer.

JulianToJD

(PHP 3, PHP 4, PHP 5)

JulianToJD -- Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int month, int day, int year )

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

Return Values

The julian day for the given julian date as an integer.

unixtojd

(PHP 4, PHP 5)

unixtojd -- Convert Unix timestamp to Julian Day

Description

int unixtojd ( [int timestamp] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

Parameters

timestamp

A unix timestamp to convert.

Return Values

A julian day number as integer.

See Also

jdtounix()

XI. CCVS API Functions [deprecated]

Introduction

These functions interface the CCVS API, allowing you to work directly with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.

Note: CCVS has been discontinued by Red Hat and there are no plans to issue further keys or support contracts. Those looking for a replacement can consider MCVE by Main Street Softworks as a potential replacement. It is similar in design and has documented PHP support!

This extension has been removed from PHP and is no longer available as of PHP 4.3.0. If you want to use credit card processing features you can use MCVE instead.


Installation

To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=[DIR], where DIR is the path to your CCVS installation. Please note that CCVS support requires that DIR/lib and DIR/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.

Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)


See Also

RedHat has discontinued support for CCVS; however, a slightly outdated manual is still available at http://www.redhat.com/docs/manuals/ccvs/.

Table of Contents
ccvs_add -- Add data to a transaction
ccvs_auth -- Perform credit authorization test on a transaction
ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API
ccvs_count --  Find out how many transactions of a given type are stored in the system
ccvs_delete -- Delete a transaction
ccvs_done -- Terminate CCVS engine and do cleanup work
ccvs_init -- Initialize CCVS for use
ccvs_lookup --  Look up an item of a particular type in the database #
ccvs_new -- Create a new, blank transaction
ccvs_report -- Return the status of the background communication process
ccvs_return --  Transfer funds from the merchant to the credit card holder
ccvs_reverse --  Perform a full reversal on an already-processed authorization
ccvs_sale --  Transfer funds from the credit card holder to the merchant
ccvs_status -- Check the status of an invoice
ccvs_textvalue -- Get text return value for previous function call
ccvs_void --  Perform a full reversal on a completed transaction

ccvs_add

(4.0.2 - 4.2.3 only)

ccvs_add -- Add data to a transaction

Description

string ccvs_add ( string session, string invoice, string argtype, string argval )

Warning

This function is currently not documented; only the argument list is available.

ccvs_auth

(4.0.2 - 4.2.3 only)

ccvs_auth -- Perform credit authorization test on a transaction

Description

string ccvs_auth ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_command

(4.0.2 - 4.2.3 only)

ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

Description

string ccvs_command ( string session, string type, string argval )

Warning

This function is currently not documented; only the argument list is available.

ccvs_count

(4.0.2 - 4.2.3 only)

ccvs_count --  Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string session, string type )

Warning

This function is currently not documented; only the argument list is available.

ccvs_delete

(4.0.2 - 4.2.3 only)

ccvs_delete -- Delete a transaction

Description

string ccvs_delete ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_done

(4.0.2 - 4.2.3 only)

ccvs_done -- Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string sess )

Warning

This function is currently not documented; only the argument list is available.

ccvs_init

(4.0.2 - 4.2.3 only)

ccvs_init -- Initialize CCVS for use

Description

string ccvs_init ( string name )

Warning

This function is currently not documented; only the argument list is available.

ccvs_lookup

(4.0.2 - 4.2.3 only)

ccvs_lookup --  Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string session, string invoice, int inum )

Warning

This function is currently not documented; only the argument list is available.

ccvs_new

(4.0.2 - 4.2.3 only)

ccvs_new -- Create a new, blank transaction

Description

string ccvs_new ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_report

(4.0.2 - 4.2.3 only)

ccvs_report -- Return the status of the background communication process

Description

string ccvs_report ( string session, string type )

Warning

This function is currently not documented; only the argument list is available.

ccvs_return

(4.0.2 - 4.2.3 only)

ccvs_return --  Transfer funds from the merchant to the credit card holder

Description

string ccvs_return ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_reverse

(4.0.2 - 4.2.3 only)

ccvs_reverse --  Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_sale

(4.0.2 - 4.2.3 only)

ccvs_sale --  Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_status

(4.0.2 - 4.2.3 only)

ccvs_status -- Check the status of an invoice

Description

string ccvs_status ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

ccvs_textvalue

(4.0.2 - 4.2.3 only)

ccvs_textvalue -- Get text return value for previous function call

Description

string ccvs_textvalue ( string session )

Warning

This function is currently not documented; only the argument list is available.

ccvs_void

(4.0.2 - 4.2.3 only)

ccvs_void --  Perform a full reversal on a completed transaction

Description

string ccvs_void ( string session, string invoice )

Warning

This function is currently not documented; only the argument list is available.

XII. Class/Object Functions

Introduction

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which an object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.


Examples

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Example 1. classes.inc

<?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable($edible, $color="green") 
    {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible() 
    {
        return $this->edible;
    }

    function what_color() 
    {
        return $this->color;
    }
    
} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach() 
    {
        $this->Vegetable(true, "green");
    }

    function cook_it() 
    {
        $this->cooked = true;
    }

    function is_cooked() 
    {
        return $this->cooked;
    }
    
} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Example 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj) 
{
    foreach (get_object_vars($obj) as $prop => $val) {
        echo "\t$prop = $val\n";
    }
}

function print_methods($obj) 
{
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method) {
        echo "\tfunction $method()\n";
    }
}

function class_parentage($obj, $class) 
{
    if (is_subclass_of($GLOBALS[$obj], $class)) {
        echo "Object $obj belongs to class " . get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

Table of Contents
call_user_method_array -- Call a user method given with an array of parameters [deprecated]
call_user_method -- Call a user method on an specific object [deprecated]
class_exists -- Checks if the class has been defined
get_class_methods -- Gets the class methods' names
get_class_vars -- Get the default properties of the class
get_class -- Returns the name of the class of an object
get_declared_classes -- Returns an array with the name of the defined classes
get_declared_interfaces -- Returns an array of all declared interfaces
get_object_vars -- Gets the properties of the given object
get_parent_class -- Retrieves the parent class name for object or class
interface_exists -- Checks if the interface has been defined
is_a -- Checks if the object is of this class or has this class as one of its parents
is_subclass_of -- Checks if the object has this class as one of its parents
method_exists -- Checks if the class method exists
property_exists --  Checks if the object or class has a property

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array -- Call a user method given with an array of parameters [deprecated]

Description

mixed call_user_method_array ( string method_name, object &obj, array paramarr )

Warning

The call_user_method_array() function is deprecated as of PHP 4.1.0, use the call_user_func_array() variety with the array(&$obj, "method_name") syntax instead.

call_user_method

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

call_user_method -- Call a user method on an specific object [deprecated]

Description

mixed call_user_method ( string method_name, object &obj [, mixed parameter [, mixed ...]] )

Warning

The call_user_method() function is deprecated as of PHP 4.1.0, use the call_user_func() variety with the array(&$obj, "method_name") syntax instead.

class_exists

(PHP 4, PHP 5)

class_exists -- Checks if the class has been defined

Description

bool class_exists ( string class_name [, bool autoload] )

This function checks if the given class have been defined.

Parameters

class_name

The class name

autoload

Whether to call __autoload or not by default

Return Values

Returns TRUE if class_name is a defined class, FALSE otherwise.

ChangeLog

VersionDescription
5.0.0 The autoload was added.

Examples

Example 1. class_exists() example

<?php
// Check the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Example 2. autoload parameter example

<?php
function __autoload($class)
{
    include($class . '.php');

    // Check to see if the include declared the class
    if (!class_exists($class, false)) {
        trigger_error("Unable to load class: $class", E_USER_WARNING);
    }
}

if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

get_class_methods

(PHP 4, PHP 5)

get_class_methods -- Gets the class methods' names

Description

array get_class_methods ( mixed class_name )

Gets the class methods names.

Parameters

class_name

The class name or an object instance

Return Values

Returns an array of method names defined for the class specified by class_name. In case of an error, it returns NULL.

ChangeLog

VersionDescription
5.0.0 As of PHP 5, this function returns the name of the methods as they were declared (case-sensitive). In PHP 4 they were lowercased.
4.0.6 The ability of specifying the object itself has been added.

Examples

Example 1. get_class_methods() example

<?php

class myclass {
    // constructor
    function myclass()
    {
        return(true);
    }

    // method 1
    function myfunc1()
    {
        return(true);
    }

    // method 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

The above example will output:

myclass
myfunc1
myfunc2

get_class_vars

(PHP 4, PHP 5)

get_class_vars -- Get the default properties of the class

Description

array get_class_vars ( string class_name )

Get the default properties of the given class.

Parameters

class_name

The class name

Return Values

Returns an associative array of default public properties of the class. The resulting array elements are in the form of varname => value.

ChangeLog

VersionDescription
Prior to 4.2.0 Uninitialized class variables will not be reported by get_class_vars()

Examples

Example 1. get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5

    // constructor
    function myclass() {
        // 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";
}

?>

The above example will output:

// Before PHP 4.2.0
var2 : xyz
var3 : 100

// As of PHP 4.2.0
var1 :
var2 : xyz
var3 : 100

get_class

(PHP 4, PHP 5)

get_class -- Returns the name of the class of an object

Description

string get_class ( [object object] )

Gets the name of the class of the given object.

Parameters

object

The tested object

Return Values

Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.

ChangeLog

VersionDescription
Since 5.0.0 The class name is returned in it's original notation.
Since 5.0.0 The object parameter is optional if called from the object's method.

Examples

Example 1. Using get_class()

<?php

class foo {
    function foo()
    {
    // implements some logic
    }

    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}

// create an object
$bar = new foo();

// external call
echo "Its name is " , get_class($bar) , "\n";

// internal call
$bar->name();

?>

The above example will output:

Its name is foo
My name is foo

get_declared_classes

(PHP 4, PHP 5)

get_declared_classes -- Returns an array with the name of the defined classes

Description

array get_declared_classes ( void )

Gets the declared classes.

Return Values

Returns an array of the names of the declared classes in the current script.

Note: In PHP 4.0.1, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).

Also note that depending on what extensions you have compiled or loaded into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

Examples

Example 1. get_declared_classes() example

<?php
print_r(get_declared_classes());
?>

The above example will output something similar to:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

get_declared_interfaces

(PHP 5)

get_declared_interfaces -- Returns an array of all declared interfaces

Description

array get_declared_interfaces ( void )

Gets the declared interfaces.

Return Values

Returns an array of the names of the declared interfaces in the current script.

Examples

Example 1. get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

The above example will output something similar to:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

get_object_vars

(PHP 4, PHP 5)

get_object_vars -- Gets the properties of the given object

Description

array get_object_vars ( object object )

Gets the properties of the given object.

Parameters

object

An object instance.

Return Values

Returns an associative array of defined object properties for the specified object. If a property have not been assigned a value, it will be returned with a NULL value.

ChangeLog

VersionDescription
prior to 4.2.0 If the variables declared in the class of which the object is an instance, have not been assigned a value, those will not be returned in the array

Examples

Example 1. Use of get_object_vars()

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label)
    {
        $this->label = $label;
    }

    function getPoint()
    {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));

?>

The above example will output:

Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

get_parent_class

(PHP 4, PHP 5)

get_parent_class -- Retrieves the parent class name for object or class

Description

string get_parent_class ( [mixed object] )

Retrieves the parent class name for object or class.

Parameters

object

The tested object or class name

Return Values

Returns the name of the parent class of the class of which object is an instance or the name.

If called without parameter outside object, this function returns FALSE.

ChangeLog

VersionDescription
Before 5.1.0 If called without parameter outside object, this function would have returned NULL with a warning.
Since 5.0.0 The object parameter is optional if called from the object's method.
Since 4.0.5 If object is a string, returns the name of the parent class of the class with that name.

Examples

Example 1. Using get_parent_class()

<?php

class dad {
    function dad()
    {
    // implements some logic
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

$foo = new child();
$bar = new child2();

?>

The above example will output:

I'm dad's son
I'm dad's son too

interface_exists

(PHP 5 >= 5.0.2)

interface_exists -- Checks if the interface has been defined

Description

bool interface_exists ( string interface_name [, bool autoload] )

Checks if the given interface has been defined.

Parameters

interface_name

The interface name

autoload

Wether to call __autoload or not by default

Return Values

Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Examples

Example 1. interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

See Also

class_exists()

is_a

(PHP 4 >= 4.2.0, PHP 5)

is_a -- Checks if the object is of this class or has this class as one of its parents

Description

bool is_a ( object object, string class_name )

Checks if the given object is of this class or has this class as one of its parents.

Note: The is_a() function is deprecated as of PHP 5 in favor of the instanceof type operator.

Parameters

object

The tested object

class_name

The class name

Return Values

Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

Examples

Example 1. is_a() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// create a new object
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "yes, \$WF is still a WidgetFactory\n";
}
?>

Example 2. Using the instanceof operator in PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?>

is_subclass_of

(PHP 4, PHP 5)

is_subclass_of -- Checks if the object has this class as one of its parents

Description

bool is_subclass_of ( mixed object, string class_name )

Checks if the given object has the class class_name as one of its parents.

Parameters

object

A class name or an object instance

class_name

The class name

Return Values

This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.

ChangeLog

VersionDescription
5.0.3 You may also specify the object parameter as a string (the name of the class)

Examples

Example 1. is_subclass_of() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// define a child class
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// create a new object
$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";
}


// usable only since PHP 5.0.3
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";
}
?>

The above example will output:

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

method_exists

(PHP 4, PHP 5)

method_exists -- Checks if the class method exists

Description

bool method_exists ( object object, string method_name )

Checks if the class method exists in the given object.

Parameters

object

An object instance

method_name

The method name

Return Values

Returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

Examples

Example 1. method_exists() example

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

The above example will output:

bool(true)

property_exists

(PHP 5 >= 5.1.0RC1)

property_exists --  Checks if the object or class has a property

Description

bool property_exists ( mixed class, string property )

This function checks if the given property exists in the specified class (and if it is accessible from the current scope).

Note: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Parameters

class

The class name or an object of the class to test for

property

The name of the property

Return Values

Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.

Examples

Example 1. A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;

    static function test() {
        var_dump(property_exists('myClass', 'xpto')); // true, it can be accessed from here
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //false, isn't public
myClass::test();

?>

See Also

method_exists()

XIII. Classkit Functions

Introduction

These functions allow the dynamic manipulation of PHP classes, at runtime.

Note: This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.


Installation

This PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/classkit.

The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CLASSKIT_ACC_PRIVATE (int)

Marks the method private

CLASSKIT_ACC_PROTECTED (int)

Marks the method protected

CLASSKIT_ACC_PUBLIC (int)

Marks the method public

Table of Contents
classkit_import -- Import new class method definitions from a file
classkit_method_add -- Dynamically adds a new method to a given class
classkit_method_copy -- Copies a method from class to another
classkit_method_redefine -- Dynamically changes the code of the given method
classkit_method_remove -- Dynamically removes the given method
classkit_method_rename -- Dynamically changes the name of the given method

classkit_import

(PECL)

classkit_import -- Import new class method definitions from a file

Description

array classkit_import ( string filename )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

filename

The filename of the class method definitions to import

Return Values

Associative array of imported methods

Examples

Example 1. classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

The above example will output:

foo!
bar!

classkit_method_add

(PECL)

classkit_method_add -- Dynamically adds a new method to a given class

Description

bool classkit_method_add ( string classname, string methodname, string args, string code [, int flags] )

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

The above example will output:

16

classkit_method_copy

(PECL)

classkit_method_copy -- Copies a method from class to another

Description

bool classkit_method_copy ( string dClass, string dMethod, string sClass [, string sMethod] )

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. classkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

The above example will output:

foo!

classkit_method_redefine

(PECL)

classkit_method_redefine -- Dynamically changes the code of the given method

Description

bool classkit_method_redefine ( string classname, string methodname, string args, string code [, int flags] )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. classkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

classkit_method_remove

(PECL)

classkit_method_remove -- Dynamically removes the given method

Description

bool classkit_method_remove ( string classname, string methodname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

classname

The class in which to remove the method

methodname

The name of the method to remove

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
    
    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

The above example will output:

bar

classkit_method_rename

(PECL)

classkit_method_rename -- Dynamically changes the name of the given method

Description

bool classkit_method_rename ( string classname, string methodname, string newname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

The above example will output:

foo!

XIV. ClibPDF Functions

Introduction

ClibPDF lets you create PDF documents with PHP. ClibPDF functionality and API are similar to PDFlib. This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.

Many functions in the native ClibPDF and the PHP module, as well as in PDFlib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter.

Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.

A nice feature of ClibPDF (and PDFlib) is the ability to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. (This feature can also be simulated by pdf_translate() when using the PDFlib functions.)

Another nice feature of ClibPDF is the fact that any page can be modified at any time even if a new page has been already opened. The function cpdf_set_current_page() allows to leave the current page and presume modifying an other page.

Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you to get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.


Requirements

In order to use the ClibPDF functions you need to install the ClibPDF package. It is available for download from FastIO, but requires that you purchase a license for commercial use. PHP requires that you use cpdflib >= 2. The development of ClibPDF library has been discontinued thus FastIO website would be most probably inaccessible.


Installation

To get these functions to work, you have to compile PHP with --with-cpdflib[=DIR]. DIR is the cpdflib install directory, defaults to /usr. In addition you can specify the jpeg library and the tiff library for ClibPDF to use. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-tiff-dir[=DIR].


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CPDF_PM_NONE (integer)

CPDF_PM_OUTLINES (integer)

CPDF_PM_THUMBS (integer)

CPDF_PM_FULLSCREEN (integer)

CPDF_PL_SINGLE (integer)

CPDF_PL_1COLUMN (integer)

CPDF_PL_2LCOLUMN (integer)

CPDF_PL_2RCOLUMN (integer)


Examples

Example 1. Simple ClibPDF Example

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 50);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 50);
cpdf_lineto($cpdf, 740, 330);
cpdf_stroke($cpdf);
cpdf_finalize_page($cpdf, 1);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:

Example 2. pdfclock example from pdflib 2.0 distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php");
cpdf_set_title($pdf, "Analog Clock");
  
while ($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);
  
  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */
  
  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);
  
  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6) {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
  }
  
  cpdf_restore($pdf);
  cpdf_save($pdf);
 
  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30) {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>

See Also

See also the PDFlib extension documentation.

Table of Contents
cpdf_add_annotation -- Adds annotation
cpdf_add_outline -- Adds bookmark for current page
cpdf_arc -- Draws an arc
cpdf_begin_text -- Starts text section
cpdf_circle -- Draw a circle
cpdf_clip -- Clips to current path
cpdf_close -- Closes the pdf document
cpdf_closepath_fill_stroke -- Close, fill and stroke current path
cpdf_closepath_stroke -- Close path and draw line along path
cpdf_closepath -- Close path
cpdf_continue_text -- Output text in next line
cpdf_curveto -- Draws a curve
cpdf_end_text -- Ends text section
cpdf_fill_stroke -- Fill and stroke current path
cpdf_fill -- Fill current path
cpdf_finalize_page -- Ends page
cpdf_finalize -- Ends document
cpdf_global_set_document_limits -- Sets document limits for any pdf document
cpdf_import_jpeg -- Opens a JPEG image
cpdf_lineto -- Draws a line
cpdf_moveto -- Sets current point
cpdf_newpath -- Starts a new path
cpdf_open -- Opens a new pdf document
cpdf_output_buffer -- Outputs the pdf document in memory buffer
cpdf_page_init -- Starts new page
cpdf_place_inline_image -- Places an image on the page
cpdf_rect -- Draw a rectangle
cpdf_restore -- Restores formerly saved environment
cpdf_rlineto -- Draws a line
cpdf_rmoveto -- Sets current point
cpdf_rotate_text -- Sets text rotation angle
cpdf_rotate -- Sets rotation
cpdf_save_to_file -- Writes the pdf document into a file
cpdf_save -- Saves current environment
cpdf_scale -- Sets scaling
cpdf_set_action_url -- Sets hyperlink
cpdf_set_char_spacing -- Sets character spacing
cpdf_set_creator -- Sets the creator field in the pdf document
cpdf_set_current_page -- Sets current page
cpdf_set_font_directories -- Sets directories to search when using external fonts
cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts
cpdf_set_font -- Select the current font face and size
cpdf_set_horiz_scaling -- Sets horizontal scaling of text
cpdf_set_keywords -- Sets the keywords field of the pdf document
cpdf_set_leading -- Sets distance between text lines
cpdf_set_page_animation -- Sets duration between pages
cpdf_set_subject -- Sets the subject field of the pdf document
cpdf_set_text_matrix -- Sets the text matrix
cpdf_set_text_pos -- Sets text position
cpdf_set_text_rendering -- Determines how text is rendered
cpdf_set_text_rise -- Sets the text rise
cpdf_set_title -- Sets the title field of the pdf document
cpdf_set_viewer_preferences -- How to show the document in the viewer
cpdf_set_word_spacing -- Sets spacing between words
cpdf_setdash -- Sets dash pattern
cpdf_setflat -- Sets flatness
cpdf_setgray_fill -- Sets filling color to gray value
cpdf_setgray_stroke -- Sets drawing color to gray value
cpdf_setgray -- Sets drawing and filling color to gray value
cpdf_setlinecap -- Sets linecap parameter
cpdf_setlinejoin -- Sets linejoin parameter
cpdf_setlinewidth -- Sets line width
cpdf_setmiterlimit -- Sets miter limit
cpdf_setrgbcolor_fill -- Sets filling color to rgb color value
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value
cpdf_show_xy -- Output text at position
cpdf_show -- Output text at current position
cpdf_stringwidth -- Returns width of text in current font
cpdf_stroke -- Draw line along path
cpdf_text -- Output text with parameters
cpdf_translate -- Sets origin of coordinate system

cpdf_add_annotation

(PHP 3 >= 3.0.12, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_annotation -- Adds annotation

Description

bool cpdf_add_annotation ( int pdf_document, float llx, float lly, float urx, float ury, string title, string content [, int mode] )

Adds a note at the specified point.

Parameters

pdf_document

The document handle, returned by cpdf_open().

llx

Lower left X

lly

Lower left Y

urx

Upper right X

ury

Upper right Y

title

The title of the annotation

text

The contents of the annotation

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_add_outline

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_outline -- Adds bookmark for current page

Description

int cpdf_add_outline ( int pdf_document, int lastoutline, int sublevel, int open, int pagenr, string text )

Adds a bookmark with text text that points to the current page.

Parameters

pdf_document

The document handle, returned by cpdf_open().

lastoutline

sublevel

open

pagenr

text

The bookmark text

Examples

Example 1. Adding a page outline

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// some drawing
// ...
cpdf_finalize($cpdf);
header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_arc -- Draws an arc

Description

bool cpdf_arc ( int pdf_document, float x_coor, float y_coor, float radius, float start, float end [, int mode] )

Draws an arc.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x

The x-coordinate of the center

y

The y-coordinate of the center

radius

The arc radius

start

The starting angle, in degrees

end

The ending angle, in degrees

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_circle()

cpdf_begin_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_begin_text -- Starts text section

Description

bool cpdf_begin_text ( int pdf_document )

Starts a text section.

The created text section must be ended with cpdf_end_text().

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See Also

cpdf_end_text()

cpdf_circle

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_circle -- Draw a circle

Description

bool cpdf_circle ( int pdf_document, float x_coor, float y_coor, float radius [, int mode] )

Draws a circle.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the center

y_coor

The y-coordinate of the center

radius

The circle radius

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_arc()

cpdf_clip

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_clip -- Clips to current path

Description

bool cpdf_clip ( int pdf_document )

Clips all drawing to the current path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_close

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_close -- Closes the pdf document

Description

bool cpdf_close ( int pdf_document )

Closes the PDF document.

This should be the last function called, even after cpdf_finalize(), cpdf_output_buffer() or cpdf_save_to_file().

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_open()

cpdf_closepath_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

bool cpdf_closepath_fill_stroke ( int pdf_document )

Closes, fills the interior of the current path with the current fill color and draws current path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_closepath_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_stroke -- Close path and draw line along path

Description

bool cpdf_closepath_stroke ( int pdf_document )

Closes the current path and draws a line along it.

cpdf_closepath_stroke() is a combination of cpdf_closepath() and cpdf_stroke().

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_closepath

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath -- Close path

Description

bool cpdf_closepath ( int pdf_document )

Closes the current path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_continue_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_continue_text -- Output text in next line

Description

bool cpdf_continue_text ( int pdf_document, string text )

Outputs the string in text in the next line.

Parameters

pdf_document

The document handle, returned by cpdf_open().

text

The string to output

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_curveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_curveto -- Draws a curve

Description

bool cpdf_curveto ( int pdf_document, float x1, float y1, float x2, float y2, float x3, float y3 [, int mode] )

Draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x1

x-coordinate for the first control point

y1

y-coordinate for the first control point

x2

x-coordinate for the second control point

y2

y-coordinate for the second control point

x3

x-coordinate for the target

y3

y-coordinate for the target

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_end_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_end_text -- Ends text section

Description

bool cpdf_end_text ( int pdf_document )

Ends a text section which was started with cpdf_begin_text().

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

cpdf_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill_stroke -- Fill and stroke current path

Description

bool cpdf_fill_stroke ( int pdf_document )

Fills the interior of the current path with the current fill color and draws current path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill -- Fill current path

Description

bool cpdf_fill ( int pdf_document )

Fills the interior of the current path with the current fill color.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_finalize_page

(PHP 3 >= 3.0.10, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize_page -- Ends page

Description

bool cpdf_finalize_page ( int pdf_document, int page_number )

Ends the page which number is page_number.

This function is only used for saving memory. A finalized page takes less memory but cannot be modified anymore.

Parameters

pdf_document

The document handle, returned by cpdf_open().

page_number

The page number

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_finalize

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize -- Ends document

Description

bool cpdf_finalize ( int pdf_document )

Ends the PDF document.

You still have to call cpdf_close().

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_close()

cpdf_global_set_document_limits

(PHP 4, PHP 5 <= 5.0.4)

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

bool cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects )

Sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.

Parameters

maxPages

The maximum number of pages

maxFonts

The maximum number of fonts

maxImages

The maximum number of images

maxAnnots

The maximum number of annotations

maxObjects

The maximum number of objects

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_open()

cpdf_import_jpeg

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_import_jpeg -- Opens a JPEG image

Description

bool cpdf_import_jpeg ( int pdf_document, string file_name, float x_coor, float y_coor, float angle, float width, float height, float x_scale, float y_scale, int gsave [, int mode] )

Opens a JPEG image.

Parameters

pdf_document

The document handle, returned by cpdf_open().

file_name

The path to the image file. The format of the image has to be JPEG

x_coor

The x-coordinate of the image

y_coor

The y-coordinate of the image

angle

The image rotation angle, in degrees

width

The image width

height

The image height

x_scale

y_scale

gsave

Should be non-zero to allow this function to operate correctly

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_lineto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_lineto -- Draws a line

Description

bool cpdf_lineto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_lineto() function draws a line from the current point to the specified point.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the destination point

y_coor

The y-coordinate of the destination point

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_moveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_moveto -- Sets current point

Description

bool cpdf_moveto ( int pdf_document, float x_coor, float y_coor [, int mode] )

Sets the current point to the given coordinates.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate

y_coor

The y-coordinate

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_newpath

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_newpath -- Starts a new path

Description

bool cpdf_newpath ( int pdf_document )

Starts a new path on the document.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_open

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_open -- Opens a new pdf document

Description

int cpdf_open ( int compression [, string filename [, array doc_limits]] )

Opens a new PDF document.

Parameters

compression

If different from 0, document compression is turned on

filename

Sets the file in which the document is written. - is a synonym for stdout.

If omitted, the document is created in memory and can either be written into a file with cpdf_save_to_file() or written to standard output with cpdf_output_buffer().

Note: Using stdout will not work if PHP is compiled as an apache module. You can solve this problem by skipping this parameter filename and using cpdf_output_buffer() later to output the PDF document.

doc_limits

An array defining the document limitation. See cpdf_global_set_document_limits() for more information

Return Values

Returns a document handle, needed as the first parameter for all other functions of the library.

cpdf_output_buffer

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

bool cpdf_output_buffer ( int pdf_document )

Outputs the pdf document to stdout.

The document has to be created in memory which is the case if cpdf_open() has been called without the file name parameter.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_open()

cpdf_page_init

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_page_init -- Starts new page

Description

bool cpdf_page_init ( int pdf_document, int page_number, int orientation, float height, float width [, float unit] )

Starts a new page.

Parameters

pdf_document

The document handle, returned by cpdf_open().

page_number

The page number

orientation

0 for portrait and 1 for landscape

height

The page height

width

The page width

unit

The unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_place_inline_image

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_place_inline_image -- Places an image on the page

Description

bool cpdf_place_inline_image ( int pdf_document, int image, float x_coor, float y_coor, float angle, float width, float height, int gsave [, int mode] )

Places an image created with the PHP image functions on the page. The image can be scaled at the same time.

Note: This function is only available if PHP was compiled with the GD Graphics Library 1.3. See the GD extension installation instructions for further information.

Parameters

pdf_document

The document handle, returned by cpdf_open().

image

An image created with the PHP image functions

x_coor

The x-coordinate of the image

y_coor

The y-coordinate of the image

angle

The image rotation angle, in degrees

width

The image width

height

The image height

gsave

Should be non-zero to allow this function to operate correctly

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_rect

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rect -- Draw a rectangle

Description

bool cpdf_rect ( int pdf_document, float x_coor, float y_coor, float width, float height [, int mode] )

Draws a rectangle.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the lower left corner

y_coor

The y-coordinate of the lower left corner

width

The rectangle width

height

The rectangle height

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Drawing a rectangle

<?php

$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);

// set the fill color to red
cpdf_setrgbcolor($cpdf, 1, 0, 0);

// draw a (180 * 100) rectangle
cpdf_rect($cpdf, 645, 400, 180, 100);

// fill the rectangle
cpdf_fill($cpdf);

cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);

?>

cpdf_restore

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_restore -- Restores formerly saved environment

Description

bool cpdf_restore ( int pdf_document )

Restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Save/Restore

<?php
cpdf_save($pdf);
// do all kinds of rotations, transformations, ...
cpdf_restore($pdf)
?>

See Also

cpdf_save()

cpdf_rlineto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rlineto -- Draws a line

Description

bool cpdf_rlineto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_rlineto() function draws a line from the current point to the given relative point.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the destination point

y_coor

The y-coordinate of the destination point

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_rmoveto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rmoveto -- Sets current point

Description

bool cpdf_rmoveto ( int pdf_document, float x_coor, float y_coor [, int mode] )

Set the current point relative to the given coordinates.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the destination point

y_coor

The y-coordinate of the destination point

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_moveto()

cpdf_rotate_text

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate_text -- Sets text rotation angle

Description

bool cpdf_rotate_text ( int pdfdoc, float angle )

Warning

This function is currently not documented; only the argument list is available.

cpdf_rotate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate -- Sets rotation

Description

bool cpdf_rotate ( int pdf_document, float angle )

Sets the rotation in degrees to angle.

Parameters

pdf_document

The document handle, returned by cpdf_open().

angle

The angle, in degrees

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_save_to_file

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save_to_file -- Writes the pdf document into a file

Description

bool cpdf_save_to_file ( int pdf_document, string filename )

Outputs the PDF document into a file if it has been created in memory.

This function is not needed if the PDF document has been open by specifying a filename as a parameter of cpdf_open().

Parameters

pdf_document

The document handle, returned by cpdf_open().

filename

The path to the saved PDF document

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_save

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save -- Saves current environment

Description

bool cpdf_save ( int pdf_document )

Saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_restore()

cpdf_scale

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_scale -- Sets scaling

Description

bool cpdf_scale ( int pdf_document, float x_scale, float y_scale )

Sets the scaling factor in both directions.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_scale

The X scale percent to set. Default to 0.0

y_scale

The Y scale percent to set. Default to 0.0

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_action_url

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_action_url -- Sets hyperlink

Description

bool cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode] )

Warning

This function is currently not documented; only the argument list is available.

cpdf_set_char_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_char_spacing -- Sets character spacing

Description

bool cpdf_set_char_spacing ( int pdf_document, float space )

Sets the spacing between characters.

Parameters

pdf_document

The document handle, returned by cpdf_open().

space

Distance between individual characters in a string.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_creator

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_creator -- Sets the creator field in the pdf document

Description

bool cpdf_set_creator ( int pdf_document, string creator )

Sets the creator of a PDF document.

Parameters

pdf_document

The document handle, returned by cpdf_open().

creator

The creator of the document

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_current_page

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_current_page -- Sets current page

Description

bool cpdf_set_current_page ( int pdf_document, int page_number )

Sets the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().

Parameters

pdf_document

The document handle, returned by cpdf_open().

page_number

The page number

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_font_directories

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

cpdf_set_font_directories -- Sets directories to search when using external fonts

Description

bool cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir )

Warning

This function is currently not documented; only the argument list is available.

cpdf_set_font_map_file

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts

Description

bool cpdf_set_font_map_file ( int pdfdoc, string filename )

Warning

This function is currently not documented; only the argument list is available.

cpdf_set_font

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_font -- Select the current font face and size

Description

bool cpdf_set_font ( int pdf_document, string font_name, float size, string encoding )

Sets the current font face, font size and encoding.

Parameters

pdf_document

The document handle, returned by cpdf_open().

font_name

The font name. Currently only the standard postscript fonts are supported.

See the ClibPDF Manual for more information, especially on how to support Asian fonts.

size

The font size

encoding

Can take the following values: MacRomanEncoding, MacExpertEncoding, WinAnsiEncoding, and NULL (the font's built-in encoding).

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_horiz_scaling

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

bool cpdf_set_horiz_scaling ( int pdf_document, float scale )

Sets the horizontal scaling to scale percent.

Parameters

pdf_document

The document handle, returned by cpdf_open().

scale

The scale percent to set

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_keywords

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_keywords -- Sets the keywords field of the pdf document

Description

bool cpdf_set_keywords ( int pdf_document, string keywords )

Sets the keywords of the PDF document.

Parameters

pdf_document

The document handle, returned by cpdf_open().

keywords

The keywords to set on the document

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_leading

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_leading -- Sets distance between text lines

Description

bool cpdf_set_leading ( int pdf_document, float distance )

Sets the distance between text lines. This will be used if text is output by cpdf_continue_text().

Parameters

pdf_document

The document handle, returned by cpdf_open().

distance

The distance between text lines, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_page_animation

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_page_animation -- Sets duration between pages

Description

bool cpdf_set_page_animation ( int pdf_document, int transition, float duration, float direction, int orientation, int inout )

Sets the transition between following pages.

Parameters

pdf_document

The document handle, returned by cpdf_open().

transition

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

duration

The value of duration is the number of seconds between page flipping.

direction

orientation

inout

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_subject

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_subject -- Sets the subject field of the pdf document

Description

bool cpdf_set_subject ( int pdf_document, string subject )

Sets the subject of the PDF document.

Parameters

pdf_document

The document handle, returned by cpdf_open().

subject

The subject of the document

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_text_matrix

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_matrix -- Sets the text matrix

Description

bool cpdf_set_text_matrix ( int pdf_document, array matrix )

Sets a matrix which describes a transformation applied on the current text font.

Parameters

pdf_document

The document handle, returned by cpdf_open().

matrix

An array of six elements describing the transformation

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_text_pos

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_pos -- Sets text position

Description

bool cpdf_set_text_pos ( int pdf_document, float x_coor, float y_coor [, int mode] )

Sets the position of text for the next cpdf_show() call.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the text position

y_coor

The y-coordinate of the text position

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_text_rendering

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rendering -- Determines how text is rendered

Description

bool cpdf_set_text_rendering ( int pdf_document, int rendermode )

Determines how the text is rendered.

Parameters

pdf_document

The document handle, returned by cpdf_open().

rendermode

The possible values for rendermode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_text_rise

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rise -- Sets the text rise

Description

bool cpdf_set_text_rise ( int pdf_document, float value )

Sets the text rising to value units.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

The text rising, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_title

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_title -- Sets the title field of the pdf document

Description

bool cpdf_set_title ( int pdf_document, string title )

Sets the title of a PDF document.

Parameters

pdf_document

The document handle, returned by cpdf_open().

title

The title of the document

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_set_viewer_preferences

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_viewer_preferences -- How to show the document in the viewer

Description

bool cpdf_set_viewer_preferences ( int pdfdoc, array preferences )

Warning

This function is currently not documented; only the argument list is available.

cpdf_set_word_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_word_spacing -- Sets spacing between words

Description

bool cpdf_set_word_spacing ( int pdf_document, float space )

Sets the spacing between words.

Parameters

pdf_document

The document handle, returned by cpdf_open().

space

The spacing, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setdash

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setdash -- Sets dash pattern

Description

bool cpdf_setdash ( int pdf_document, float white, float black )

Sets the dash pattern to the given one. If both parameters are 0, a solid line is set.

Parameters

pdf_document

The document handle, returned by cpdf_open().

white

White units, as a float

black

Black units, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setflat

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setflat -- Sets flatness

Description

bool cpdf_setflat ( int pdf_document, float value )

Sets the flatness.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

The flatness as a float, between 0 and 100

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setgray_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_fill -- Sets filling color to gray value

Description

bool cpdf_setgray_fill ( int pdf_document, float value )

Sets the current gray value to fill a path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

The gray value, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setgray_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

bool cpdf_setgray_stroke ( int pdf_document, float gray_value )

Sets the current drawing color to the given gray value.

Parameters

pdf_document

The document handle, returned by cpdf_open().

gray_value

The gray value, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setgray

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray -- Sets drawing and filling color to gray value

Description

bool cpdf_setgray ( int pdf_document, float gray_value )

Sets the current drawing and filling color to the given gray value.

Parameters

pdf_document

The document handle, returned by cpdf_open().

gray_value

The gray value, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setlinecap

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinecap -- Sets linecap parameter

Description

bool cpdf_setlinecap ( int pdf_document, int value )

Sets the linecap parameter.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

0 = butt end, 1 = round, 2 = projecting square

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setlinejoin

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinejoin -- Sets linejoin parameter

Description

bool cpdf_setlinejoin ( int pdf_document, int value )

Set the linejoin parameter.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

0 = miter, 1 = round, 2 = bevel

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setlinewidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinewidth -- Sets line width

Description

bool cpdf_setlinewidth ( int pdf_document, float width )

Set the line width.

Parameters

pdf_document

The document handle, returned by cpdf_open().

width

The line width, as a float

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setmiterlimit

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setmiterlimit -- Sets miter limit

Description

bool cpdf_setmiterlimit ( int pdf_document, float value )

Sets the miter limit.

Parameters

pdf_document

The document handle, returned by cpdf_open().

value

The miter limit. Must be greater or equal than 1

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setrgbcolor_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

bool cpdf_setrgbcolor_fill ( int pdf_document, float red_value, float green_value, float blue_value )

Sets the current rgb color value to fill a path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

red_value

The red value, as a float between 0.0 (black) and 1.0 (red)

green_value

The green value, as a float between 0.0 (black) and 1.0 (green)

blue_value

The blue value, as a float between 0.0 (black) and 1.0 (blue)

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setrgbcolor_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

bool cpdf_setrgbcolor_stroke ( int pdf_document, float red_value, float green_value, float blue_value )

Sets the current drawing color to the given rgb color value.

Parameters

pdf_document

The document handle, returned by cpdf_open().

red_value

The red value, as a float between 0.0 (black) and 1.0 (red)

green_value

The green value, as a float between 0.0 (black) and 1.0 (green)

blue_value

The blue value, as a float between 0.0 (black) and 1.0 (blue)

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_setrgbcolor

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

bool cpdf_setrgbcolor ( int pdf_document, float red_value, float green_value, float blue_value )

Sets the current drawing and filling color to the given rgb color value.

Parameters

pdf_document

The document handle, returned by cpdf_open().

red_value

The red value, as a float between 0.0 (black) and 1.0 (red)

green_value

The green value, as a float between 0.0 (black) and 1.0 (green)

blue_value

The blue value, as a float between 0.0 (black) and 1.0 (blue)

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_show_xy

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show_xy -- Output text at position

Description

bool cpdf_show_xy ( int pdf_document, string text, float x_coor, float y_coor [, int mode] )

Outputs the string text at the given position.

Note: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

Parameters

pdf_document

The document handle, returned by cpdf_open().

text

The text

x_coor

The x-coordinate of the text position

y_coor

The y-coordinate of the text position

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_text()

cpdf_show

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show -- Output text at current position

Description

bool cpdf_show ( int pdf_document, string text )

Outputs a text at the current position.

Parameters

pdf_document

The document handle, returned by cpdf_open().

text

The text, as a string

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_stringwidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stringwidth -- Returns width of text in current font

Description

float cpdf_stringwidth ( int pdf_document, string text )

Returns the width of the string in text.

This function requires a font to be set before.

Parameters

pdf_document

The document handle, returned by cpdf_open().

text

The text, as a string

Return Values

Returns the width of text.

See Also

cpdf_set_font()

cpdf_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stroke -- Draw line along path

Description

bool cpdf_stroke ( int pdf_document )

Draws a line along current path.

Parameters

pdf_document

The document handle, returned by cpdf_open().

Return Values

Returns TRUE on success or FALSE on failure.

cpdf_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_text -- Output text with parameters

Description

bool cpdf_text ( int pdf_document, string text [, float x_coor, float y_coor [, int mode [, float orientation [, int alignmode]]]] )

Outputs the string text at the given position.

Parameters

pdf_document

The document handle, returned by cpdf_open().

text

The text

x_coor

The x-coordinate of the text position

y_coor

The y-coordinate of the text position

mode

The optional parameter mode determines the unit length. If it is 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

orientation

Rotation of the text in degrees

alignmode

Determines how the text is aligned. See the ClibPDF documentation for possible values.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

cpdf_show_xy()

cpdf_translate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_translate -- Sets origin of coordinate system

Description

bool cpdf_translate ( int pdf_document, float x_coor, float y_coor )

Sets the origin of coordinate system to the specified point.

Parameters

pdf_document

The document handle, returned by cpdf_open().

x_coor

The x-coordinate of the point

y_coor

The y-coordinate of the point

Return Values

Returns TRUE on success or FALSE on failure.

XV. COM and .Net (Windows)

Introduction

COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.

There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.

Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.

Starting with PHP 5, this extension (and this documentation) was rewritten from scratch and much of the old confusing and bogus cruft has be removed. Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.

Please read this article for an overview of the changes in this extension in PHP 5.


Requirements

COM functions are only available for the Windows version of PHP.

.Net support requires PHP 5 and the .Net runtime.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension 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.


For Each

Starting with PHP 5, you may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In laymans terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Example 1. For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example 2. while() ... Next() in PHP 4

<?php 
$domainObject = new COM("WinNT://Domain"); 
while ($obj = $domainObject->Next()) { 
   echo $obj->Name . "<br />"; 
} 
?>

Example 3. foreach in PHP 5

<?php 
$domainObject = new COM("WinNT://Domain"); 
foreach ($domainObject as $obj) { 
   echo $obj->Name . "<br />"; 
} 
?>


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access. In PHP 4, you may use PHP array syntax to read/write such a property, but only a single dimension is allowed. If you want to read a multi-dimensional property, you could instead make the property access into a function call, with each parameter representing each dimension of the array access, but there is no way to write to such a property.

PHP 5 introduces the following new features to make your life easier:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the the Section called foreach in Chapter 16 control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at the Section called For Each for more information on this topic.


Exceptions (PHP 5)

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Com configuration options

NameDefaultChangeableChangelog
com.allow_dcom"0"PHP_INI_SYSTEMAvailable since PHP 4.0.5.
com.autoregister_typelib"0"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose"0"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_casesensitive"1"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page""PHP_INI_ALLAvailable since PHP 5.0.0.
com.typelib_file""PHP_INI_SYSTEMAvailable since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

com.allow_dcom

When this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the com.autoregister_casesensitive configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

Note: This configuration directive was introduced with PHP 5.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.


Resource Types

This extension defines a reference to a COM component returned by deprecated com_load() (this function does not exist in PHP 5; use the COM class instead).


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)

VARCMP_LT (integer)

VARCMP_EQ (integer)

VARCMP_GT (integer)

VARCMP_NULL (integer)

NORM_IGNORECASE (integer)

NORM_IGNORENONSPACE (integer)

NORM_IGNORESYMBOLS (integer)

NORM_IGNOREWIDTH (integer)

NORM_IGNOREKANATYPE (integer)

NORM_IGNOREKASHIDA (integer)

DISP_E_DIVBYZERO (integer)

DISP_E_OVERFLOW (integer)

MK_E_UNAVAILABLE (integer)


See Also

For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL). You might find some additional useful information in our FAQ for Chapter 66. 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 -- COM class
DOTNET -- DOTNET class
VARIANT -- VARIANT class
com_addref --  Increases the components reference counter [deprecated]
com_create_guid --  Generate a globally unique identifier (GUID)
com_event_sink --  Connect events from a COM object to a PHP object
com_get_active_object --  Returns a handle to an already running instance of a COM object
com_get --  Gets the value of a COM Component's property [deprecated]
com_invoke --  Calls a COM component's method [deprecated]
com_isenum -- Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
com_load_typelib -- Loads a Typelib
com_load --  Creates a new reference to a COM component [deprecated]
com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds
com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface
com_propget -- Alias of com_get()
com_propput -- Alias of com_set()
com_propset -- Alias of com_set()
com_release --  Decreases the components reference counter [deprecated]
com_set --  Assigns a value to a COM component's property
variant_abs --  Returns the absolute value of a variant
variant_add --  "Adds" two variant values together and returns the result
variant_and --  performs a bitwise AND operation between two variants and returns the result
variant_cast --  Convert a variant into a new variant object of another type
variant_cat --  concatenates two variant values together and returns the result
variant_cmp --  Compares two variants
variant_date_from_timestamp --  Returns a variant date representation of a Unix timestamp
variant_date_to_timestamp --  Converts a variant date/time value to Unix timestamp
variant_div --  Returns the result from dividing two variants
variant_eqv --  Performs a bitwise equivalence on two variants
variant_fix --  Returns the integer portion ? of a variant
variant_get_type -- Returns the type of a variant object
variant_idiv --  Converts variants to integers and then returns the result from dividing them
variant_imp --  Performs a bitwise implication on two variants
variant_int --  Returns the integer portion of a variant
variant_mod --  Divides two variants and returns only the remainder
variant_mul --  multiplies the values of the two variants and returns the result
variant_neg --  Performs logical negation on a variant
variant_not --  Performs bitwise not negation on a variant
variant_or --  Performs a logical disjunction on two variants
variant_pow --  Returns the result of performing the power function with two variants
variant_round --  Rounds a variant to the specified number of decimal places
variant_set_type --  Convert a variant into another type "in-place"
variant_set --  Assigns a new value for a variant object
variant_sub --  subtracts the value of the right variant from the left variant value and returns the result
variant_xor --  Performs a logical exclusion on two variants

COM

(no version information, might be only in CVS)

COM -- COM class

Synopsis

$obj = new COM("Application.ID")

Description

The COM class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

Methods

com COM::COM ( string module_name [, mixed server_name [, int codepage [, string typelib]]] )

COM class constructor. The parameters have the following meanings:

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 you specify a non-NULL value for server, PHP will refuse to load the object unless the com.allow_dcom configuration 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 directive.

Table 1. DCOM server name

server_name keytypedescription
ServerstringThe name of the server.
UsernamestringThe username to connect as.
PasswordstringThe password for Username.
FlagsintegerOne 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 in PHP 5, 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.

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.

Starting with PHP 5, 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.

In PHP 4, to pass parameters by reference you need to create an instance of the VARIANT class to wrap the byref parameters.

Pseudo Methods

In PHP versions prior to 5, a number of not very pleasant hacks meant that the following method names were not passed through to COM and were handled directly by PHP. PHP 5 eliminates these things; read the details below to determine how to fix your scripts. These magic method names are case insensitive.

void COM::AddRef ( void )

Artificially adds a reference count to the COM object.

Warning

You should never need to use this method. It exists as a logical complement to the Release() method below.

void COM::Release ( void )

Artificially removes a reference count from the COM object.

Warning

You should never need to use this method. Its existence in PHP is a bug designed to work around a bug that keeps COM objects running longer than they should.

Pseudo Methods for Iterating

These pseudo methods are only available if com_isenum() returns TRUE, in which case, they hide any methods with the same names that might otherwise be provided by the COM object. These methods have all been eliminated in PHP 5, and you should use the Section called For Each in Reference XV, COM and .Net (Windows) instead.

variant COM::All ( void )

Returns a variant representing a SafeArray that has 10 elements; each element will be an empty/null variant. This function was supposed to return an array containing all the elements from the iterator, but was never completed. Do not use.

variant COM::Next ( void )

Returns a variant representing the next element available from the iterator, or FALSE when there are no more elements.

variant COM::Prev ( void )

Returns a variant representing the previous element available from the iterator, or FALSE when there are no more elements.

void COM::Reset ( void )

Rewinds the iterator back to the start.

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;

?>

DOTNET

(no version information, might be only in CVS)

DOTNET -- DOTNET class

Synopsis

$obj = new DOTNET("assembly", "classname")

Description

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.

Methods

string DOTNET::DOTNET ( string assembly_name, string class_name [, int codepage] )

DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.

Example 1. DOTNET example

<?php
  $stack = new DOTNET("mscorlib", "System.Collections.Stack"); 
  $stack->Push(".Net"); 
  $stack->Push("Hello "); 
  echo $stack->Pop() . $stack->Pop(); 
?>

Note: You need to install the .Net runtime on your web server to take advantage of this feature.

VARIANT

(no version information, might be only in CVS)

VARIANT -- VARIANT class

Synopsis

$vVar = new VARIANT($var)

Description

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.

Methods

object VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]] )

VARIANT class constructor. Parameters:

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 the Section called Predefined Constants in Reference XV, COM and .Net (Windows).

In PHP versions prior to PHP 5, you could force PHP to pass a variant object by reference by OR'ing VT_BYREF with the type. In PHP 5, this hack is not supported; instead, PHP 5 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.

PHP versions prior to PHP 5 define a number of (undocumented) virtual properties for instances of the VARIANT class; these properties have all been removed in PHP 5 in favour of its more natural syntax; these differences are best highlighted by example:

Example 1. Variant example, PHP 4.x style

<?php
$v = new VARIANT(42);
print "The type is " . $v->type . "<br/>";
print "The value is " . $v->value . "<br/>";
?>

Example 2. Variant example, PHP 5 style

<?php
$v = new VARIANT(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

The reason for the change is that, internally, the COM extension sees VARIANT, COM and DOTNET classes as the same thing, and the design philosophy for these classes is that all property and member accesses are passed through to COM with no interference. The new syntax is more natural and less effort, and most of the removed virtual properties didn't make any sense in a PHP context in any case.

Note: PHP 5 takes a much simpler approach to handling VARIANTs; 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 print()ing 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().

com_addref

(PHP 4 >= 4.1.0)

com_addref --  Increases the components reference counter [deprecated]

Description

void com_addref ( void )

Increases the components reference counter.

Warning

You should never need to use this function.

com_create_guid

(PHP 5)

com_create_guid --  Generate a globally unique identifier (GUID)

Description

string com_create_guid ( void )

Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

See also uuid_create() in the PECL uuid extension.

com_event_sink

(PHP 4 >= 4.2.3, PHP 5)

com_event_sink --  Connect events from a COM object to a PHP object

Description

bool com_event_sink ( variant comobject, object sinkobject [, mixed sinkinterface] )

Instructs COM to sink events generated by comobject into the PHP object sinkobject. PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.

sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

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");
// note that you don't need the & for PHP 5!
$sink =& new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.php.net");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

See also com_print_typeinfo(), com_message_pump().

com_get_active_object

(PHP 5)

com_get_active_object --  Returns a handle to an already running instance of a COM object

Description

variant com_get_active_object ( string progid [, int code_page] )

com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application). code_page acts in precisely the same way that it does for the COM class.

If the requested object is running, it will be returned to your script just like any other COM object. Otherwise a com_exception will be raised. There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

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.

com_get

(PHP 3 >= 3.0.3, PHP 4)

com_get --  Gets the value of a COM Component's property [deprecated]

Description

mixed com_get ( resource com_object, string property )

Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.

Example 1. Don't use com_get(), use OO syntax instead

<?php 
// do this
$var = $obj->property;
// instead of this:
$var = com_get($obj, 'property');
?>

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

com_invoke

(PHP 4)

com_invoke --  Calls a COM component's method [deprecated]

Description

mixed com_invoke ( resource com_object, string function_name [, mixed function_parameters] )

com_invoke() invokes the method named function_name of the COM component referenced by com_object. com_invoke() returns FALSE on error, returns the function_name's return value on success. All the extra parameters function_parameters are passed to the method function_name.

Example 1. Don't use com_invoke(), use OO syntax instead

<?php 
// do this
$val = $obj->method($one, $two);
// instead of this:
$val = com_invoke($obj, 'method', $one, $two);
?>

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

com_isenum

(PHP 4 >= 4.1.0)

com_isenum -- Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]

Description

bool com_isenum ( variant com_module )

Checks to see if a COM object can be enumerated using the Next() method hack. Returns TRUE if it can, FALSE if it cannot. See COM class for more details on these methods.

Note: This function does not exist in PHP 5; use the more natural foreach statement to iterate over the contents of COM objects. See the Section called For Each in Reference XV, COM and .Net (Windows) for more details.

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5)

com_load_typelib -- Loads a Typelib

Description

bool com_load_typelib ( string typelib_name [, bool case_insensitive] )

Loads a type-library and registers its constants in the engine, as though they were defined using define(). The case_insensitive behaves in the same way as the parameter with the same name in the define() function.

typelib_name can be one of the following:

  • The filename of a .tlb file or the executable module that contains the type library.

  • The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP will attempt to resolve the type library in this order, as the process gets more and more expensive as you progress down the list; searching for the type library by name is handled by physically enumerating the registry until we find a match.

Note that it is much more efficient to use the com.typelib_file configuration setting to pre-load and register the constants, although not so flexible.

If you have turned on com.autoregister_typelib , then PHP will attempt to automatically register the constants associated with a COM object when you instantiate it. This depends on the interfaces provided by the COM object itself, and may not always be possible.

com_load

(PHP 4)

com_load --  Creates a new reference to a COM component [deprecated]

Description

resource com_load ( string module_name [, string server_name [, int codepage]] )

Equivalent to using the new operator to create an instance of the COM class. You should do that instead of calling this function.

Example 1. Don't use com_load(), use OO syntax instead

<?php 
// do this
$obj = new COM($module);
// instead of this:
$obj = com_load($module);
?>

Note: This function does not exist in PHP 5; use the COM class instead.

com_message_pump

(PHP 4 >= 4.2.3, PHP 5)

com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds

Description

bool com_message_pump ( [int timeoutms] )

This function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue. If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE. If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

com_print_typeinfo

(PHP 4 >= 4.2.3, PHP 5)

com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface

Description

bool com_print_typeinfo ( object comobject [, string dispinterface [, bool wantsink]] )

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()). dispinterface is the name of an IDispatch descendant interface that you want to display. If wantsink is TRUE, the corresponding sink interface will be displayed instead.

See also com_event_sink(), com_load_typelib().

com_propget

(PHP 3 >= 3.0.3, PHP 4)

com_propget -- Alias of com_get()

Description

This function is an alias of: com_get().

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

com_propput

(PHP 3 >= 3.0.3, PHP 4)

com_propput -- Alias of com_set()

Description

This function is an alias of: com_set().

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

com_propset

(PHP 3 >= 3.0.3, PHP 4)

com_propset -- Alias of com_set()

Description

This function is an alias of: com_set().

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

com_release

(PHP 4 >= 4.1.0)

com_release --  Decreases the components reference counter [deprecated]

Description

void com_release ( void )

Decreases the components reference counter.

Warning

You should never need to use this function.

Note: This function has gone away in PHP 5.

com_set

(PHP 3 >= 3.0.3, PHP 4)

com_set --  Assigns a value to a COM component's property

Description

void com_set ( resource com_object, string property, mixed value )

Sets the value of the property of the COM component referenced by com_object. Returns the newly set value if succeeded, FALSE on error.

Example 1. Don't use com_set(), use OO syntax instead

<?php 
// do this
$obj->property = $value;
// instead of this:
com_set($obj, 'property', $value);
?>

Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.

variant_abs

(PHP 5)

variant_abs --  Returns the absolute value of a variant

Description

mixed variant_abs ( mixed val )

Returns the absolute value of val.

See also abs().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_add

(PHP 5)

variant_add --  "Adds" two variant values together and returns the result

Description

mixed variant_add ( mixed left, mixed right )

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Table 1. Variant Addition Rules

IfThen
Both expressions are of the string typeConcatenation
One expression is a string type and the other a characterAddition
One expression is numeric and the other is a stringAddition
Both expressions are numericAddition
Either expression is NULLNULL is returned
Both expressions are emptyInteger subtype is returned

See also variant_sub().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_and

(PHP 5)

variant_and --  performs a bitwise AND operation between two variants and returns the result

Description

mixed variant_and ( mixed left, mixed right )

Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.

Table 1. Variant AND Rules

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSEFALSE
TRUENULLNULL
FALSETRUEFALSE
FALSEFALSEFALSE
FALSENULLFALSE
NULLTRUENULL
NULLFALSEFALSE
NULLNULLNULL

See also variant_or().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_cast

(PHP 5)

variant_cast --  Convert a variant into a new variant object of another type

Description

variant variant_cast ( variant variant, int type )

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type. type should be one of the VT_XXX constants.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

See also variant_set_type().

variant_cat

(PHP 5)

variant_cat --  concatenates two variant values together and returns the result

Description

mixed variant_cat ( mixed left, mixed right )

Concatenates left with right and returns the result.

See also the Section called String Operators in Chapter 15 for the string concatenation operator; this function is notionally equivalent to $left . $right.

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_cmp

(PHP 5)

variant_cmp --  Compares two variants

Description

int variant_cmp ( mixed left, mixed right [, int lcid [, int flags]] )

Compares left with right and returns one of the following values:

Table 1. Variant Comparision Results

valuemeaning
VARCMP_LTleft is less than right
VARCMP_EQleft is equal to right
VARCMP_GTleft is greater than right
VARCMP_NULLEither left, right or both are NULL

This function will only compare scalar values, not arrays or variant records.

lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:

Table 2. Variant Comparision Flags

valuemeaning
NORM_IGNORECASECompare case insensitively
NORM_IGNORENONSPACEIgnore nonspacing characters
NORM_IGNORESYMBOLSIgnore symbols
NORM_IGNOREWIDTHIgnore string width
NORM_IGNOREKANATYPEIgnore Kana type
NORM_IGNOREKASHIDAIgnore Arabic kashida characters

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_date_from_timestamp

(PHP 5)

variant_date_from_timestamp --  Returns a variant date representation of a Unix timestamp

Description

variant variant_date_from_timestamp ( int timestamp )

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().

variant_date_to_timestamp

(PHP 5)

variant_date_to_timestamp --  Converts a variant date/time value to Unix timestamp

Description

int variant_date_to_timestamp ( variant variant )

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().

variant_div

(PHP 5)

variant_div --  Returns the result from dividing two variants

Description

mixed variant_div ( mixed left, mixed right )

Divides left by right and returns the result, subject to the following rules:

Table 1. Variant Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDouble is returned
One expression is a string type and the other a characterDivision and a double is returned
One expression is numeric and the other is a stringDivision and a double is returned.
Both expressions are numericDivision and a double is returned
Either expression is NULLNULL is returned
right is empty and left is anything but emptyA com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty.0 as type double is returned
Both expressions are emptyA com_exception with code DISP_E_OVERFLOW is thrown

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_eqv

(PHP 5)

variant_eqv --  Performs a bitwise equivalence on two variants

Description

mixed variant_eqv ( mixed left, mixed right )

If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_fix

(PHP 5)

variant_fix --  Returns the integer portion ? of a variant

Description

mixed variant_fix ( mixed variant )

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

See also variant_int(), variant_round(), floor(), ceil(), round().

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.

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_get_type

(PHP 5)

variant_get_type -- Returns the type of a variant object

Description

int variant_get_type ( variant variant )

This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.

variant_idiv

(PHP 5)

variant_idiv --  Converts variants to integers and then returns the result from dividing them

Description

mixed variant_idiv ( mixed left, mixed right )

Converts left and right to integer values, and then performs integer division according the following rules:

Table 1. Variant Integer Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDivision and integer is returned
One expression is a string type and the other a characterDivision
One expression is numeric and the other is a stringDivision
Both expressions are numericDivision
Either expression is NULLNULL is returned
Both expressions are emptyA com_exception with code DISP_E_DIVBYZERO is thrown

See also variant_div().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_imp

(PHP 5)

variant_imp --  Performs a bitwise implication on two variants

Description

mixed variant_imp ( mixed left, mixed right )

Performs a bitwise implication operation, according to the following truth table:

Table 1. Variant Implication Table

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSETRUE
FALSENULLTRUE
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_int

(PHP 5)

variant_int --  Returns the integer portion of a variant

Description

mixed variant_int ( mixed variant )

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

See also variant_fix(), variant_round(), floor(), ceil(), round().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_mod

(PHP 5)

variant_mod --  Divides two variants and returns only the remainder

Description

mixed variant_mod ( mixed left, mixed right )

Divides left by right and returns the remainder.

See also variant_div(), variant_idiv().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_mul

(PHP 5)

variant_mul --  multiplies the values of the two variants and returns the result

Description

mixed variant_mul ( mixed left, mixed right )

Multiplies left by right and returns the result, subject to the following rules:

Table 1. Variant Multiplication Rules

IfThen
Both expressions are of the string, date, character, boolean typeMultiplication
One expression is a string type and the other a characterMultiplication
One expression is numeric and the other is a stringMultiplication
Both expressions are numericMultiplication
Either expression is NULLNULL is returned
Both expressions are emptyEmpty string is returned

Boolean values are converted to -1 for FALSE and 0 for TRUE.

See also variant_div(), variant_idiv().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_neg

(PHP 5)

variant_neg --  Performs logical negation on a variant

Description

mixed variant_neg ( mixed variant )

Performs logical negation of variant and returns the result.

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_not

(PHP 5)

variant_not --  Performs bitwise not negation on a variant

Description

mixed variant_not ( mixed variant )

Performs bitwise not negation on variant and returns the result. If variant is NULL, the result will also be NULL.

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_or

(PHP 5)

variant_or --  Performs a logical disjunction on two variants

Description

mixed variant_or ( mixed left, mixed right )

Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.

Table 1. Variant OR Rules

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSEFALSE
FALSENULLNULL
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

See also variant_and(), variant_xor().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_pow

(PHP 5)

variant_pow --  Returns the result of performing the power function with two variants

Description

mixed variant_pow ( mixed left, mixed right )

Returns the result of left to the power of right.

See also pow().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_round

(PHP 5)

variant_round --  Rounds a variant to the specified number of decimal places

Description

mixed variant_round ( mixed variant, int decimals )

Returns the value of variant rounded to decimals decimal places.

See also round().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_set_type

(PHP 5)

variant_set_type --  Convert a variant into another type "in-place"

Description

void variant_set_type ( variant variant, int type )

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

See also variant_cast().

variant_set

(PHP 5)

variant_set --  Assigns a new value for a variant object

Description

void variant_set ( variant variant, mixed value )

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

variant_sub

(PHP 5)

variant_sub --  subtracts the value of the right variant from the left variant value and returns the result

Description

mixed variant_sub ( mixed left, mixed right )

Subtracts right from left using the following rules:

Table 1. Variant Subtraction Rules

IfThen
Both expressions are of the string typeSubtraction
One expression is a string type and the other a characterSubtraction
One expression is numeric and the other is a stringSubtraction.
Both expressions are numericSubtraction
Either expression is NULLNULL is returned
Both expressions are emptyEmpty string is returned

See also variant_add().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

variant_xor

(PHP 5)

variant_xor --  Performs a logical exclusion on two variants

Description

mixed variant_xor ( mixed left, mixed right )

Performs a logical exclusion, according to the following truth table:

Table 1. Variant XOR Rules

If left isIf right isthen the result is
TRUETRUEFALSE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
NULLNULLNULL

See also variant_and(), variant_or().

Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

XVI. Crack Functions

Introduction

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.


Requirements

More information regarding CrackLib along with the library can be found at http://sourceforge.net/projects/cracklib.


Installation

This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/crack.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with Crack support by using the --with-crack[=DIR] configuration option.

Windows users will enable php_crack.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Crack configuration options

NameDefaultChangeableChangelog
crack.default_dictionaryNULLPHP_INI_PERDIRAvailable since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.


Resource Types

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().


Predefined Constants

This extension has no constants defined.


Examples

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Example 1. CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Note: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Table of Contents
crack_check -- Performs an obscure check with the given password
crack_closedict -- Closes an open CrackLib dictionary
crack_getlastmessage -- Returns the message from the last obscure check
crack_opendict -- Opens a new CrackLib dictionary

crack_check

(PHP 4 >= 4.0.5, PECL)

crack_check -- Performs an obscure check with the given password

Description

bool crack_check ( resource dictionary, string password )

bool crack_check ( string password )

Performs an obscure check with the given password on the specified dictionary.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

dictionary

The crack lib dictionary. If not specified, the last opened dictionary is used.

password

The tested password.

Return Values

Returns TRUE if password is strong, or FALSE otherwise.

crack_closedict

(PHP 4 >= 4.0.5, PECL)

crack_closedict -- Closes an open CrackLib dictionary

Description

bool crack_closedict ( [resource dictionary] )

crack_closedict() closes the specified dictionary identifier.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Parameters

dictionary

The dictionary to close. If not specified, the current directory is closed.

Return Values

Returns TRUE on success or FALSE on failure.

crack_getlastmessage

(PHP 4 >= 4.0.5, PECL)

crack_getlastmessage -- Returns the message from the last obscure check

Description

string crack_getlastmessage ( void )

crack_getlastmessage() returns the message from the last obscure check.

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Return Values

The message from the last obscure check or FALSE if there was no obscure checks made so far.

The returned message is one of:

  • it's WAY too short

  • it is too short

  • it does not contain enough DIFFERENT characters

  • it is all whitespace

  • it is too simplistic/systematic

  • it looks like a National Insurance number.

  • it is based on a dictionary word

  • it is based on a (reversed) dictionary word

  • strong password

See Also

crack_check()

crack_opendict

(PHP 4 >= 4.0.5, PECL)

crack_opendict -- Opens a new CrackLib dictionary

Description

resource crack_opendict ( string dictionary )

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

Note: Only one dictionary may be open at a time.

Parameters

dictionary

The path to the Cracklib dictionary.

Return Values

Returns a dictionary resource identifier on success, or FALSE on failure.

XVII. Character Type Functions

Introduction

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.

Passing anything else but a string or integer will return FALSE immediately.

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.


Requirements

None besides functions from the standard C library which are always available.


Installation

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Note: Builtin support for ctype is available with PHP 4.3.0.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.

Table of Contents
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_lower -- Check for lowercase character(s)
ctype_print -- Check for printable character(s)
ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit --  Check for character(s) representing a hexadecimal digit

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum -- Check for alphanumeric character(s)

Description

bool ctype_alnum ( string text )

Checks if all of the characters in the provided string, text, are alphanumeric. In the standard C locale letters are just [A-Za-z] and the function is equivalent to preg_match('/^[a-z0-9]+$/iD', $text).

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

Examples

Example 1. A ctype_alnum() example (using the default locale)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

The above example will output:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha -- Check for alphabetic character(s)

Description

bool ctype_alpha ( string text )

Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

Examples

Example 1. A ctype_alpha() example (using the default locale)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

The above example will output:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl -- Check for control character(s)

Description

bool ctype_cntrl ( string text )

Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, escape.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.

Examples

Example 1. A ctype_cntrl() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

See Also

ctype_print()

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit -- Check for numeric character(s)

Description

bool ctype_digit ( string text )

Checks if all of the characters in the provided string, text, are numerical.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

Examples

Example 1. A ctype_digit() example

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

The above example will output:

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.

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph -- Check for any printable character(s) except space

Description

bool ctype_graph ( string text )

Checks if all of the characters in the provided string, text, creates visible output.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

Examples

Example 1. A ctype_graph() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower -- Check for lowercase character(s)

Description

bool ctype_lower ( string text )

Checks if all of the characters in the provided string, text, are lowercase letters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a lowercase letter in the current locale.

Examples

Example 1. A ctype_lower() example (using the default locale)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

The above example will output:

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print -- Check for printable character(s)

Description

bool ctype_print ( string text )

Checks if all of the characters in the provided string, text, are printable.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

Examples

Example 1. A ctype_print() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string text )

Checks if all of the characters in the provided string, text, are punctuation character.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

Examples

Example 1. A ctype_punct() example

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

The above example will output:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space -- Check for whitespace character(s)

Description

bool ctype_space ( string text )

Checks if all of the characters in the provided string, text, creates whitespace.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

Examples

Example 1. A ctype_space() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of all whitespace characters.\n";
    } else {
        echo "The string '$name' does not consist of all whitespace characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of all whitespace characters.
The string 'string2' does not consist of all whitespace characters.
The string 'string3' does not consist of all whitespace characters.

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper -- Check for uppercase character(s)

Description

bool ctype_upper ( string text )

Checks if all of the characters in the provided string, text, are uppercase characters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is an uppercase letter in the current locale.

Examples

Example 1. A ctype_upper() example (using the default locale)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

The above example will output:

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit --  Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string text )

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.

Examples

Example 1. A ctype_xdigit() example

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

The above example will output:

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.

See Also

ctype_digit()

XVIII. CURL, Client URL Library Functions

Introduction

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.


Requirements

In order to use PHP's cURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.


Installation

To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers.

Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH.

You don't need libcurl.dll from the cURL site.


Resource Types

This extension defines two resource types: a cURL handle and a cURL multi handle.


Examples

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the cURL functions to fetch the example.com homepage into a file:

Example 1. Using PHP's cURL module to fetch the example.com homepage

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Table of Contents
Constants -- Curl Predefined Constants
curl_close -- Close a cURL session
curl_copy_handle -- Copy a cURL handle along with all of its preferences
curl_errno -- Return the last error number
curl_error -- Return a string containing the last error for the current session
curl_exec -- Perform a cURL session
curl_getinfo -- Get information regarding a specific transfer
curl_init -- Initialize a cURL session
curl_multi_add_handle -- Add a normal cURL handle to a cURL multi handle
curl_multi_close -- Close a set of cURL handles
curl_multi_exec -- Run the sub-connections of the current cURL handle
curl_multi_getcontent -- Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read -- Get information about the current transfers
curl_multi_init -- Returns a new cURL multi handle
curl_multi_remove_handle -- Remove a multi handle from a set of cURL handles
curl_multi_select -- Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt_array -- Set multiple options for a cURL transfer
curl_setopt -- Set an option for a cURL transfer
curl_version -- Gets cURL version information

Constants

(no version information, might be only in CVS)

Constants -- Curl Predefined Constants

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CURLOPT_AUTOREFERER (integer)

Available since PHP 5.1.0

CURLOPT_COOKIESESSION (integer)

Available since PHP 5.1.0

CURLOPT_DNS_USE_GLOBAL_CACHE (integer)

CURLOPT_DNS_CACHE_TIMEOUT (integer)

CURLOPT_FTP_SSL (integer)

Available since PHP 5.2.0

CURLFTPSSL_TRY (integer)

Available since PHP 5.2.0

CURLFTPSSL_ALL (integer)

Available since PHP 5.2.0

CURLFTPSSL_CONTROL (integer)

Available since PHP 5.2.0

CURLFTPSSL_NONE (integer)

Available since PHP 5.2.0

CURLOPT_FTPSSLAUTH (integer)

Available since PHP 5.1.0

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_FTP_CREATE_MISSING_DIRS (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

This constant is not available when opendbase_dir or safe_mode are enabled.

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_TIMEOUT_MS (integer)

CURLOPT_TCP_NODELAY (integer)

Available since PHP 5.2.1

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_FTP_USE_EPSV (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_CONNECTTIMEOUT_MS (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_CAPATH (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLOPT_NOSIGNAL (integer)

CURLOPT_PROXYTYPE (integer)

CURLOPT_BUFFERSIZE (integer)

CURLOPT_HTTPGET (integer)

CURLOPT_HTTP_VERSION (integer)

CURLOPT_SSLKEY (integer)

CURLOPT_SSLKEYTYPE (integer)

CURLOPT_SSLKEYPASSWD (integer)

CURLOPT_SSLENGINE (integer)

CURLOPT_SSLENGINE_DEFAULT (integer)

CURLOPT_SSLCERTTYPE (integer)

CURLOPT_CRLF (integer)

CURLOPT_ENCODING (integer)

CURLOPT_PROXYPORT (integer)

CURLOPT_UNRESTRICTED_AUTH (integer)

CURLOPT_FTP_USE_EPRT (integer)

CURLOPT_HTTP200ALIASES (integer)

CURLOPT_HTTPAUTH (integer)

CURLAUTH_BASIC (integer)

CURLAUTH_DIGEST (integer)

CURLAUTH_GSSNEGOTIATE (integer)

CURLAUTH_NTLM (integer)

CURLAUTH_ANY (integer)

CURLAUTH_ANYSAFE (integer)

CURLOPT_PROXYAUTH (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_OUT (integer)

Available since PHP 6.0.0

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLINFO_STARTTRANSFER_TIME (integer)

CURLINFO_CONTENT_TYPE (integer)

CURLINFO_REDIRECT_TIME (integer)

CURLINFO_REDIRECT_COUNT (integer)

CURL_TIMECOND_IFMODSINCE (integer)

CURL_TIMECOND_IFUNMODSINCE (integer)

CURL_TIMECOND_LASTMOD (integer)

CURL_VERSION_IPV6 (integer)

CURL_VERSION_KERBEROS4 (integer)

CURL_VERSION_SSL (integer)

CURL_VERSION_LIBZ (integer)

CURLVERSION_NOW (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)

CURLE_GOT_NOTHING (integer)

CURLE_SSL_ENGINE_NOTFOUND (integer)

CURLE_SSL_ENGINE_SETFAILED (integer)

CURLE_SEND_ERROR (integer)

CURLE_RECV_ERROR (integer)

CURLE_SHARE_IN_USE (integer)

CURLE_SSL_CERTPROBLEM (integer)

CURLE_SSL_CIPHER (integer)

CURLE_SSL_CACERT (integer)

CURLE_BAD_CONTENT_ENCODING (integer)

CURLE_LDAP_INVALID_URL (integer)

CURLE_FILESIZE_EXCEEDED (integer)

CURLE_FTP_SSL_FAILED (integer)

CURLFTPAUTH_DEFAULT (integer)

Available since PHP 5.1.0

CURLFTPAUTH_SSL (integer)

Available since PHP 5.1.0

CURLFTPAUTH_TLS (integer)

Available since PHP 5.1.0

CURLPROXY_HTTP (integer)

CURLPROXY_SOCKS5 (integer)

CURL_NETRC_OPTIONAL (integer)

CURL_NETRC_IGNORED (integer)

CURL_NETRC_REQUIRED (integer)

CURL_HTTP_VERSION_NONE (integer)

CURL_HTTP_VERSION_1_0 (integer)

CURL_HTTP_VERSION_1_1 (integer)

CURLM_CALL_MULTI_PERFORM (integer)

CURLM_OK (integer)

CURLM_BAD_HANDLE (integer)

CURLM_BAD_EASY_HANDLE (integer)

CURLM_OUT_OF_MEMORY (integer)

CURLM_INTERNAL_ERROR (integer)

CURLMSG_DONE (integer)

curl_close

(PHP 4 >= 4.0.2, PHP 5)

curl_close -- Close a cURL session

Description

void curl_close ( resource ch )

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

No value is returned.

Examples

Example 1. Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

curl_copy_handle

(PHP 5)

curl_copy_handle -- Copy a cURL handle along with all of its preferences

Description

resource curl_copy_handle ( resource ch )

Copies a cURL handle keeping the same preferences.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns a new cURL handle.

Examples

Example 1. Copying a cURL handle

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close cURL resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>

curl_errno

(PHP 4 >= 4.0.3, PHP 5)

curl_errno -- Return the last error number

Description

int curl_errno ( resource ch )

Returns the error number for the last cURL operation.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns the error number or 0 (zero) if no error occurred.

curl_error

(PHP 4 >= 4.0.3, PHP 5)

curl_error -- Return a string containing the last error for the current session

Description

string curl_error ( resource ch )

Returns a clear text error message for the last cURL operation.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns the error number or '' (the empty string) if no error occurred.

curl_exec

(PHP 4 >= 4.0.2, PHP 5)

curl_exec -- Perform a cURL session

Description

mixed curl_exec ( resource ch )

Execute the given cURL session.

This function should be called after initializing a cURL session and all the options for the session are set.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Examples

Example 1. Fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5)

curl_getinfo -- Get information regarding a specific transfer

Description

mixed curl_getinfo ( resource ch [, int opt] )

Gets information about the last transfer,

Parameters

ch

A cURL handle returned by curl_init().

opt

This may be one of the following constants:

  • CURLINFO_EFFECTIVE_URL - Last effective URL

  • CURLINFO_HTTP_CODE - Last received HTTP code

  • CURLINFO_FILETIME - Remote time of the retrieved document, if -1 is returned the time of the document is unknown

  • CURLINFO_TOTAL_TIME - Total transaction time in seconds for last transfer

  • CURLINFO_NAMELOOKUP_TIME - Time in seconds until name resolving was complete

  • CURLINFO_CONNECT_TIME - Time in seconds it took to establish the connection

  • CURLINFO_PRETRANSFER_TIME - Time in seconds from start until just before file transfer begins

  • CURLINFO_STARTTRANSFER_TIME - Time in seconds until the first byte is about to be transferred

  • CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started

  • CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded

  • CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded

  • CURLINFO_SPEED_DOWNLOAD - Average download speed

  • CURLINFO_SPEED_UPLOAD - Average upload speed

  • CURLINFO_HEADER_SIZE - Total size of all headers received

  • CURLINFO_HEADER_OUT - The request string sent. Available since PHP 6.0.0

  • CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests

  • CURLINFO_SSL_VERIFYRESULT - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER

  • CURLINFO_CONTENT_LENGTH_DOWNLOAD - content-length of download, read from Content-Length: field

  • CURLINFO_CONTENT_LENGTH_UPLOAD - Specified size of upload

  • CURLINFO_CONTENT_TYPE - Content-type of downloaded object, NULL indicates server did not send valid Content-Type: header

Return Values

If opt is given, returns its value as a string. Otherwise, returns an associative array with the following elements (which correspond to opt):

  • "url"

  • "content_type"

  • "http_code"

  • "header_size"

  • "request_size"

  • "filetime"

  • "ssl_verify_result"

  • "redirect_count"

  • "total_time"

  • "namelookup_time"

  • "connect_time"

  • "pretransfer_time"

  • "size_upload"

  • "size_download"

  • "speed_download"

  • "speed_upload"

  • "download_content_length"

  • "upload_content_length"

  • "starttransfer_time"

  • "redirect_time"

curl_init

(PHP 4 >= 4.0.2, PHP 5)

curl_init -- Initialize a cURL session

Description

resource curl_init ( [string url] )

Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.

Parameters

url

If provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.

Return Values

Returns a cURL handle on success, FALSE on errors.

Examples

Example 1. Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

curl_multi_add_handle

(PHP 5)

curl_multi_add_handle -- Add a normal cURL handle to a cURL multi handle

Description

int curl_multi_add_handle ( resource mh, resource ch )

Adds the ch handle to the multi handle mh

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ch

A cURL handle returned by curl_init().

Return Values

Returns 0 on success, or one of the CURLM_XXX errors code.

Examples

Example 1. curl_multi_add_handle() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
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);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while($running > 0);

//close all the handles
curl_multi_remove_handle($ch1);
curl_multi_remove_handle($ch2);
curl_multi_close($mh);
?>

curl_multi_close

(PHP 5)

curl_multi_close -- Close a set of cURL handles

Description

void curl_multi_close ( resource mh )

Closes a set of cURL handles.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

Return Values

No value is returned.

Examples

Example 1. curl_multi_close() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
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);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while ($running > 0)
//close the handles
curl_multi_remove_handle($ch1);
curl_multi_remove_handle($ch2);
curl_multi_close($mh);

?>

curl_multi_exec

(PHP 5)

curl_multi_exec -- Run the sub-connections of the current cURL handle

Description

int curl_multi_exec ( resource mh, int &still_running )

Processes each of the handles in the stack. This method can be called whether or not a handle needs to read or write data.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

still_running

A reference to a flag to tell whether the operations are still running.

Return Values

A cURL code defined in the cURL Predefined Constants.

Note: This only returns errors regarding the whole multi stack. There might still have occurred problems on individual transfers even when this function returns CURLM_OK.

Examples

Example 1. curl_multi_exec() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
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);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while ($running > 0);
//close the handles
curl_multi_remove_handle($ch1);
curl_multi_remove_handle($ch2);
curl_multi_close($mh);

?>

curl_multi_getcontent

(PHP 5)

curl_multi_getcontent -- Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Description

string curl_multi_getcontent ( resource ch )

If CURLOPT_RETURNTRANSFER is an option that is set for a specific handle, then this function will return the content of that cURL handle in the form of a string.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set.

curl_multi_info_read

(PHP 5)

curl_multi_info_read -- Get information about the current transfers

Description

array curl_multi_info_read ( resource mh [, int msgs_in_queue] )

Ask the multi handle if there are any messages/informationals from the individual transfers. Messages may include informationals such as an error code from the transfer or just the fact that a transfer is completed.

Repeated calls to this function will return a new result each time, until a FALSE is returned as a signal that there is no more to get at this point. The integer pointed to with msgs_in_queue will contain the number of remaining messages after this function was called.

Warning

The data the returned resource points to will not survive calling curl_multi_remove_handle().

Parameters

mh

A cURL multi handle returned by curl_multi_init().

msgs_in_queue

Number of messages that are still in the queue

Return Values

On success, returns an associative array for the message, FALSE on failure.

ChangeLog

VersionDescription
5.2.0 msgs_in_queue was added.

curl_multi_init

(PHP 5)

curl_multi_init -- Returns a new cURL multi handle

Description

resource curl_multi_init ( void )

Allows the processing of multiple cURL handles in parallel.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

Return Values

Returns a cURL on handle on success, FALSE on failure.

Examples

Example 1. curl_multi_init() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
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);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while ($running > 0);

//close the handles
curl_multi_remove_handle($ch1);
curl_multi_remove_handle($ch2);
curl_multi_close($mh);

?>

curl_multi_remove_handle

(PHP 5)

curl_multi_remove_handle -- Remove a multi handle from a set of cURL handles

Description

int curl_multi_remove_handle ( resource mh, resource ch )

Removes a given ch handle from the given mh handle. When the ch handle has been removed, it is again perfectly legal to run curl_exec() on this handle. Removing a handle while being used, will effectively halt all transfers in progress.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ch

A cURL handle returned by curl_init().

Return Values

On success, returns a cURL handle, FALSE on failure.

curl_multi_select

(PHP 5)

curl_multi_select -- Get all the sockets associated with the cURL extension, which can then be "selected"

Description

int curl_multi_select ( resource mh [, float timeout] )

Get all the sockets associated with the cURL extension, which can then be "selected".

Parameters

mh

A cURL multi handle returned by curl_multi_init().

timeout

Time, in seconds, to wait for a response.

Return Values

On success, returns the number of descriptors contained in, the descriptor sets. On failure, this function will return FALSE.

curl_setopt_array

(PHP 5 CVS only)

curl_setopt_array -- Set multiple options for a cURL transfer

Description

bool curl_setopt_array ( resource ch, array options )

Sets multiple options for a cURL session. This function is useful for setting a large amount of cURL options without repetitively calling curl_setopt().

Parameters

ch

A cURL handle returned by curl_init().

options

An array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.

Return Values

Returns TRUE if all options were successfully set. If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.

Examples

Example 1. Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://www.example.com/',
                 CURLOPT_HEADER => false
                );

curl_setopt_array($ch, $options);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Prior to PHP 5.1.4 this function can be simulated with:

Example 2. Our own implementation of curl_setopt_array()

<?php
if (!function_exists('curl_setopt_array')) {
   function curl_setopt_array(&$ch, $curl_options)
   {
       foreach ($curl_options as $option => $value) {
           if (!curl_setopt($ch, $option, $value)) {
               return false;
           } 
       }
       return true;
   }
}
?>

See Also

curl_setopt()

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt -- Set an option for a cURL transfer

Description

bool curl_setopt ( resource ch, int option, mixed value )

Sets an option on the given cURL session handle.

Parameters

ch

A cURL handle returned by curl_init().

option

The CURLOPT_XXX option to set.

value

The value to be set on option.

value should be a bool for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_AUTOREFERER TRUE to automatically set the Referer: field in requests where it follows a Location: redirect. Available since PHP 5.1.0.
CURLOPT_BINARYTRANSFER TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.  
CURLOPT_COOKIESESSION TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. Available since PHP 5.1.0.
CURLOPT_CRLF TRUE to convert Unix newlines to CRLF newlines on transfers.  
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.  
CURLOPT_FAILONERROR TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.  
CURLOPT_FILETIME TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().  
CURLOPT_FOLLOWLOCATION TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).  
CURLOPT_FORBID_REUSE TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.  
CURLOPT_FRESH_CONNECT TRUE to force the use of a new connection instead of a cached one.  
CURLOPT_FTP_USE_EPRT TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only. Added in PHP 5.0.0.
CURLOPT_FTP_USE_EPSV TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.  
CURLOPT_FTPAPPEND TRUE to append to the remote file instead of overwriting it.  
CURLOPT_FTPASCII An alias of CURLOPT_TRANSFERTEXT. Use that instead.  
CURLOPT_FTPLISTONLY TRUE to only list the names of an FTP directory.  
CURLOPT_HEADER TRUE to include the header in the output.  
CURLOPT_HTTPGET TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.  
CURLOPT_HTTPPROXYTUNNEL TRUE to tunnel through a given HTTP proxy.  
CURLOPT_MUTE TRUE to be completely silent with regards to the cURL functions.  
CURLOPT_NETRC TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.  
CURLOPT_NOBODY TRUE to exclude the body from the output.  
CURLOPT_NOPROGRESS TRUE to disable the progress meter for cURL transfers.

Note: PHP automatically sets this option to TRUE, this should only be changed for debugging purposes.

 
CURLOPT_NOSIGNAL TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.  
CURLOPT_PUT TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.  
CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.  
CURLOPT_SSL_VERIFYPEER FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.
CURLOPT_TRANSFERTEXT TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.  
CURLOPT_UNRESTRICTED_AUTH TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed. Added in PHP 5.0.0.
CURLOPT_UPLOAD TRUE to prepare for an upload.  
CURLOPT_VERBOSE TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.  

value should be an integer for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_BUFFERSIZE The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_CLOSEPOLICY Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.  
CURLOPT_CONNECTTIMEOUT The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.  
CURLOPT_DNS_CACHE_TIMEOUT The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.  
CURLOPT_FTPSSLAUTH The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). Added in cURL 7.12.2 and PHP 5.1.0.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).  
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Added in PHP 5.0.0.
CURLOPT_INFILESIZE The expected size, in bytes, of the file when uploading a file to a remote site.  
CURLOPT_LOW_SPEED_LIMIT The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.  
CURLOPT_LOW_SPEED_TIME The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.  
CURLOPT_MAXCONNECTS The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.  
CURLOPT_MAXREDIRS The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.  
CURLOPT_PORT An alternative port number to connect to.  
CURLOPT_PROXYAUTH The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. Added in cURL 7.10.7 and PHP 5.1.0.
CURLOPT_PROXYPORT The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. Added in PHP 5.0.0.
CURLOPT_PROXYTYPE Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_RESUME_FROM The offset, in bytes, to resume a transfer from.  
CURLOPT_SSL_VERIFYHOST 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.  
CURLOPT_SSLVERSION The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.  
CURLOPT_TIMECONDITION How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_ISUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default. Added in PHP 5.1.0.
CURLOPT_TIMEOUT The maximum number of seconds to allow cURL functions to execute.  
CURLOPT_TIMEVALUE The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.  

value should be a string for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_CAINFO The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.  
CURLOPT_CAPATH A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.  
CURLOPT_COOKIE The contents of the "Set-Cookie: " header to be used in the HTTP request.  
CURLOPT_COOKIEFILE The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.  
CURLOPT_COOKIEJAR The name of a file to save all internal cookies to when the connection closes.  
CURLOPT_CUSTOMREQUEST A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note: Don't do this without making sure the server supports the custom request method first.

 
CURLOPT_EGBSOCKET Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.  
CURLOPT_ENCODING The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. Added in cURL 7.10.
CURLOPT_FTPPORT The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.  
CURLOPT_INTERFACE The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.  
CURLOPT_KRB4LEVEL The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.  
CURLOPT_POSTFIELDS The full data to post in a HTTP "POST" operation.  
CURLOPT_PROXY The HTTP proxy to tunnel requests through.  
CURLOPT_PROXYUSERPWD A username and password formatted as "[username]:[password]" to use for the connection to the proxy.  
CURLOPT_RANDOM_FILE A filename to be used to seed the random number generator for SSL.  
CURLOPT_RANGE Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".  
CURLOPT_REFERER The contents of the "Referer: " header to be used in a HTTP request.  
CURLOPT_SSL_CIPHER_LIST A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.  
CURLOPT_SSLCERT The name of a file containing a PEM formatted certificate.  
CURLOPT_SSLCERTPASSWD The password required to use the CURLOPT_SSLCERT certificate.  
CURLOPT_SSLCERTTYPE The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". Added in cURL 7.9.3 and PHP 5.0.0.
CURLOPT_SSLENGINE The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.  
CURLOPT_SSLENGINE_DEFAULT The identifier for the crypto engine used for asymmetric crypto operations.  
CURLOPT_SSLKEY The name of a file containing a private SSL key.  
CURLOPT_SSLKEYPASSWD The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Note: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

 
CURLOPT_SSLKEYTYPE The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".  
CURLOPT_URL The URL to fetch. This can also be set when initializing a session with curl_init().  
CURLOPT_USERAGENT The contents of the "User-Agent: " header to be used in a HTTP request.  
CURLOPT_USERPWD A username and password formatted as "[username]:[password]" to use for the connection.  

value should be an array for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HTTP200ALIASES An array of HTTP 200 responses that will be treated as valid responses and not as errors. Added in cURL 7.10.3 and PHP 5.0.0.
CURLOPT_HTTPHEADER An array of HTTP header fields to set.  
CURLOPT_POSTQUOTE An array of FTP commands to execute on the server after the FTP request has been performed.  
CURLOPT_QUOTE An array of FTP commands to execute on the server prior to the FTP request.  

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_FILE The file that the transfer should be written to. The default is STDOUT (the browser window).  
CURLOPT_INFILE The file that the transfer should be read from when uploading.  
CURLOPT_STDERR An alternative location to output errors to instead of STDERR.  
CURLOPT_WRITEHEADER The file that the header part of the transfer is written to.  

value should be a string that is the name of a valid callback function for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HEADERFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when using this callback function. Return the number of bytes written.  
CURLOPT_PASSWDFUNCTION The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.  
CURLOPT_READFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. The data must be read by using this callback function. Return the number of bytes read. Return 0 to signal EOF.  
CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be written by using this callback function. Must return the exact number of bytes written or this will fail.  

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version -- Gets cURL version information

Description

array curl_version ( [int age] )

Returns information about the cURL version.

Parameters

age

Return Values

Returns an associative array with the following elements:

version_numbercURL 24 bit version number
versioncURL version number, as a string
ssl_version_numberOpenSSL 24 bit version number
ssl_versionOpenSSL version number, as a string
libz_versionzlib version number, as a string
hostInformation about the host where cURL was built
age 
featuresA bitmask of the CURL_VERSION_XXX constants
protocolsAn array of protocols names supported by cURL

XIX. Cybercash Payment Functions

Installation

These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR].

This extension has been moved from PHP as of PHP 4.3.0 and now CyberCash lives in PECL.

If you have questions as to the latest status of CyberCash then the following CyberCash Faq will be helpful. In short, CyberCash was bought out by VeriSign and although the CyberCash service continues to exist, VeriSign encourages users to switch. See the above faq and PECL link for details.

Table of Contents
cybercash_base64_decode -- base64 decode data for Cybercash
cybercash_base64_encode -- base64 encode data for Cybercash
cybercash_decr -- Cybercash decrypt
cybercash_encr -- Cybercash encrypt

cybercash_base64_decode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_decode -- base64 decode data for Cybercash

Description

string cybercash_base64_decode ( string inbuff )

Warning

This function is currently not documented; only the argument list is available.

cybercash_base64_encode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_encode -- base64 encode data for Cybercash

Description

string cybercash_base64_encode ( string inbuff )

Warning

This function is currently not documented; only the argument list is available.

cybercash_decr

(PHP 4 <= 4.2.3, PECL)

cybercash_decr -- Cybercash decrypt

Description

array cybercash_decr ( string wmk, string sk, string inbuff )

Decrypts information.

Parameters

wmk

The merchant key.

sk

The session key.

inbuff

Return Values

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

cybercash_encr

(PHP 4 <= 4.2.3, PECL)

cybercash_encr -- Cybercash encrypt

Description

array cybercash_encr ( string wmk, string sk, string inbuff )

Encrypts information.

Parameters

wmk

The merchant key.

sk

The session key.

inbuff

URL encoded string of value pairs, i.e. order-id=12345&amount=USD+12.34&card_number=......

Return Values

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

XX. Credit Mutuel CyberMUT functions

Introduction

This extension allows you to process credit cards transactions using Credit Mutuel CyberMUT system.

CyberMUT is a popular Web Payment Service in France, provided by the Credit Mutuel bank. If you are foreign in France, these functions will not be useful for you.

The use of these functions is almost identical to the original functions, except for the parameters of return for CreerFormulaireCM and CreerReponseCM, which are returned directly by functions PHP, whereas they had passed in reference in the original functions.

Note: This extension is not available on Windows platforms.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 4.3.0


Requirements

You will require the appropriate SDK for your platform, which may be sent to you after your CyberMUT's subscription (contact them via Web, or go to the nearest Credit Mutuel).

Note: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.

Table of Contents
cybermut_creerformulairecm -- Generate HTML form of request for payment
cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmation
cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmation

cybermut_creerformulairecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerformulairecm -- Generate HTML form of request for payment

Description

string cybermut_creerformulairecm ( string url_cm, string version, string tpe, string price, string ref_command, string text_free, string url_return, string url_return_ok, string url_return_err, string language, string code_company, string text_button )

cybermut_creerformulairecm() is used to generate the HTML form of request for payment.

cybermut_creerreponsecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmation

Description

string cybermut_creerreponsecm ( string sentence )

The parameter is "OK" if the message of confirmation of the payment were correctly authenticated by cybermut_testmac(). Any other chain is regarded as an error message.

Return Values

Returns a string containing the message of acknowledgement of delivery.

cybermut_testmac

(4.0.5 - 4.2.3 only, PECL)

cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmation

Description

bool cybermut_testmac ( string code_mac, string version, string tpe, string cdate, string price, string ref_command, string text_free, string code_return )

cybermut_testmac() is used to make sure that there was no data diddling contained in the received message of confirmation. Pay attention to parameters code_return and text_free, which cannot be evaluated as is, because of the dash.

XXI. Cyrus IMAP administration Functions

Introduction

Warning

This function is currently not documented; only the argument list is available.

Note: This extension is not available on Windows platforms.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.


Installation

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they both share the same internal symbol.


Resource Types

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

Table of Contents
cyrus_authenticate -- Authenticate against a Cyrus IMAP server
cyrus_bind -- Bind callbacks to a Cyrus IMAP connection
cyrus_close -- Close connection to a Cyrus IMAP server
cyrus_connect -- Connect to a Cyrus IMAP server
cyrus_query -- Send a query to a Cyrus IMAP server
cyrus_unbind -- Unbind ...

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL)

cyrus_authenticate -- Authenticate against a Cyrus IMAP server

Description

void cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf [, string authname [, string password]]]]]]] )

Warning

This function is currently not documented; only the argument list is available.

cyrus_bind

(PHP 4 >= 4.1.0, PECL)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks )

Warning

This function is currently not documented; only the argument list is available.

cyrus_close

(PHP 4 >= 4.1.0, PECL)

cyrus_close -- Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource connection )

Warning

This function is currently not documented; only the argument list is available.

cyrus_connect

(PHP 4 >= 4.1.0, PECL)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]] )

Warning

This function is currently not documented; only the argument list is available.

cyrus_query

(PHP 4 >= 4.1.0, PECL)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

array cyrus_query ( resource connection, string query )

Warning

This function is currently not documented; only the argument list is available.

cyrus_unbind

(PHP 4 >= 4.1.0, PECL)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name )

Warning

This function is currently not documented; only the argument list is available.

XXII. Date and Time Functions

Introduction

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Note: The timezones referenced in this section can be found in the Appendix J.


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

Note: The latest version of the timezone database can be installed via PECL's timezonedb. For Windows users, a pre-compiled DLL can be downloaded from the PECL4Win site: php_timezonedb.dll.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Date/Time Configuration Options

NameDefaultChangeableChangelog
date.default_latitude"31.7667"PHP_INI_ALLAvailable since PHP 5.0.0.
date.default_longitude"35.2333"PHP_INI_ALLAvailable since PHP 5.0.0.
date.sunrise_zenith"90.83"PHP_INI_ALLAvailable since PHP 5.0.0.
date.sunset_zenith"90.83"PHP_INI_ALLAvailable since PHP 5.0.0.
date.timezone""PHP_INI_ALLAvailable since PHP 5.1.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

date.default_latitude float

The default latitude.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions if the TZ environment variable isn't set. The precedence order is described in the date_default_timezone_get() page. See Appendix J for a list of supported timezones.

Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().


Resource Types

This extension has no resource types defined.


Predefined Constants

The following constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

DATE_ATOM (string)

Atom (example: 2005-08-15T15:52:01+00:00)

DATE_COOKIE (string)

HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)

DATE_ISO8601 (string)

ISO-8601 (example: 2005-08-15T15:52:01+0000)

DATE_RFC822 (string)

RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)

DATE_RFC850 (string)

RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)

DATE_RFC1036 (string)

RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)

DATE_RFC1123 (string)

RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)

DATE_RFC2822 (string)

RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)

DATE_RFC3339 (string)

Same as DATE_ATOM (since PHP 5.1.3)

DATE_RSS (string)

RSS (Mon, 15 Aug 2005 15:52:01 +0000)

DATE_W3C (string)

World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)

Timestamp

SUNFUNCS_RET_STRING (integer)

Hours:minutes (example: 08:02)

SUNFUNCS_RET_DOUBLE (integer)

Hours as floating point number (example 8.75)

Table of Contents
checkdate -- Validate a Gregorian date
date_create -- Returns new DateTime object
date_date_set -- Sets the date
date_default_timezone_get --  Gets the default timezone used by all date/time functions in a script
date_default_timezone_set --  Sets the default timezone used by all date/time functions in a script
date_format -- Returns date formatted according to given format
date_isodate_set -- Sets the ISO date
date_modify -- Alters the timestamp
date_offset_get -- Returns the daylight saving time offset
date_parse -- Returns associative array with detailed info about given date
date_sun_info -- Returns an array with information about sunset/sunrise and twilight begin/end
date_sunrise -- Returns time of sunrise for a given day and location
date_sunset --  Returns time of sunset for a given day and location
date_time_set -- Sets the time
date_timezone_get -- Return time zone relative to given DateTime
date_timezone_set -- Sets the time zone for the DateTime object
date -- Format a local time/date
getdate -- Get date/time information
gettimeofday -- Get current time
gmdate -- Format a GMT/UTC date/time
gmmktime -- Get Unix timestamp for a GMT date
gmstrftime -- Format a GMT/UTC time/date according to locale settings
idate -- Format a local time/date as integer
localtime -- Get the local time
microtime -- Return current Unix timestamp with microseconds
mktime -- Get Unix timestamp for a date
strftime -- Format a local time/date according to locale settings
strptime --  Parse a time/date generated with strftime()
strtotime -- Parse about any English textual datetime description into a Unix timestamp
time -- Return current Unix timestamp
timezone_abbreviations_list -- Returns associative array containing dst, offset and the timezone name
timezone_identifiers_list -- Returns numerically index array with all timezone identifiers
timezone_name_from_abbr -- Returns the timezone name from abbrevation
timezone_name_get -- Returns the name of the timezone
timezone_offset_get -- Returns the timezone offset from GMT
timezone_open -- Returns new DateTimeZone object
timezone_transitions_get -- Returns all transitions for the timezone

checkdate

(PHP 3, PHP 4, PHP 5)

checkdate -- Validate a Gregorian date

Description

bool checkdate ( int month, int day, int year )

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters

month

The month is between 1 and 12 inclusive.

day

The day is within the allowed number of days for the given month. Leap years are taken into consideration.

year

The year is between 1 and 32767 inclusive.

Return Values

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples

Example 1. checkdate() example

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

The above example will output:

bool(true)
bool(false)

date_create

(PHP 5 >= 5.1.0RC1)

date_create -- Returns new DateTime object

Description

DateTime date_create ( [string time [, DateTimeZone timezone]] )

DateTime DateTime::__construct ( [string time [, DateTimeZone timezone]] )

Parameters

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

Return Values

Returns DateTime object on success or FALSE on failure.

date_date_set

(no version information, might be only in CVS)

date_date_set -- Sets the date

Description

void date_date_set ( DateTime object, int year, int month, int day )

void DateTime::setDate ( int year, int month, int day )

Parameters

object

DateTime object.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Return Values

Returns NULL on success or FALSE on failure.

date_default_timezone_get

(PHP 5 >= 5.1.0RC1)

date_default_timezone_get --  Gets the default timezone used by all date/time functions in a script

Description

string date_default_timezone_get ( void )

This functions returns the default timezone, using the following "guess" order:

  • The timezone set using the date_default_timezone_set() function (if any)

  • The TZ environment variable (if non empty)

  • The date.timezone ini option (if set)

  • "magical" guess (if the operating system supports it)

  • If none of the above options succeeds, return UTC

Return Values

Returns a string.

date_default_timezone_set

(PHP 5 >= 5.1.0RC1)

date_default_timezone_set --  Sets the default timezone used by all date/time functions in a script

Description

bool date_default_timezone_set ( string timezone_identifier )

date_default_timezone_set() sets the default timezone used by all date/time functions.

Note: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_STRICT message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

Parameters

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendix J.

Return Values

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

ChangeLog

VersionDescription
5.1.2 The function started to validate the timezone_identifier parameter.

date_format

(PHP 5 >= 5.1.0RC1)

date_format -- Returns date formatted according to given format

Description

string date_format ( DateTime object, string format )

string DateTime::format ( string format )

Parameters

object

DateTime object.

format

Format accepted by date().

Return Values

Returns formatted date on success or FALSE on failure.

See Also

date()

date_isodate_set

(no version information, might be only in CVS)

date_isodate_set -- Sets the ISO date

Description

void date_isodate_set ( DateTime object, int year, int week [, int day] )

void DateTime::setISODate ( int year, int week [, int day] )

Parameters

object

DateTime object.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Return Values

Returns NULL on success or FALSE on failure.

See Also

date_date_set()

date_modify

(PHP 5 >= 5.1.0RC1)

date_modify -- Alters the timestamp

Description

void date_modify ( DateTime object, string modify )

void DateTime::modify ( string modify )

Parameters

object

DateTime object.

modify

String in a relative format accepted by strtotime().

Return Values

Returns NULL on success or FALSE on failure.

Examples

Example 1. A date_modify() example

<?php
$date = new DateTime("2006-12-12");
$date->modify("+1 day");
echo $date->format("Y-m-d");
?>

The above example will output:

2006-12-13

See Also

strtotime()

date_offset_get

(PHP 5 >= 5.1.0RC1)

date_offset_get -- Returns the daylight saving time offset

Description

int date_offset_get ( DateTime object )

int DateTime::getOffset ( void )

Parameters

object

DateTime object.

Return Values

Returns DST offset in seconds on success or FALSE on failure.

date_parse

(no version information, might be only in CVS)

date_parse -- Returns associative array with detailed info about given date

Description

array date_parse ( string date )

Parameters

date

Date in format accepted by strtotime().

Return Values

Returns array on success or FALSE on failure.

Examples

Example 1. A date_parse() example

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

The above example will output:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)

See Also

getdate()

date_sun_info

(no version information, might be only in CVS)

date_sun_info -- Returns an array with information about sunset/sunrise and twilight begin/end

Description

array date_sun_info ( int time, float latitude, float longitude )

Parameters

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Return Values

Returns array on success or FALSE on failure.

Examples

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";
}
?>

The above example will output:

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

date_sunrise

(PHP 5)

date_sunrise -- Returns time of sunrise for a given day and location

Description

mixed date_sunrise ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location.

Parameters

timestamp

The timestamp of the day from which the sunrise time is taken.

format

Table 1. format constants

constantdescriptionexample
SUNFUNCS_RET_STRINGreturns the result as string16:46
SUNFUNCS_RET_DOUBLEreturns the result as float16.78243132
SUNFUNCS_RET_TIMESTAMPreturns the result as integer (timestamp)1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunrise_zenith

gmtoffset

Specified in hours.

Return Values

Returns the sunrise time in a specified format on success, or FALSE on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunrise time : 08:54

See Also

date_sunset()

date_sunset

(PHP 5)

date_sunset --  Returns time of sunset for a given day and location

Description

mixed date_sunset ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

date_sunset() returns the sunset time for a given day (specified as a timestamp) and location.

Parameters

timestamp

The timestamp of the day from which the sunset time is taken.

format

Table 1. format constants

constantdescriptionexample
SUNFUNCS_RET_STRINGreturns the result as string16:46
SUNFUNCS_RET_DOUBLEreturns the result as float16.78243132
SUNFUNCS_RET_TIMESTAMPreturns the result as integer (timestamp)1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunrise_zenith

gmtoffset

Specified in hours.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Return Values

Returns the sunset time in a specified format on success, or FALSE on failure.

Examples

Example 1. date_sunset() example

<?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);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunset time : 18:13

See Also

date_sunrise()

date_time_set

(no version information, might be only in CVS)

date_time_set -- Sets the time

Description

void date_time_set ( DateTime object, int hour, int minute [, int second] )

void DateTime::setTime ( int hour, int minute [, int second] )

Parameters

object

DateTime object.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Return Values

Returns NULL on success or FALSE on failure.

See Also

date_date_set()

date_timezone_get

(PHP 5 >= 5.1.0RC1)

date_timezone_get -- Return time zone relative to given DateTime

Description

DateTimeZone date_timezone_get ( DateTime object )

DateTimeZone DateTime::getTimezone ( void )

Parameters

object

DateTime object.

Return Values

Returns DateTimeZone object on success or FALSE on failure.

date_timezone_set

(PHP 5 >= 5.1.0RC1)

date_timezone_set -- Sets the time zone for the DateTime object

Description

void date_timezone_set ( DateTime object, DateTimeZone timezone )

void DateTime::setTimezone ( DateTimeZone timezone )

Parameters

object

DateTime object.

timezone

Desired time zone.

Return Values

Returns NULL on success or FALSE on failure.

date

(PHP 3, PHP 4, PHP 5)

date -- Format a local time/date

Description

string date ( string format [, int timestamp] )

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Parameters

format

The format of the outputted date string. See the formatting options below.

Table 1. The following characters are recognized in the format parameter string

format characterDescriptionExample returned values
Day------
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
l (lowercase 'L')A full textual representation of the day of the weekSunday through Saturday
NISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0)0 through 365
Week------
WISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)Example: 42 (the 42nd week in the year)
Month------
FA full textual representation of a month, such as January or MarchJanuary through December
mNumeric representation of a month, with leading zeros01 through 12
MA short textual representation of a month, three lettersJan through Dec
nNumeric representation of a month, without leading zeros1 through 12
tNumber of days in the given month28 through 31
Year------
LWhether it's a leap year1 if it is a leap year, 0 otherwise.
oISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)Examples: 1999 or 2003
YA full numeric representation of a year, 4 digitsExamples: 1999 or 2003
yA two digit representation of a yearExamples: 99 or 03
Time------
aLowercase Ante meridiem and Post meridiemam or pm
AUppercase Ante meridiem and Post meridiemAM or PM
BSwatch Internet time000 through 999
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
iMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 through 59
uMilliseconds (added in PHP 5.2.2)Example: 54321
Timezone------
eTimezone identifier (added in PHP 5.1.0)Examples: UTC, GMT, Atlantic/Azores
I (capital i)Whether or not the date is in daylight saving time1 if Daylight Saving Time, 0 otherwise.
ODifference to Greenwich time (GMT) in hoursExample: +0200
PDifference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)Example: +02:00
TTimezone abbreviationExamples: EST, MDT ...
ZTimezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200 through 50400
Full Date/Time------
cISO 8601 date (added in PHP 5)2004-02-12T15:19:21+00:00
rRFC 2822 formatted dateExample: Thu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.

Examples

Example 1. date() examples

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 15th of August 2005 03:12:46 PM
echo date('l dS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example 2. Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example 3. date() and mktime() example

<?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: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example 4. date() Formatting

<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17
?>

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

Notes

Note: To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's UNIX_TIMESTAMP function).

Tip: Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

getdate

(PHP 3, PHP 4, PHP 5)

getdate -- Get date/time information

Description

array getdate ( [int timestamp] )

Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an associative array of information related to the typestamp. Elements from the returned associative array are as follows:

Table 1. Key elements of the returned associative array

KeyDescriptionExample returned values
"seconds"Numeric representation of seconds0 to 59
"minutes"Numeric representation of minutes0 to 59
"hours"Numeric representation of hours0 to 23
"mday"Numeric representation of the day of the month1 to 31
"wday"Numeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
"mon"Numeric representation of a month1 through 12
"year"A full numeric representation of a year, 4 digitsExamples: 1999 or 2003
"yday"Numeric representation of the day of the year0 through 365
"weekday"A full textual representation of the day of the weekSunday through Saturday
"month"A full textual representation of a month, such as January or MarchJanuary through December
0 Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). System Dependent, typically -2147483648 through 2147483647.

Examples

Example 1. getdate() example

<?php
$today = getdate();
print_r($today);
?>

The above example will output something similar to:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

gettimeofday

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

gettimeofday -- Get current time

Description

mixed gettimeofday ( [bool return_float] )

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

Parameters

return_float

When set to TRUE, a float instead of an array is returned.

Return Values

By default an array is returned. If return_float is set, then a float is returned.

Array keys:

  • "sec" - seconds since the Unix Epoch

  • "usec" - microseconds

  • "minuteswest" - minutes west of Greenwich

  • "dsttime" - type of dst correction

ChangeLog

VersionDescription
5.1.0 The return_float parameter was added.

Examples

Example 1. gettimeofday() example

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

The above example will output something similar to:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

gmdate

(PHP 3, PHP 4, PHP 5)

gmdate -- Format a GMT/UTC date/time

Description

string gmdate ( string format [, int timestamp] )

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

Parameters

format

The format of the outputted date string. See the formatting options for the date() function.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

ChangeLog

VersionDescription
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.

Examples

Example 1. gmdate() example

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "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));
?>

gmmktime

(PHP 3, PHP 4, PHP 5)

gmmktime -- Get Unix timestamp for a GMT date

Description

int gmmktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

Parameters

hour

The hour

minute

The minute

second

The second

month

The month

day

The day

year

The year

is_dst

Parameters always represent a GMT date so is_dst doesn't influence the result.

Return Values

Returns a integer Unix timestamp.

ChangeLog

VersionDescription
5.1.0 As of PHP 5.1.0, the is_dst parameter became deprecated. As a result, the new timezone handling features should be used instead.

Examples

Example 1. gmmktime() on Windows boundary

<?php
gmmktime(0, 0, 0, 1, 1, 1970); // valid in GMT and west, invalid in east
?>

gmstrftime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

gmstrftime -- Format a GMT/UTC time/date according to locale settings

Description

string gmstrftime ( string format [, int timestamp] )

Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".

Examples

Example 1. gmstrftime() example

<?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";
?>

See Also

strftime()

idate

(PHP 5)

idate -- Format a local time/date as integer

Description

int idate ( string format [, int timestamp] )

Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the format parameter.

Parameters

format

Table 1. The following characters are recognized in the format parameter string

format characterDescription
BSwatch Beat/Internet Time
dDay of the month
hHour (12 hour format)
HHour (24 hour format)
iMinutes
Ireturns 1 if DST is activated, 0 otherwise
Lreturns 1 for leap year, 0 otherwise
mMonth number
sSeconds
tDays in current month
USeconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time()
wDay of the week (0 on Sunday)
WISO-8601 week number of year, weeks starting on Monday
yYear (1 or 2 digits - check note below)
YYear (4 digits)
zDay of the year
ZTimezone offset in seconds

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. idate() example

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp);
?>

See Also

date()
time()

localtime

(PHP 4, PHP 5)

localtime -- Get the local time

Description

array localtime ( [int timestamp [, bool is_associative]] )

The localtime() function returns an array identical to that of the structure returned by the C function call.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

is_associative

If set to FALSE or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds

  • "tm_min" - minutes

  • "tm_hour" - hour

  • "tm_mday" - day of the month

    Months are from 0 (Jan) to 11 (Dec) and days of the week are from 0 (Sun) to 6 (Sat).

  • "tm_mon" - month of the year, starting with 0 for January

  • "tm_year" - Years since 1900

  • "tm_wday" - Day of the week

  • "tm_yday" - Day of the year

  • "tm_isdst" - Is daylight savings time in effect

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. localtime() example

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

The above example will output something similar to:

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
)

microtime

(PHP 3, PHP 4, PHP 5)

microtime -- Return current Unix timestamp with microseconds

Description

mixed microtime ( [bool get_as_float] )

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

Parameters

get_as_float

When called without the optional argument, this function returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. Both portions of the string are returned in units of seconds.

If the optional get_as_float is set to TRUE then a float (in seconds) is returned.

ChangeLog

VersionDescription
5.0.0 The get_as_float parameter was added.

Examples

Example 1. Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example 2. Timing script execution in PHP 5

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

See Also

time()

mktime

(PHP 3, PHP 4, PHP 5)

mktime -- Get Unix timestamp for a date

Description

int mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

Parameters

hour

The number of the hour.

minute

The number of the minute.

second

The number of seconds past the minute.

month

The number of the month.

day

The number of the day.

year

The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1901 and 2038, although this limitation is overcome as of PHP 5.1.0.

is_dst

This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
3.0.10Added is_dst parameter
5.1.0 The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. mktime() example

mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "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 2. Last day of next month

The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "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);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

strftime

(PHP 3, PHP 4, PHP 5)

strftime -- Format a local time/date according to locale settings

Description

string strftime ( string format [, int timestamp] )

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().

Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. %e, %T, %R and %D (there might be more) and dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems a complete overview of supported conversion specifiers can be found at this MSDN website.

Parameters

format

The following conversion specifiers are recognized in the format string:

  • %a - abbreviated weekday name according to the current locale

  • %A - full weekday name according to the current locale

  • %b - abbreviated month name according to the current locale

  • %B - full month name according to the current locale

  • %c - preferred date and time representation for the current locale

  • %C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)

  • %d - day of the month as a decimal number (range 01 to 31)

  • %D - same as %m/%d/%y

  • %e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')

  • %g - like %G, but without the century.

  • %G - The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead.

  • %h - same as %b

  • %H - hour as a decimal number using a 24-hour clock (range 00 to 23)

  • %I - hour as a decimal number using a 12-hour clock (range 01 to 12)

  • %j - day of the year as a decimal number (range 001 to 366)

  • %m - month as a decimal number (range 01 to 12)

  • %M - minute as a decimal number

  • %n - newline character

  • %p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale

  • %r - time in a.m. and p.m. notation

  • %R - time in 24 hour notation

  • %S - second as a decimal number

  • %t - tab character

  • %T - current time, equal to %H:%M:%S

  • %u - weekday as a decimal number [1,7], with 1 representing Monday

    Warning

    Sun Solaris seems to start with Sunday as 1 although ISO 9889:1999 (the current C standard) clearly specifies that it should be Monday.

  • %U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week

  • %V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.)

  • %W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week

  • %w - day of the week as a decimal, Sunday being 0

  • %x - preferred date representation for the current locale without the time

  • %X - preferred time representation for the current locale without the date

  • %y - year as a decimal number without a century (range 00 to 99)

  • %Y - year as a decimal number including the century

  • %Z or %z - time zone or name or abbreviation

  • %% - a literal `%' character

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

This example works if you have the respective locales installed in your system.

Example 1. strftime() locale examples

<?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   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Notes

Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.

strptime

(PHP 5 >= 5.1.0RC1)

strptime --  Parse a time/date generated with strftime()

Description

array strptime ( string date, string format )

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

Note: This function is not implemented on Windows platforms.

Parameters

date (string)

The string to parse (e.g. returned from strftime())

format (string)

The format used in date (e.g. the same as used in strftime()).

For more information about the format options, read the strftime() page.

Return Values

Returns an array, or FALSE on failure.

Table 1. The following parameters are returned in the array

parametersDescription
tm_secSeconds after the minute (0-61)
tm_minMinutes after the hour (0-59)
tm_hourHour since midnight (0-23)
tm_mdayDay of the month (1-31)
tm_monMonths since January (0-11)
tm_yearYears since 1900
tm_wdayDays since Sunday (0-6)
tm_ydayDays since January 1 (0-365)
unparsedthe date part which was not recognized using the specified format

Examples

Example 1. strptime() example

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

The above example will output something similar to:

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] =>
)

See Also

strftime()

strtotime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

strtotime -- Parse about any English textual datetime description into a Unix timestamp

Description

int strtotime ( string time [, int now] )

The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT), relative to the timestamp given in now, or the current time if none is supplied.

This function will use the TZ environment variable (if available) to calculate the timestamp. Since PHP 5.1.0 there are easier ways to define the timezone that is used across all date/time functions. That process is explained in the date_default_timezone_get() function page.

Note: If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999.

Parameters

time

The string to parse, according to the GNU Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

now

The timestamp used to calculate the returned value.

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

VersionDescription
5.1.0 It now returns FALSE on failure, instead of -1.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. A strtotime() example

<?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. Checking for failure

<?php
$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

Notes

Warning

In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. It differs from other versions where it is correctly computed from current time.

Warning

In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

See Also

strptime()

time

(PHP 3, PHP 4, PHP 5)

time -- Return current Unix timestamp

Description

int time ( void )

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Examples

Example 1. time() example

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Notes

Tip: Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

timezone_abbreviations_list

(PHP 5 >= 5.1.0RC1)

timezone_abbreviations_list -- Returns associative array containing dst, offset and the timezone name

Description

array timezone_abbreviations_list ( void )

array DateTimeZone::listAbbreviations ( void )

Return Values

Returns array on success or FALSE on failure.

Examples

Example 1. A timezone_abbreviations_list() example

<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

The above example will output something similar to:

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

(PHP 5 >= 5.1.0RC1)

timezone_identifiers_list -- Returns numerically index array with all timezone identifiers

Description

array timezone_identifiers_list ( void )

array DateTimeZone::listIdentifiers ( void )

Return Values

Returns array on success or FALSE on failure.

Examples

Example 1. A timezone_identifiers_list() example

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
	echo "$timezone_identifiers[$i]\n";
}
?>

The above example will output something similar to:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmera

timezone_name_from_abbr

(no version information, might be only in CVS)

timezone_name_from_abbr -- Returns the timezone name from abbrevation

Description

string timezone_name_from_abbr ( string abbr [, int gmtOffset [, int isdst]] )

Parameters

abbr

Time zone abbreviation.

gmtOffset

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. If abbr doesn't exist then the time zone is searched solely by offset and isdst.

Return Values

Returns time zone name on success or FALSE on failure.

Examples

Example 1. A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>

The above example will output something similar to:

Europe/Berlin
Europe/Paris

timezone_name_get

(PHP 5 >= 5.1.0RC1)

timezone_name_get -- Returns the name of the timezone

Description

string timezone_name_get ( DateTimeZone object )

string DateTimeZone::getName ( void )

Parameters

object

DateTimeZone object.

Return Values

Returns time zone name on success or FALSE on failure.

timezone_offset_get

(PHP 5 >= 5.1.0RC1)

timezone_offset_get -- Returns the timezone offset from GMT

Description

int timezone_offset_get ( DateTimeZone object, DateTime datetime )

int DateTimeZone::getOffset ( DateTime datetime )

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTime object being used.

Parameters

object

DateTimeZone object.

datetime

DateTime that contains the date/time to compute the offset from.

Return Values

Returns time zone offset in seconds on success or FALSE on failure.

Examples

Example 1. timezone_offset_get() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>

timezone_open

(PHP 5 >= 5.1.0RC1)

timezone_open -- Returns new DateTimeZone object

Description

DateTimeZone timezone_open ( string timezone )

DateTimeZone DateTimeZone::__construct ( string timezone )

Parameters

timezone

Time zone identifier as full name (e.g. Europe/Prague) or abbreviation (e.g. CET).

Return Values

Returns DateTimeZone object on success or FALSE on failure.

timezone_transitions_get

(no version information, might be only in CVS)

timezone_transitions_get -- Returns all transitions for the timezone

Description

array timezone_transitions_get ( DateTimeZone object )

array DateTimeZone::getTransitions ( void )

Parameters

object

DateTimeZone object.

Return Values

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Examples

Example 1. A timezone_transitions_get() example

<?php
$timezone = new DateTimeZone("CET");
print_r(reset($timezone->getTransitions()));
?>

The above example will output something similar to:

Array
(
    [ts] => -1693706400
    [time] => 1916-04-30T22:00:00+0000
    [offset] => 7200
    [isdst] => 1
    [abbr] => CEST
)

XXIII. DB++ Functions

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.


Introduction

db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra than SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.


Requirements

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

Concept asa provides db++ Demo versions and documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).


Installation

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.


db++ error codes

Table 1. DB++ Error Codes

PHP Constantdb++ constantmeaning
DBPLUS_ERR_NOERR (integer) ERR_NOERRNull error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATETried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCANEnd of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTYRelation is empty (server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSEThe server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKEDThe record is write locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKEDRelation was already locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCKRelation cannot be locked
DBPLUS_ERR_READ (integer) ERR_READRead error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITEWrite error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATECreate() system call failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEKLseek() system call failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTHTuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) ERR_OPENOpen() system call failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPENRelation already opened for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGICFile is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSIONFile is a very old relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZERelation uses a different page size
DBPLUS_ERR_CRC (integer) ERR_CRCInvalid crc in the superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPEPiped relation requires lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDXToo many secondary indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOCMalloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERSError use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXITCaused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAPCaused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROCError in the preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSEError in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERRRun error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXITExit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAITWait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) ERR_CORRUPT_TUPLEA client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) ERR_WARNING0 The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) ERR_PANIC The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) ERR_FIFOCan't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERMPermission denied
DBPLUS_ERR_TCL (integer) ERR_TCLTCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTEDOnly two users
DBPLUS_ERR_USER (integer) ERR_USER An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) ERR_UNKNOWN 

Table of Contents
dbplus_add -- Add a tuple to a relation
dbplus_aql -- Perform AQL query
dbplus_chdir -- Get/Set database virtual current directory
dbplus_close -- Close a relation
dbplus_curr -- Get current tuple from relation
dbplus_errcode -- Get error string for given errorcode or last error
dbplus_errno -- Get error code for last operation
dbplus_find -- Set a constraint on a relation
dbplus_first -- Get first tuple from relation
dbplus_flush -- Flush all changes made on a relation
dbplus_freealllocks -- Free all locks held by this client
dbplus_freelock -- Release write lock on tuple
dbplus_freerlocks -- Free all tuple locks on given relation
dbplus_getlock -- Get a write lock on a tuple
dbplus_getunique -- Get an id number unique to a relation
dbplus_info -- Get information about a relation
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_restorepos -- Restore position
dbplus_rkeys -- Specify new primary key for a relation
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex -- Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- Save position
dbplus_setindex -- Set index
dbplus_setindexbynumber -- Set index by number
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- Undo
dbplus_undoprepare -- Prepare undo
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(4.1.0 - 4.2.3 only, PECL)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple )

Adds a tuple to a relation.

Parameters

relation

tuple

An array of attribute/value pairs to be inserted into the given relation.

After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

Return Values

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_aql

(4.1.0 - 4.2.3 only, PECL)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]] )

Executes an AQL query on the given server and dbpath.

Parameters

query

The AQL query to be executed. Further information on the AQL A... Query Language is provided in the original db++ manual.

server

dbpath

Return Values

Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_chdir

(4.1.0 - 4.2.3 only, PECL)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir] )

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parameters

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Return Values

Returns the absolute path of the current directory.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_close

(4.1.0 - 4.2.3 only, PECL)

dbplus_close -- Close a relation

Description

mixed dbplus_close ( resource relation )

Closes a relation previously opened by dbplus_open().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_curr

(4.1.0 - 4.2.3 only, PECL)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array &tuple )

Reads the data for the current tuple for the given relation.

Parameters

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Return Values

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_errcode

(4.1.0 - 4.2.3 only, PECL)

dbplus_errcode -- Get error string for given errorcode or last error

Description

string dbplus_errcode ( [int errno] )

Returns a clear error string for the given error code.

Parameters

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Return Values

Returns the error message.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_errno

(4.1.0 - 4.2.3 only, PECL)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void )

Returns the error code returned by the last db++ operation.

Return Values

Returns the error code, as an integer.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_find

(4.1.0 - 4.2.3 only, PECL)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple )

Places a constraint on the given relation.

Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Parameters

relation

A relation opened by dbplus_open().

constraints

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_first

(4.1.0 - 4.2.3 only, PECL)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array &tuple )

Reads the data for the first tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_flush

(4.1.0 - 4.2.3 only, PECL)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation )

Writes all changes applied to relation since the last flush to disk.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_freealllocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void )

Frees all tuple locks held by this client.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_freelock

(4.1.0 - 4.2.3 only, PECL)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tuple )

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_freerlocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation )

Frees all tuple locks held on the given relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_getlock

(4.1.0 - 4.2.3 only, PECL)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tuple )

Requests a write lock on the specified tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_getunique

(4.1.0 - 4.2.3 only, PECL)

dbplus_getunique -- Get an id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid )

Obtains a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

Parameters

relation

A relation opened by dbplus_open().

uniqueid

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_info

(4.1.0 - 4.2.3 only, PECL)

dbplus_info -- Get information about a relation

Description

int dbplus_info ( resource relation, string key, array &result )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

key

result

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_last

(4.1.0 - 4.2.3 only, PECL)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array &tuple )

Reads the data for the last tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation )

Requests a write lock on the given relation.

Other clients may still query the relation, but can't alter it while it is locked.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_next

(4.1.0 - 4.2.3 only, PECL)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array &tuple )

Reads the data for the next tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_open

(4.1.0 - 4.2.3 only, PECL)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name )

Opens the given relation file.

Parameters

name

Can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

Return Values

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_prev

(4.1.0 - 4.2.3 only, PECL)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array &tuple )

Reads the data for the previous tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rchperm

(4.1.0 - 4.2.3 only, PECL)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group )

Changes access permissions as specified by mask, user and group. The values for these are operating system specific.

Parameters

relation

A relation opened by dbplus_open().

mask

user

group

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rcreate

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, bool overwrite] )

Creates a new relation. Any existing relation sharing the same name will be overwritten if the relation is currently not in use and overwrite is set to TRUE.

Parameters

name

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

This parameter should contain the domain specification for the new relation within an array of domain description strings. A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Note: This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rcrtexact

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

mixed dbplus_rcrtexact ( string name, resource relation [, bool overwrite] )

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rcrtlike

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

mixed dbplus_rcrtlike ( string name, resource relation [, int overwrite] )

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_resolve

(4.1.0 - 4.2.3 only, PECL)

dbplus_resolve -- Resolve host information for relation

Description

array dbplus_resolve ( string relation_name )

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host.

Parameters

relation_name

The relation name.

Return Values

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

See Also

dbplus_tcl()

dbplus_restorepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_restorepos -- Restore position

Description

int dbplus_restorepos ( resource relation, array tuple )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rkeys

(4.1.0 - 4.2.3 only, PECL)

dbplus_rkeys -- Specify new primary key for a relation

Description

mixed dbplus_rkeys ( resource relation, mixed domlist )

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_ropen

(4.1.0 - 4.2.3 only, PECL)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name )

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

Parameters

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rquery

(4.1.0 - 4.2.3 only, PECL)

dbplus_rquery -- Perform local (raw) AQL query

Description

resource dbplus_rquery ( string query [, string dbpath] )

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

Parameters

query

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rrename

(4.1.0 - 4.2.3 only, PECL)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name )

dbplus_rrename() will change the name of relation to name.

Parameters

relation

A relation opened by dbplus_open().

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rsecindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_rsecindex -- Create a new secondary index for a relation

Description

mixed dbplus_rsecindex ( resource relation, mixed domlist, int type )

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

type

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_runlink

(4.1.0 - 4.2.3 only, PECL)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation )

dbplus_unlink() will close and remove the relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_rzap

(4.1.0 - 4.2.3 only, PECL)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation )

dbplus_rzap() will remove all tuples from relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_savepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_savepos -- Save position

Description

int dbplus_savepos ( resource relation )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_setindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindex -- Set index

Description

int dbplus_setindex ( resource relation, string idx_name )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindexbynumber -- Set index by number

Description

int dbplus_setindexbynumber ( resource relation, int idx_number )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_number

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_sql

(4.1.0 - 4.2.3 only, PECL)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query [, string server [, string dbpath]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

query

server

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_tcl

(4.1.0 - 4.2.3 only, PECL)

dbplus_tcl -- Execute TCL code on server side

Description

string dbplus_tcl ( int sid, string script )

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

Parameters

sid

script

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_tremove

(4.1.0 - 4.2.3 only, PECL)

dbplus_tremove -- Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource relation, array tuple [, array &current] )

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

Parameters

relation

A relation opened by dbplus_open().

tuple

current

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_undo

(4.1.0 - 4.2.3 only, PECL)

dbplus_undo -- Undo

Description

int dbplus_undo ( resource relation )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_undoprepare

(4.1.0 - 4.2.3 only, PECL)

dbplus_undoprepare -- Prepare undo

Description

int dbplus_undoprepare ( resource relation )

Warning

This function is currently not documented; only the argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_unlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation )

Release a write lock previously obtained by dbplus_lockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_unselect

(4.1.0 - 4.2.3 only, PECL)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation )

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_update

(4.1.0 - 4.2.3 only, PECL)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new )

dbplus_update() replaces the old tuple with the data from the new one, only if the old completely matches a tuple within relation.

Parameters

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_xlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation )

Request an exclusive lock on relation preventing even read access from other clients.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

dbplus_xunlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation )

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk.

XXIV. Database (dbm-style) Abstraction Layer Functions

Introduction

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)


Requirements

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.

Table 1. List of DBA handlers

HandlerNotes
dbm Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm Gdbm is the GNU database manager.
db2 DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 DB3 is Sleepycat Software's DB3.
db4 DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2.
cdb Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE.
qdbm This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().


Installation

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

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.

Table 2. Supported DBA handlers

HandlerConfigure 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 db2 add --with-db2[=DIR].

Note: db2 conflicts with db3 and db4.

db3 To enable support for db3 add --with-db3[=DIR].

Note: db3 conflicts with db2 and db4.

db4 To enable support for db4 add --with-db4[=DIR].

Note: db4 conflicts with db2 and db3.

Note: This was added in PHP 4.3.2. In earlier versions of PHP you need to use --with-db3=DIR with DIR being the path to db4 library. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0. Also, the db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

cdb To enable support for cdb add --with-cdb[=DIR].

Note: Since PHP 4.3.0 you can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile To enable support for flatfile add --with-flatfile.

Note: This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile To enable support for inifile add --with-inifile.

Note: This was added in PHP 5.0.0 and allows to read and set microsoft style .ini files (like the php.ini file).

qdbm To enable support for qdbm add --with-qdbm[=DIR].

Note: qdbm conflicts with dbm and gdbm.

Note: This was added in PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

Note: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

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.


Predefined Constants

This extension has no constants defined.


Examples

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);
}

?>

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

dba_close

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_close -- Close a DBA database

Description

void dba_close ( resource handle )

dba_close() closes the established database and frees all resources of the specified database handle.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

No value is returned.

dba_delete

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_delete -- Delete DBA entry specified by key

Description

bool dba_delete ( string key, resource handle )

dba_delete() deletes the specified entry from the database.

Parameters

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

dba_exists

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, resource handle )

dba_exists() checks whether the specified key exists in the database.

Parameters

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE if the key exists, FALSE otherwise.

dba_fetch

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_fetch -- Fetch data specified by key

Description

string dba_fetch ( string key, resource handle )

string dba_fetch ( string key, int skip, resource handle )

dba_fetch() fetches the data specified by key from the database specified with handle.

Parameters

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().

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the associated string if the key/data pair is found, FALSE otherwise.

ChangeLog

VersionDescription
4.3 The skip parameter is available to support cdb's capability of multiple keys having the same name.

dba_firstkey

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( resource handle )

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success, or FALSE on failure.

See Also

dba_nextkey()
dba_key_split()
Example 2 in the DBA examples

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers -- List all the handlers available

Description

array dba_handlers ( [bool full_info] )

dba_handlers() list all the handlers supported by this extension.

Parameters

full_info

Turns on/off full information display in the result. The default is FALSE.

Return Values

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.

Examples

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";
}

?>

The above example will output something similar to:

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3 
 - cdb_make: 0.75, Revision: 1.2.2.4 
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3 
 - flatfile: 1.0, Revision: 1.5.2.4

dba_insert

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, resource handle )

dba_insert() inserts the entry described with key and value into the database.

Parameters

key

The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.

value

The value to be inserted.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

dba_key_split

(PHP 5)

dba_key_split --  Splits a key in string representation into array representation

Description

mixed dba_key_split ( mixed key )

dba_key_split() splits a key (string representation) into an array representation.

Parameters

key

The key in string representation.

Return Values

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list -- List all open database files

Description

array dba_list ( void )

dba_list() list all open database files.

Return Values

An associative array, in the form resourceid => filename.

dba_nextkey

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( resource handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success, or FALSE on failure.

dba_open

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_open -- Open database

Description

resource dba_open ( string path, string mode [, string handler [, mixed ...]] )

dba_open() establishes a database instance for path with mode using handler.

Parameters

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

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:

Table 1. DBA locking

already openmode = "rl"mode = "rlt"mode = "wl"mode = "wlt"mode = "rd"mode = "rdt"mode = "wd"mode = "wdt"
not openokokokokokokokok
mode = "rl"okokwaitfalseillegalillegalillegalillegal
mode = "wl"waitfalsewaitfalseillegalillegalillegalillegal
mode = "rd"illegalillegalillegalillegalokokwaitfalse
mode = "wd"illegalillegalillegalillegalwaitfalsewaitfalse

ok: the second call will be successfull.
wait: the second call waits until dba_close() is called for the first.
false: the second call returns false.
illegal: you must not mix "l" and "d" modifiers for mode parameter.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

Return Values

Returns a positive handle on success, or FALSE on failure.

ChangeLog

VersionDescription
4.3.0 It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.
4.3.0 Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.
before 4.3.5 open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

dba_optimize

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_optimize -- Optimize database

Description

bool dba_optimize ( resource handle )

dba_optimize() optimizes the underlying database.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dba_sync()

dba_popen

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_popen -- Open database persistently

Description

resource dba_popen ( string path, string mode [, string handler [, mixed ...]] )

dba_popen() establishes a persistent database instance for path with mode using handler.

Parameters

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.

Return Values

Returns a positive handle on success, or FALSE on failure.

dba_replace

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_replace -- Replace or insert entry

Description

bool dba_replace ( string key, string value, resource handle )

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

Parameters

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

dba_sync

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_sync -- Synchronize database

Description

bool dba_sync ( resource handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dba_optimize()

XXV. dBase Functions

Introduction

These functions allow you to access records stored in dBase-format (dbf) databases.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

The types of dBase fields available are:

Table 1. Available types of fields

FielddBase TypeFormatAdditional information
MMemon/aThis type is not supported by PHP, such field will be ignored
DDateYYYYMMDDThe field length is limited to 8
NNumberA number You must declare a length and a precision (the number of digits after the decimal point)
CStringA stringYou must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length.
LBooleanT or Y for TRUE, F or N for FALSEStored and returned as an integer (1 or 0)
FFloatA float numberSupport for this type of field was added in PHP 5.2.0

Warning

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent web server processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.


Installation

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Examples

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().


Predefined Constants

This extension has no constants defined.

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

dbase_add_record

(PHP 3, PHP 4, PHP 5)

dbase_add_record -- Adds a record to a database

Description

bool dbase_add_record ( int dbase_identifier, array record )

Adds the given data to the database.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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_close

(PHP 3, PHP 4, PHP 5)

dbase_close -- Closes a database

Description

bool dbase_close ( int dbase_identifier )

Closes the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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_create

(PHP 3, PHP 4, PHP 5)

dbase_create -- Creates a database

Description

int dbase_create ( string filename, array fields )

dbase_create() creates a dBase database with the given definition.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

Note: This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.

Note: The fieldnames are limited in length and must not exceed 10 chars.

Return Values

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

Examples

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_delete_record

(PHP 3, PHP 4, PHP 5)

dbase_delete_record -- Deletes a record from a database

Description

bool dbase_delete_record ( int dbase_identifier, int record_number )

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().

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Return Values

Returns TRUE on success or FALSE on failure.

dbase_get_header_info

(PHP 5)

dbase_get_header_info -- Gets the header info of a database

Description

array dbase_get_header_info ( int dbase_identifier )

Returns information on the column structure of the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name

The name of the column

type

The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)

length

The number of bytes this column can hold

precision

The number of digits of decimal precision for the column

format

A suggested printf() format specifier for the column

offset

The byte offset of the column from the start of the row

If the database header information cannot be read, FALSE is returned.

Examples

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);
?>

dbase_get_record_with_names

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

dbase_get_record_with_names --  Gets a record from a database as an associative array

Description

array dbase_get_record_with_names ( int dbase_identifier, int record_number )

Gets a record from a dBase database as an associative array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Return Values

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.

  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record_with_names() will return FALSE.

Examples

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

(PHP 3, PHP 4, PHP 5)

dbase_get_record --  Gets a record from a database as an indexed array

Description

array dbase_get_record ( int dbase_identifier, int record_number )

Gets a record from a database as an indexed array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Return Values

An indexed array with the record. This array will also include an associative key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.

  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record() will return FALSE.

dbase_numfields

(PHP 3, PHP 4, PHP 5)

dbase_numfields -- Gets the number of fields of a database

Description

int dbase_numfields ( int dbase_identifier )

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).

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of fields in the database, or FALSE if an error occurs.

Examples

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

(PHP 3, PHP 4, PHP 5)

dbase_numrecords -- Gets the number of records in a database

Description

int dbase_numrecords ( int dbase_identifier )

Gets the number of records (rows) in the specified database.

Note: Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of records in the database, or FALSE if an error occurs.

Examples

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++) {
      // do something here, for each record
  }
}

?>

See Also

dbase_num_fields()

dbase_open

(PHP 3, PHP 4, PHP 5)

dbase_open -- Opens a database

Description

int dbase_open ( string filename, int mode )

dbase_open() opens a dBase database with the given access mode.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

Note: This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

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.

Examples

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);
}

?>

Return Values

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

dbase_pack

(PHP 3, PHP 4, PHP 5)

dbase_pack -- Packs a database

Description

bool dbase_pack ( int dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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_replace_record

(PHP 3 >= 3.0.11, PHP 4, PHP 5)

dbase_replace_record -- Replaces a record in a database

Description

bool dbase_replace_record ( int dbase_identifier, array record, int record_number )

Replaces the given record in the database with the given data.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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');
  
  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

XXVI. DBM Functions [deprecated]

Introduction

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

Note: DBM support is deprecated and you are encouraged to use the Database (dbm-style) abstraction layer functions instead.

Note: This extension has been removed from PHP and is no longer available as of PHP 5.0.0.


Requirements

To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.


Installation

In order to use these functions, you must compile PHP with dbm support by using the --with-db option. In addition you must ensure support for an underlying database or you can use some system libraries.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

The function dbmopen() returns an database identifier which is used by the other dbm-functions.


Predefined Constants

This extension has no constants defined.


Examples

Example 1. DBM example

<?php

$dbm = dbmopen("lastseen", "w");
if (dbmexists($dbm, $userid)) {
    $last_seen = dbmfetch($dbm, $userid);
} else {
    dbminsert($dbm, $userid, time());
}
do_stuff();
dbmreplace($dbm, $userid, time());
dbmclose($dbm);

?>

Table of Contents
dblist -- Describes the DBM-compatible library being used
dbmclose -- Closes a dbm database
dbmdelete -- Deletes the value for a key from a DBM database
dbmexists -- Tells if a value exists for a key in a DBM database
dbmfetch -- Fetches a value for a key from a DBM database
dbmfirstkey -- Retrieves the first key from a DBM database
dbminsert -- Inserts a value for a key in a DBM database
dbmnextkey -- 
dbmopen -- Opens a DBM database
dbmreplace -- Replaces the value for a key in a DBM database

dblist

(PHP 3, PHP 4, PECL)

dblist -- Describes the DBM-compatible library being used

Description

string dblist ( void )

Describes the GDBM version.

Return Values

Returns a string describing the GDBM version.

Examples

Example 1. Getting the information on the command line

[marcus@zaphod marcus]$ php -r 'echo dblist();'
This is GDBM version 1.8.0, as of May 19, 1999.

dbmclose

(PHP 3, PHP 4, PECL)

dbmclose -- Closes a dbm database

Description

bool dbmclose ( resource dbm_identifier )

Unlocks and closes the specified database.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dbmopen()

dbmdelete

(PHP 3, PHP 4, PECL)

dbmdelete -- Deletes the value for a key from a DBM database

Description

bool dbmdelete ( resource dbm_identifier, string key )

Deletes the value for key in the database.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The key, as a string

Return Values

Returns TRUE on success or FALSE on failure. Returns FALSE if the key didn't exist in the database.

See Also

dbminsert()

dbmexists

(PHP 3, PHP 4, PECL)

dbmexists -- Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( resource dbm_identifier, string key )

Returns TRUE if there is a value associated with the key.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The key, as a string

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dbmfetch()

dbmfetch

(PHP 3, PHP 4, PECL)

dbmfetch -- Fetches a value for a key from a DBM database

Description

string dbmfetch ( resource dbm_identifier, string key )

Gets the value associated with the given key.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The key, as a string

Return Values

Returns the value associated with key.

dbmfirstkey

(PHP 3, PHP 4, PECL)

dbmfirstkey -- Retrieves the first key from a DBM database

Description

string dbmfirstkey ( resource dbm_identifier )

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dbmnextkey()

dbminsert

(PHP 3, PHP 4, PECL)

dbminsert -- Inserts a value for a key in a DBM database

Description

int dbminsert ( resource dbm_identifier, string key, string value )

Adds the value to the database with the specified key.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The added key

value

The added key value

Return Values

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmnextkey

(PHP 3, PHP 4, PECL)

dbmnextkey -- 

Description

string dbmnextkey ( resource dbm_identifier, string key )

Returns the next key after key.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The previous key

Return Values

The next key if possible

Examples

By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Example 1. Visiting every key/value pair in a DBM database

<?php

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}

?>

See Also

dbmfirstkey()

dbmopen

(PHP 3, PHP 4, PECL)

dbmopen -- Opens a DBM database

Description

resource dbmopen ( string filename, string flags )

Opens the specified DBM database in the given mode.

Parameters

filename

The full-path filename of the DBM file to be opened

flags

The file open mode which is one of r, n, c or w, for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Return Values

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

Notes

Note: If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file.

Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

See Also

dbmclose()

dbmreplace

(PHP 3, PHP 4, PECL)

dbmreplace -- Replaces the value for a key in a DBM database

Description

int dbmreplace ( resource dbm_identifier, string key, string value )

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

Parameters

dbm_identifier

The DBM link identifier, returned by dbmopen().

key

The replaced key

value

The new value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

dbminsert()

XXVII. dbx Functions

Introduction

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.


Requirements

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.


Installation

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. DBX Configuration Options

NameDefaultChangeableChangelog
dbx.colnames_case"unchanged"PHP_INI_SYSTEMAvailable since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().


Resource Types

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DBX_MYSQL (integer)

DBX_ODBC (integer)

DBX_PGSQL (integer)

DBX_MSSQL (integer)

DBX_FBSQL (integer)

DBX_OCI8 (integer) (available from PHP 4.3.0)

DBX_SYBASECT (integer)

DBX_SQLITE (integer) (PHP 5)

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_RESULT_UNBUFFERED (integer) (PHP 5)

DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)

DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)

DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)

DBX_CMP_NATIVE (integer)

DBX_CMP_TEXT (integer)

DBX_CMP_NUMBER (integer)

DBX_CMP_ASC (integer)

DBX_CMP_DESC (integer)

Table of Contents
dbx_close -- Close an open connection/database
dbx_compare -- Compare two rows for sorting purposes
dbx_connect -- Open a connection/database
dbx_error --  Report the error message of the latest function call in the module
dbx_escape_string --  Escape a string so it can safely be used in an sql-statement
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
dbx_query -- Send a query and fetch all results (if any)
dbx_sort --  Sort a result from a dbx_query by a custom sort function

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_close -- Close an open connection/database

Description

int dbx_close ( object link_identifier )

Parameters

link_identifier

The DBX link object to close.

Return Values

Returns 1 on success and 0 on errors.

Examples

Example 1. dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

See Also

dbx_connect()

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string column_key [, int flags] )

dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

Parameters

row_a

First row

row_b

Second row

column_key

The compared column

flags

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order

  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion

  • DBX_CMP_TEXT - compare items as strings

  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|). The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

Return Values

Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC.

Examples

Example 1. dbx_compare() example

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See Also

dbx_sort()

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_connect -- Open a connection/database

Description

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent] )

Opens a connection to a database.

Parameters

module

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"

  • DBX_ODBC or "odbc"

  • DBX_PGSQL or "pgsql"

  • DBX_MSSQL or "mssql"

  • DBX_FBSQL or "fbsql" (available from PHP 4.1.0)

  • DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)

  • DBX_OCI8 or "oci8" (available from PHP 4.3.0)

  • DBX_SQLITE or "sqlite" (PHP 5)

host

The SQL server host

database

The database name

username

The username

password

The password

persistent

The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

Return Values

Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.

The returned object has three properties:

database

It is the name of the currently selected database.

handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module

It is used internally by dbx only, and is actually the module number mentioned above.

Examples

Example 1. dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

See Also

dbx_close()

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_error --  Report the error message of the latest function call in the module

Description

string dbx_error ( object link_identifier )

dbx_error() returns the last error message.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

Return Values

Returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Examples

Example 1. dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented yet.

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dbx_escape_string --  Escape a string so it can safely be used in an sql-statement

Description

string dbx_escape_string ( object link_identifier, string text )

Escape the given string so that it can safely be used in an sql-statement.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Return Values

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Examples

Example 1. dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See Also

dbx_query()

dbx_fetch_row

(PHP 5 <= 5.0.4)

dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

mixed dbx_fetch_row ( object result_identifier )

dbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.

When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

Parameters

result_identifier

A result set returned by dbx_query().

Return Values

Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.

Upon failure, returns 0 (e.g. when no more rows are available).

Examples

Example 1. How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

See Also

dbx_query()

dbx_query

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_query -- Send a query and fetch all results (if any)

Description

mixed dbx_query ( object link_identifier, string sql_statement [, int flags] )

Sends a query and fetch all results.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

sql_statement

SQL statement.

flags

The compared column

flags

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX

It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.

If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.

DBX_RESULT_INFO

It provides info about columns, such as field names and field types.

DBX_RESULT_ASSOC

It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.

Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.

DBX_RESULT_UNBUFFERED (PHP 5)

This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.

The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.

DBX_COLNAMES_UNCHANGED (available from PHP 4.3.0)

The case of the returned column names will not be changed.

DBX_COLNAMES_UPPERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to uppercase.

DBX_COLNAMES_LOWERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to lowercase.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:

  • DBX_RESULT_INDEX

  • DBX_RESULT_INDEX | DBX_RESULT_INFO

  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

Return Values

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

The returned object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields 
?>

info (optional)

It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Example 1. lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";  
}
?>
data

This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Example 2. outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Example 3. How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Examples

Example 4. How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types 
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_sort --  Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object result, string user_compare_function )

Sort a result from a dbx_query() call with a custom sort function.

Parameters

result

A result set returned by dbx_query().

user_compare_function

The user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. dbx_sort() example

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Notes

Note: It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

See Also

dbx_compare()

XXVIII. Direct IO Functions

Introduction

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

This extension is only available on Windows Platforms as of PHP 5.0.0


Requirements

No external libraries are needed to build this extension.


Installation

To get these functions to work, you have to configure PHP with --enable-dio.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

c (integer)

F_DUPFD (integer)

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

One resource type is defined by this extension: a file descriptor returned by dio_open().

Table of Contents
dio_close -- Closes the file descriptor given by fd
dio_fcntl -- Performs a c library fcntl on fd
dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read -- Reads bytes from a file descriptor
dio_seek -- Seeks to pos on fd from whence
dio_stat --  Gets stat information about the file descriptor fd
dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port
dio_truncate --  Truncates file descriptor fd to offset bytes
dio_write --  Writes data to fd with optional truncation at length

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_close -- Closes the file descriptor given by fd

Description

void dio_close ( resource fd )

The function dio_close() closes the file descriptor fd.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

No value is returned.

Examples

Example 1. Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

See Also

dio_open()

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_fcntl -- Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource fd, int cmd [, mixed args] )

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

Note: This function is not implemented on Windows platforms.

Parameters

fd

The file descriptor returned by dio_open().

cmd

Can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater than or equal to args and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by args, which can be O_APPEND, O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

args

args is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Return Values

Returns the result of the C call.

Examples

Example 1. Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}

dio_close($fd);
?>

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode

Description

resource dio_open ( string filename, int flags [, int mode] )

dio_open() opens a file and returns a new file descriptor for it.

Parameters

filename

The opened file.

flags

The flags parameter can also include any combination of the following flags:

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if the file already exists.

  • O_TRUNC - if the file exists, and its opened for write access, the file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of the file.

  • O_NONBLOCK - sets non blocking mode.

mode

If flags is O_CREAT, mode will set the mode of the file (creation permissions).

  • O_RDONLY - opens the file for read access.

  • O_WRONLY - opens the file for write access.

  • O_RDWR - opens the file for both reading and writing.

Return Values

A file descriptor or FALSE on error.

Examples

Example 1. Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

See Also

dio_close()

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_read -- Reads bytes from a file descriptor

Description

string dio_read ( resource fd [, int len] )

The function dio_read() reads and returns len bytes from file with descriptor fd.

Parameters

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

Return Values

The bytes read from fd.

See Also

dio_write()

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_seek -- Seeks to pos on fd from whence

Description

int dio_seek ( resource fd, int pos [, int whence] )

The function dio_seek() is used to change the file position of the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

Return Values

Examples

Example 1. Positioning in a file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file. 
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_stat --  Gets stat information about the file descriptor fd

Description

array dio_stat ( resource fd )

dio_stat() returns information about the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

Returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port

Description

bool dio_tcsetattr ( resource fd, array options )

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

Note: This function is not implemented on Windows platforms.

Parameters

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

Return Values

No value is returned.

Examples

Example 1. Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
)); 

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
} 

?>

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_truncate --  Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource fd, int offset )

dio_truncate() truncates a file to at most offset bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

Note: This function is not implemented on Windows platforms.

Parameters

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Return Values

Returns TRUE on success or FALSE on failure.

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_write --  Writes data to fd with optional truncation at length

Description

int dio_write ( resource fd, string data [, int len] )

dio_write() writes up to len bytes from data to file fd.

Parameters

fd

The file descriptor returned by dio_open().

data

The written data.

len

The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

Return Values

Returns the number of bytes written to fd.

See Also

dio_read()

XXIX. Directory Functions


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DIRECTORY_SEPARATOR (string)

PATH_SEPARATOR (string)

Note: The PATH_SEPARATOR was introduced with PHP 4.3.0-RC2.


See Also

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.

Table of Contents
chdir -- Change directory
chroot -- Change the root directory
dir -- Directory class
closedir -- Close directory handle
getcwd -- Gets the current working directory
opendir -- Open directory handle
readdir -- Read entry from directory handle
rewinddir -- Rewind directory handle
scandir -- List files and directories inside the specified path

chdir

(PHP 3, PHP 4, PHP 5)

chdir -- Change directory

Description

bool chdir ( string directory )

Changes PHP's current directory to directory.

Parameters

directory

The new current directory

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/vincent
/home/vincent/public_html

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

See Also

getcwd()

chroot

(PHP 4 >= 4.0.5, PHP 5)

chroot -- Change the root directory

Description

bool chroot ( string directory )

Changes the root directory of the current process to directory.

This function is only available if your system supports it and you're using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parameters

directory

The new directory

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.

dir

(PHP 3, PHP 4, PHP 5)

dir -- Directory class

Description

class dir {

dir ( string directory )

string path

resource handle

string read ( void )

void rewind ( void )

void close ( void )

}

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once the directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Examples

Example 1. dir() example

Please note the fashion in which dir()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

<?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();
?>

The above example will output something similar to:

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

Notes

Note: The order in which directory entries are returned by the read method is system-dependent.

Note: This defines the internal class Directory, meaning that you will not be able to define your own classes with that name. For a full list of predefined classes in PHP, please see Predefined Classes.

closedir

(PHP 3, PHP 4, PHP 5)

closedir -- Close directory handle

Description

void closedir ( resource dir_handle )

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

Parameters

dir_handle

The directory handle resource previously opened with opendir().

Examples

Example 1. closedir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

getcwd

(PHP 4, PHP 5)

getcwd -- Gets the current working directory

Description

string getcwd ( void )

Gets the current working directory.

Return Values

Returns the current working directory on success, or FALSE on failure.

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. See chmod() for more information on modes and permissions.

Examples

Example 1. getcwd() example

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/didou
/home/didou/cvs

See Also

chdir()
chmod()

opendir

(PHP 3, PHP 4, PHP 5)

opendir -- Open directory handle

Description

resource opendir ( string path [, resource context] )

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parameters

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns a directory handle resource on success, or FALSE on failure.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error of level E_WARNING. You can suppress the error output of opendir() by prepending '@' to the front of the function name.

ChangeLog

VersionDescription
5.0.0 path supports the ftp:// URL wrapper.
4.3.0 path can also be any URL which supports directory listing, however only the file:// URL wrapper supports this in PHP 4

Examples

Example 1. opendir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

The above example will output something similar to:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

readdir

(PHP 3, PHP 4, PHP 5)

readdir -- Read entry from directory handle

Description

string readdir ( resource dir_handle )

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Parameters

dir_handle

The directory handle resource previously opened with opendir().

Return Values

Returns the filename on success, or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example 1. List all files in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php
// Note that !== did not exist until 4.0.0-RC2

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Example 2. List all files in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

See Also

is_dir()
glob()

rewinddir

(PHP 3, PHP 4, PHP 5)

rewinddir -- Rewind directory handle

Description

void rewinddir ( resource dir_handle )

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Parameters

dir_handle

The directory handle resource previously opened with opendir().

scandir

(PHP 5)

scandir -- List files and directories inside the specified path

Description

array scandir ( string directory [, int sorting_order [, resource context]] )

Returns an array of files and directories from the directory.

Parameters

directory

The directory that will be scanned.

sorting_order

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then the sort order is alphabetical in descending order.

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

Examples

Example 1. A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Example 2. PHP 4 alternatives to scandir()

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Notes

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix O for a list of supported URL protocols.

XXX. DOM Functions

Introduction

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.

For PHP 4, use DOM XML.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Predefined Classes

The API of the module follows the DOM Level 3 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module.

This module defines a number of classes, which are explained in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.


DOMAttr

Extends DOMNode. The DOMAttr interface represents an attribute in an DOMElement object.


Constructor


Methods


Properties

Table 1.

NameTypeRead-onlyDescription
namestringyesThe name of the attribute
ownerElementDOMElementyesThe element which contains the attribute
schemaTypeInfoboolyesNot implemented yet, always return NULL
specifiedboolyesNot implemented yet, always return NULL
valuestringnoThe value of the attribute

DOMCharacterData

Extends DOMNode.


Methods


Properties

Table 2.

NameTypeRead-onlyDescription
datastringnoThe contents of the node
lengthintyesThe length of the contents

DOMComment

Extends DOMCharacterData.


Constructor


DOMDocument

Extends DOMNode.


Constructor


Methods


Properties

Table 3.

NameTypeRead-onlyDescription
actualEncodingstringyes 
configDOMConfigurationyes 
doctypeDOMDocumentTypeyes The Document Type Declaration associated with this document.
documentElementDOMElementyes This is a convenience attribute that allows direct access to the child node that is the document element of the document.
documentURIstringno The location of the document or NULL if undefined.
encodingstringno 
formatOutputboolno 
implementationDOMImplementationyes The DOMImplementation object that handles this document.
preserveWhiteSpaceboolnoDo not remove redundant white space. Default to TRUE.
recoverboolno 
resolveExternalsboolno Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.
standaloneboolno 
strictErrorCheckingboolnoThrows DOMException on errors. Default to TRUE.
substituteEntitiesboolno 
validateOnParseboolnoLoads and validates against the DTD. Default to FALSE.
versionstringno 
xmlEncodingstringyes An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.
xmlStandaloneboolno An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.
xmlVersionstringno An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

DOMDocumentFragment

Extends DOMNode.


Methods


DOMDocumentType

Extends DOMNode

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.


Properties

Table 4.

NameTypeRead-onlyDescription
publicIdstringyesThe public identifier of the external subset.
systemIdstringyesThe system identifier of the external subset. This may be an absolute URI or not.
namestringyesThe name of DTD; i.e., the name immediately following the DOCTYPE keyword.
entitiesDOMNamedNodeMapyes A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.
notationsDOMNamedNodeMapyes A DOMNamedNodeMap containing the notations declared in the DTD.
internalSubsetstringyes The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.

DOMElement

Extends DOMNode.


Constructor


Methods


Properties

Table 5.

NameTypeRead-onlyDescription
schemaTypeInfoboolyesNot implemented yet, always return NULL
tagNamestringyesThe element name

DOMEntity

Extends DOMNode

This interface represents a known entity, either parsed or unparsed, in an XML document.


Properties

Table 6.

NameTypeRead-onlyDescription
publicIdstringyes The public identifier associated with the entity if specified, and NULL otherwise.
systemIdstringyes The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.
notationNamestringyes For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.
actualEncodingstringno An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.
encodingstringyes An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.
versionstringyes An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.

DOMEntityReference

Extends DOMNode.


Constructor


DOMException

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Chapter 20.


Properties

Table 7.

NameTypeRead-onlyDescription
codeintyesAn integer indicating the type of error generated

DOMImplementation

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.


Constructor


Methods


DOMNamedNodeMap

Methods


DOMNode

Methods


Properties

Table 8.

NameTypeRead-onlyDescription
nodeNamestringyesReturns the most accurate name for the current node type
nodeValuestringnoThe value of this node, depending on its type.
nodeTypeintyesGets the type of the node. One of the predefined XML_xxx_NODE constants
parentNodeDOMNodeyesThe parent of this node.
childNodesDOMNodeListyes A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.
firstChildDOMNodeyes The first child of this node. If there is no such node, this returns NULL.
lastChildDOMNodeyes The last child of this node. If there is no such node, this returns NULL.
previousSiblingDOMNodeyes The node immediately preceding this node. If there is no such node, this returns NULL.
nextSiblingDOMNodeyes The node immediately following this node. If there is no such node, this returns NULL.
attributesDOMNamedNodeMapyes A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.
ownerDocumentDOMDocumentyes The DOMDocument object associated with this node.
namespaceURIstringyes The namespace URI of this node, or NULL if it is unspecified.
prefixstringno The namespace prefix of this node, or NULL if it is unspecified.
localNamestringyes Returns the local part of the qualified name of this node.
baseURIstringyes The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.
textContentstringno This attribute returns the text content of this node and its descendants.

DOMNodeList


Methods


Properties

Table 9.

NameTypeRead-onlyDescription
lengthintyes The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

DOMNotation

Extends DOMNode


Properties

Table 10.

NameTypeRead-onlyDescription
publicIdstringyes 
systemIdstringyes 

DOMProcessingInstruction

Extends DOMNode.


Constructor


Properties

Table 11.

NameTypeRead-onlyDescription
targetstringyes 
datastringno 

DOMText

Extends DOMCharacterData.


Constructor


Methods


Properties

Table 12.

NameTypeRead-onlyDescription
wholeTextstringyes 

DOMXPath


Constructor


Methods


Properties

Table 13.

NameTypeRead-onlyDescription
documentDOMDocument  

Examples

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="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 14. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) 2Node is a DOMAttr
XML_TEXT_NODE (integer) 3Node is a DOMText
XML_CDATA_SECTION_NODE (integer) 4Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) 5Node is a DOMEntityReference
XML_ENTITY_NODE (integer) 6Node is a DOMEntity
XML_PI_NODE (integer) 7Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) 8Node is a DOMComment
XML_DOCUMENT_NODE (integer) 9Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) 10Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) 11Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) 12Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) 13 
XML_DTD_NODE (integer) 14 
XML_ELEMENT_DECL_NODE (integer) 15 
XML_ATTRIBUTE_DECL_NODE (integer) 16 
XML_ENTITY_DECL_NODE (integer) 17 
XML_NAMESPACE_DECL_NODE (integer) 18 
XML_ATTRIBUTE_CDATA (integer) 1 
XML_ATTRIBUTE_ID (integer) 2 
XML_ATTRIBUTE_IDREF (integer) 3 
XML_ATTRIBUTE_IDREFS (integer) 4 
XML_ATTRIBUTE_ENTITY (integer) 5 
XML_ATTRIBUTE_NMTOKEN (integer) 7 
XML_ATTRIBUTE_NMTOKENS (integer) 8 
XML_ATTRIBUTE_ENUMERATION (integer) 9 
XML_ATTRIBUTE_NOTATION (integer) 10 

Table 15. DOMException constants

ConstantValueDescription
DOM_INDEX_SIZE_ERR (integer) 1 If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) 2 If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) 3If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) 4 If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) 5 If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) 6 If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) 7 If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) 8 If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) 9 If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) 10 If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) 11 If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) 12If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) 13If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) 14 If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) 15 If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) 16 If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
Table of Contents
DOMAttr->__construct() --  Creates a new DOMAttr object
DOMAttr->isId() --  Checks if attribute is a defined ID
DOMCharacterData->appendData() --  Append the string to the end of the character data of the node
DOMCharacterData->deleteData() --  Remove a range of characters from the node
DOMCharacterData->insertData() --  Insert a string at the specified 16-bit unit offset
DOMCharacterData->replaceData() --  Replace a substring within the DOMCharacterData node
DOMCharacterData->substringData() --  Extracts a range of data from the node
DOMComment->__construct() --  Creates a new DOMComment object
DOMDocument->__construct() --  Creates a new DOMDocument object
DOMDocument->createAttribute() -- Create new attribute
DOMDocument->createAttributeNS() --  Create new attribute node with an associated namespace
DOMDocument->createCDATASection() -- Create new cdata node
DOMDocument->createComment() -- Create new comment node
DOMDocument->createDocumentFragment() -- Create new document fragment
DOMDocument->createElement() -- Create new element node
DOMDocument->createElementNS() --  Create new element node with an associated namespace
DOMDocument->createEntityReference() -- Create new entity reference node
DOMDocument->createProcessingInstruction() -- Creates new PI node
DOMDocument->createTextNode() -- Create new text node
DOMDocument->getElementById() -- Searches for an element with a certain id
DOMDocument->getElementsByTagName() -- Searches for all elements with given tag name
DOMDocument->getElementsByTagNameNS() --  Searches for all elements with given tag name in specified namespace
DOMDocument->importNode() -- Import node into current document
DOMDocument->load() --  Load XML from a file
DOMDocument->loadHTML() --  Load HTML from a string
DOMDocument->loadHTMLFile() --  Load HTML from a file
DOMDocument->loadXML() --  Load XML from a string
DOMDocument->normalizeDocument() -- Normalizes the document
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->save() --  Dumps the internal XML tree back into a file
DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting
DOMDocument->saveXML() --  Dumps the internal XML tree back into a string
DOMDocument->schemaValidate() --  Validates a document based on a schema
DOMDocument->schemaValidateSource() --  Validates a document based on a schema
DOMDocument->validate() --  Validates the document based on its DTD
DOMDocument->xinclude() --  Substitutes XIncludes in a DOMDocument Object
DOMDocumentFragment->appendXML() -- Append raw XML data
DOMElement->__construct() --  Creates a new DOMElement object
DOMElement->getAttribute() -- Returns value of attribute
DOMElement->getAttributeNode() -- Returns attribute node
DOMElement->getAttributeNodeNS() --  Returns attribute node
DOMElement->getAttributeNS() -- Returns value of attribute
DOMElement->getElementsByTagName() -- Gets elements by tagname
DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName
DOMElement->hasAttribute() -- Checks to see if attribute exists
DOMElement->hasAttributeNS() --  Checks to see if attribute exists
DOMElement->removeAttribute() -- Removes attribute
DOMElement->removeAttributeNode() -- Removes attribute
DOMElement->removeAttributeNS() -- Removes attribute
DOMElement->setAttribute() -- Adds new attribute
DOMElement->setAttributeNode() -- Adds new attribute node to element
DOMElement->setAttributeNodeNS() -- Adds new attribute node to element
DOMElement->setAttributeNS() -- Adds new attribute
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
DOMEntityReference->__construct() --  Creates a new DOMEntityReference object
DOMImplementation->__construct() --  Creates a new DOMImplementation object
DOMImplementation->createDocument() --  Creates a DOMDocument object of the specified type with its document element
DOMImplementation->createDocumentType() --  Creates an empty DOMDocumentType object
DOMImplementation->hasFeature() --  Test if the DOM implementation implements a specific feature
DOMNamedNodeMap->getNamedItem() --  Retrieves a node specified by name
DOMNamedNodeMap->getNamedItemNS() --  Retrieves a node specified by local name and namespace URI
DOMNamedNodeMap->item() -- Retrieves a node specified by index
DOMNode->appendChild() --  Adds new child at the end of the children
DOMNode->cloneNode() --  Clones a node
DOMNode->hasAttributes() --  Checks if node has attributes
DOMNode->hasChildNodes() --  Checks if node has children
DOMNode->insertBefore() --  Adds a new child before a reference node
DOMNode->isDefaultNamespace() -- Checks if the specified namespaceURI is the default namespace or not
DOMNode->isSameNode() --  Indicates if two nodes are the same node
DOMNode->isSupported() --  Checks if feature is supported for specified version
DOMNode->lookupNamespaceURI() --  Gets the namespace URI of the node based on the prefix
DOMNode->lookupPrefix() --  Gets the namespace prefix of the node based on the namespace URI
DOMNode->normalize() --  Normalizes the node
DOMNode->removeChild() --  Removes child from list of children
DOMNode->replaceChild() --  Replaces a child
DOMNodelist->item() --  Retrieves a node specified by index
DOMProcessingInstruction->__construct() --  Creates a new DOMProcessingInstruction object
DOMText->__construct() --  Creates a new DOMText object
DOMText->isWhitespaceInElementContent() --  Indicates whether this text node contains whitespace
DOMText->splitText() --  Breaks this node into two nodes at the specified offset
DOMXPath->__construct() --  Creates a new DOMXPath object
DOMXPath->evaluate() --  Evaluates the given XPath expression and returns a typed result if possible.
DOMXPath->query() --  Evaluates the given XPath expression
DOMXPath->registerNamespace() --  Registers the namespace with the DOMXPath object
dom_import_simplexml --  Gets a DOMElement object from a SimpleXMLElement object

DOMAttr->__construct()

(no version information, might be only in CVS)

DOMAttr->__construct() --  Creates a new DOMAttr object

Description

class DOMAttr {

__construct ( string name [, string value] )

}

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createAttribute().

Parameters

name

The tag name of the attribute.

value

The value of the attribute.

Examples

Example 1. Creating a new DOMAttr

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root attr="attrvalue" /> */

?>

DOMAttr->isId()

(no version information, might be only in CVS)

DOMAttr->isId() --  Checks if attribute is a defined ID

Description

class DOMAttr {

bool isId ( void )

}

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument->validate() or DOMDocument::validateOnParse before using this function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. DOMAttr->isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

DOMCharacterData->appendData()

(no version information, might be only in CVS)

DOMCharacterData->appendData() --  Append the string to the end of the character data of the node

Description

class DOMCharacterData {

void appendData ( string data )

}

Append the string data to the end of the character data of the node.

Parameters

data

The string to append.

Return Values

No value is returned.

DOMCharacterData->deleteData()

(no version information, might be only in CVS)

DOMCharacterData->deleteData() --  Remove a range of characters from the node

Description

class DOMCharacterData {

void deleteData ( int offset, int count )

}

Deletes count characters starting from position offset.

Parameters

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.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMCharacterData->insertData()

(no version information, might be only in CVS)

DOMCharacterData->insertData() --  Insert a string at the specified 16-bit unit offset

Description

class DOMCharacterData {

void insertData ( int offset, string data )

}

Inserts string data at position offset.

Parameters

offset

The character offset at which to insert.

data

The string to insert.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

DOMCharacterData->replaceData()

(no version information, might be only in CVS)

DOMCharacterData->replaceData() --  Replace a substring within the DOMCharacterData node

Description

class DOMCharacterData {

void replaceData ( int offset, int count, string data )

}

Replace count characters starting from position offset with data.

Parameters

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.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMCharacterData->substringData()

(no version information, might be only in CVS)

DOMCharacterData->substringData() --  Extracts a range of data from the node

Description

class DOMCharacterData {

string substringData ( int offset, int count )

}

Returns the specified substring.

Parameters

offset

Start offset of substring to extract.

count

The number of characters to extract.

Return Values

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.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMComment->__construct()

(no version information, might be only in CVS)

DOMComment->__construct() --  Creates a new DOMComment object

Description

class DOMComment {

__construct ( [string value] )

}

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createComment().

Parameters

value

The value of the comment.

Examples

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->__construct()

(no version information, might be only in CVS)

DOMDocument->__construct() --  Creates a new DOMDocument object

Description

class DOMDocument {

__construct ( [string version [, string encoding]] )

}

Creates a new DOMDocument object.

Parameters

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.

Examples

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"?> */

?>

DOMDocument->createAttribute()

(no version information, might be only in CVS)

DOMDocument->createAttribute() -- Create new attribute

Description

class DOMDocument {

DOMAttr createAttribute ( string name )

}

This function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

name

The name of the attribute.

Return Values

The new DOMAttr or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

DOMDocument->createAttributeNS()

(no version information, might be only in CVS)

DOMDocument->createAttributeNS() --  Create new attribute node with an associated namespace

Description

class DOMDocument {

DOMAttr createAttributeNS ( string namespaceURI, string qualifiedName )

}

This function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

namespaceURI

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

Return Values

The new DOMAttr or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

DOMDocument->createCDATASection()

(no version information, might be only in CVS)

DOMDocument->createCDATASection() -- Create new cdata node

Description

class DOMDocument {

DOMCDATASection createCDATASection ( string data )

}

This function creates a new instance of class DOMCDATASection. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

data

The content of the cdata.

Return Values

The new DOMCDATASection or FALSE if an error occured.

DOMDocument->createComment()

(no version information, might be only in CVS)

DOMDocument->createComment() -- Create new comment node

Description

class DOMDocument {

DOMComment createComment ( string data )

}

This function creates a new instance of class DOMComment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

data

The content of the comment.

Return Values

The new DOMComment or FALSE if an error occured.

DOMDocument->createDocumentFragment()

(no version information, might be only in CVS)

DOMDocument->createDocumentFragment() -- Create new document fragment

Description

class DOMDocument {

DOMDocumentFragment createDocumentFragment ( void )

}

This function creates a new instance of class DOMDocumentFragment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Return Values

The new DOMDocumentFragment or FALSE if an error occured.

DOMDocument->createElement()

(no version information, might be only in CVS)

DOMDocument->createElement() -- Create new element node

Description

class DOMDocument {

DOMElement createElement ( string name [, string value] )

}

This function creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

name

The tag name of the element.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.

Return Values

Returns a new instance of class DOMElement or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Examples

Example 1. Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<test>This is the root element!</test>

DOMDocument->createElementNS()

(no version information, might be only in CVS)

DOMDocument->createElementNS() --  Create new element node with an associated namespace

Description

class DOMDocument {

DOMElement createElementNS ( string namespaceURI, string qualifiedName [, string value] )

}

This function creates a new element node with an associated namespace. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

namespaceURI

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.

Return Values

The new DOMElement or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

Examples

Example 1. Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

DOMDocument->createEntityReference()

(no version information, might be only in CVS)

DOMDocument->createEntityReference() -- Create new entity reference node

Description

class DOMDocument {

DOMEntityReference createEntityReference ( string name )

}

This function creates a new instance of class DOMEntityReference. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Return Values

The new DOMEntityReference or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

DOMDocument->createProcessingInstruction()

(no version information, might be only in CVS)

DOMDocument->createProcessingInstruction() -- Creates new PI node

Description

class DOMDocument {

DOMProcessingInstruction createProcessingInstruction ( string target [, string data] )

}

This function creates a new instance of class DOMProcessingInstruction. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

target

The target of the processing instruction.

data

The content of the processing instruction.

Return Values

The new DOMProcessingInstruction or FALSE if an error occured.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

DOMDocument->createTextNode()

(no version information, might be only in CVS)

DOMDocument->createTextNode() -- Create new text node

Description

class DOMDocument {

DOMText createTextNode ( string content )

}

This function creates a new instance of class DOMText. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

Parameters

content

The content of the text.

Return Values

The new DOMText or FALSE if an error occured.

DOMDocument->getElementById()

(no version information, might be only in CVS)

DOMDocument->getElementById() -- Searches for an element with a certain id

Description

class DOMDocument {

DOMElement getElementById ( string elementId )

}

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.

Parameters

elementId

The unique id value for an element.

Return Values

Returns the DOMElement or NULL if the element is not found.

Examples

Example 1. DOMDocument->getElementById() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is books is: " . $doc->getElementById('books')->tagName . "\n";

?>

The above example will output:

The element whose id is books is: chapter

DOMDocument->getElementsByTagName()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagName() -- Searches for all elements with given tag name

Description

class DOMDocument {

DOMNodeList getElementsByTagName ( string name )

}

This function returns a new instance of class DOMNodeList containing the elements with a given tag name.

Parameters

name

The name of the tag to match on. The special value * matches all tags.

Return Values

A new DOMNodeList object containing all the matched elements.

DOMDocument->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagNameNS() --  Searches for all elements with given tag name in specified namespace

Description

class DOMDocument {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parameters

namespaceURI

The namespace URI of the elements to match on. The special value * matches all namespaces.

localName

The local name of the elements to match on. The special value * matches all local names.

Return Values

A new DOMNodeList object containing all the matched elements.

Examples

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";
}
?>

The above example will output:

local name: include, prefix: xi
local name: fallback, prefix: xi

DOMDocument->importNode()

(no version information, might be only in CVS)

DOMDocument->importNode() -- Import node into current document

Description

class DOMDocument {

DOMNode importNode ( DOMNode importedNode [, bool deep] )

}

This function returns a copy of the node to import and associates it with the current document.

Parameters

importedNode

The node to import.

deep

If set to TRUE, this method will recursively import the subtree under the importedNode.

Return Values

The copied node.

Errors/Exceptions

DOMException is thrown if node cannot be imported.

DOMDocument->load()

(no version information, might be only in CVS)

DOMDocument->load() --  Load XML from a file

Description

class DOMDocument {

mixed load ( string filename [, int options] )

}

Loads an XML document from a file.

Parameters

filename

The path to the XML document.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument.

Examples

Example 1. Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

DOMDocument->loadHTML()

(no version information, might be only in CVS)

DOMDocument->loadHTML() --  Load HTML from a string

Description

class DOMDocument {

bool loadHTML ( string source )

}

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parameters

source

The HTML string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

DOMDocument->loadHTMLFile()

(no version information, might be only in CVS)

DOMDocument->loadHTMLFile() --  Load HTML from a file

Description

class DOMDocument {

bool loadHTMLFile ( string filename )

}

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parameters

filename

The path to the HTML file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

DOMDocument->loadXML()

(no version information, might be only in CVS)

DOMDocument->loadXML() --  Load XML from a string

Description

class DOMDocument {

mixed loadXML ( string source [, int options] )

}

Loads an XML document from a string.

This method may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parameters

source

The string containing the XML.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument.

Examples

Example 1. Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Example 2. Static invocation of loadXML

<?php
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

DOMDocument->normalizeDocument()

(no version information, might be only in CVS)

DOMDocument->normalizeDocument() -- Normalizes the document

Description

class DOMDocument {

void normalizeDocument ( void )

}

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Return Values

No value is returned.

DOMDocument->registerNodeClass()

(no version information, might be only in CVS)

DOMDocument->registerNodeClass() -- Register extended class used to create base node type

Description

class DOMDocument {

bool registerNodeClass ( string baseclass, string extendedclass )

}

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.

Parameters

baseclass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

Of course, you won't be able to register a class extending DOMDocument but you can always start your document by instanciating your own extending class.

extendedclass

Your extended class name. If NULL is provided, any previously registered class extending baseclass will be removed.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
PHP 5.2.2 Prior to 5.2.2, a previously registered extendedclass had to be unregistered before being able to register a new class extending the same baseclass.

Examples

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();

?>

The above example will output:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

DOMDocument->relaxNGValidate()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidate() --  Performs relaxNG validation on the document

Description

class DOMDocument {

bool relaxNGValidate ( string filename )

}

Performs relaxNG validation on the document based on the given RNG schema.

Parameters

filename

The RNG file.

Return Values

Returns TRUE on success or FALSE on failure.

DOMDocument->relaxNGValidateSource()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidateSource() --  Performs relaxNG validation on the document

Description

class DOMDocument {

bool relaxNGValidateSource ( string source )

}

Performs relaxNG validation on the document based on the given RNG source.

Parameters

source

A string containing the RNG schema.

Return Values

Returns TRUE on success or FALSE on failure.

DOMDocument->save()

(no version information, might be only in CVS)

DOMDocument->save() --  Dumps the internal XML tree back into a file

Description

class DOMDocument {

mixed save ( string filename [, int options] )

}

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Return Values

Returns the number of bytes written or FALSE if an error occurred.

ChangeLog

VersionDescription
5.1.0 Added the options parameter

Examples

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->saveHTML()

(no version information, might be only in CVS)

DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting

Description

class DOMDocument {

string saveHTML ( void )

}

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Return Values

Returns the HTML, or FALSE if an error occurred.

Examples

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()

(no version information, might be only in CVS)

DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting

Description

class DOMDocument {

int saveHTMLFile ( string filename )

}

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

filename

The path to the saved HTML document.

Return Values

Returns the number of bytes written or FALSE if an error occurred.

Examples

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->saveXML()

(no version information, might be only in CVS)

DOMDocument->saveXML() --  Dumps the internal XML tree back into a string

Description

class DOMDocument {

string saveXML ( [DOMNode node [, int options]] )

}

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Return Values

Returns the XML, or FALSE if an error occurred.

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

ChangeLog

VersionDescription
5.1.0 Added the options parameter

Examples

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);

?>

The above example will output:

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->schemaValidate()

(no version information, might be only in CVS)

DOMDocument->schemaValidate() --  Validates a document based on a schema

Description

class DOMDocument {

bool schemaValidate ( string filename )

}

Validates a document based on the given schema file.

Parameters

filename

The path to the schema.

Return Values

Returns TRUE on success or FALSE on failure.

DOMDocument->schemaValidateSource()

(no version information, might be only in CVS)

DOMDocument->schemaValidateSource() --  Validates a document based on a schema

Description

class DOMDocument {

bool schemaValidateSource ( string source )

}

Validates a document based on a schema defined in the given string.

Parameters

source

A string containing the schema.

Return Values

Returns TRUE on success or FALSE on failure.

DOMDocument->validate()

(no version information, might be only in CVS)

DOMDocument->validate() --  Validates the document based on its DTD

Description

class DOMDocument {

bool validate ( void )

}

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

Return Values

Returns TRUE on success or FALSE on failure. If the document have no DTD attached, this method will return FALSE.

Examples

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->xinclude()

(no version information, might be only in CVS)

DOMDocument->xinclude() --  Substitutes XIncludes in a DOMDocument Object

Description

class DOMDocument {

int xinclude ( [int options] )

}

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.

Parameters

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

Return Values

Returns the number of XIncludes in the document.

Examples

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();

?>

The above example will output something similar to:

<?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>

DOMDocumentFragment->appendXML()

(no version information, might be only in CVS)

DOMDocumentFragment->appendXML() -- Append raw XML data

Description

class DOMDocumentFragment {

bool appendXML ( string data )

}

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simplier 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.

Parameters

data

XML to append.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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(); 
?>

The above example will output:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

DOMElement->__construct()

(no version information, might be only in CVS)

DOMElement->__construct() --  Creates a new DOMElement object

Description

class DOMElement {

__construct ( string name [, string value [, string namespaceURI]] )

}

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createElement() or DOMDocument->createElementNS().

Parameters

name

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespaceURI

A namespace URI to create the element within a specific namespace.

Examples

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="iso-8859-1"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

DOMElement->getAttribute()

(no version information, might be only in CVS)

DOMElement->getAttribute() -- Returns value of attribute

Description

class DOMElement {

string getAttribute ( string name )

}

Gets the value of the attribute with name name for the current node.

Parameters

name

The name of the attribute.

Return Values

The value of the attribute, or an empty string if no attribute with the given name is found.

DOMElement->getAttributeNode()

(no version information, might be only in CVS)

DOMElement->getAttributeNode() -- Returns attribute node

Description

class DOMElement {

DOMAttr getAttributeNode ( string name )

}

Returns the attribute node with name name for the current element.

Parameters

name

The name of the attribute.

Return Values

The attribute node.

DOMElement->getAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNodeNS() --  Returns attribute node

Description

class DOMElement {

DOMAttr getAttributeNodeNS ( string namespaceURI, string localName )

}

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

The attribute node.

DOMElement->getAttributeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNS() -- Returns value of attribute

Description

class DOMElement {

string getAttributeNS ( string namespaceURI, string localName )

}

Gets the value of the attribute in namespace namespaceURI with local name localName for the current node.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

DOMElement->getElementsByTagName()

(no version information, might be only in CVS)

DOMElement->getElementsByTagName() -- Gets elements by tagname

Description

class DOMElement {

DOMNodeList getElementsByTagName ( string name )

}

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.

Parameters

name

The tag name. Use * to return all elements within the element tree.

Return Values

This function returns a new instance of the class DOMNodeList of all matched elements.

DOMElement->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName

Description

class DOMElement {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

This function fetch all the descendant elements with a given localName and namespaceURI.

Parameters

namespaceURI

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

Return Values

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

DOMElement->hasAttribute()

(no version information, might be only in CVS)

DOMElement->hasAttribute() -- Checks to see if attribute exists

Description

class DOMElement {

bool hasAttribute ( string name )

}

Indicates whether attribute named name exists as a member of the element.

Parameters

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

DOMElement->hasAttributeNS()

(no version information, might be only in CVS)

DOMElement->hasAttributeNS() --  Checks to see if attribute exists

Description

class DOMElement {

bool hasAttributeNS ( string namespaceURI, string localName )

}

Indicates whether attribute in namespace namespaceURI named localName exists as a member of the element.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

Returns TRUE on success or FALSE on failure.

DOMElement->removeAttribute()

(no version information, might be only in CVS)

DOMElement->removeAttribute() -- Removes attribute

Description

class DOMElement {

bool removeAttribute ( string name )

}

Removes attribute named name from the element.

Parameters

name

The name of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->removeAttributeNode()

(no version information, might be only in CVS)

DOMElement->removeAttributeNode() -- Removes attribute

Description

class DOMElement {

bool removeAttributeNode ( DOMAttr oldnode )

}

Removes attribute oldnode from the element.

Parameters

oldnode

The attribute node.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if oldnode is not an attribute of the element.

DOMElement->removeAttributeNS()

(no version information, might be only in CVS)

DOMElement->removeAttributeNS() -- Removes attribute

Description

class DOMElement {

bool removeAttributeNS ( string namespaceURI, string localName )

}

Removes attribute is namespace namespaceURI named localName from the element.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttribute()

(no version information, might be only in CVS)

DOMElement->setAttribute() -- Adds new attribute

Description

class DOMElement {

bool setAttribute ( string name, string value )

}

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

Parameters

name

The name of the attribute.

value

The value of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Examples

Example 1. Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

DOMElement->setAttributeNode()

(no version information, might be only in CVS)

DOMElement->setAttributeNode() -- Adds new attribute node to element

Description

class DOMElement {

DOMAttr setAttributeNode ( DOMAttr attr )

}

Adds new attribute node attr to element.

Parameters

attr

The attribute node.

Return Values

Returns old node if the attribute has been replaced or NULL.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNodeNS() -- Adds new attribute node to element

Description

class DOMElement {

DOMAttr setAttributeNodeNS ( DOMAttr attr )

}

Adds new attribute node attr to element.

Parameters

name

The attribute node.

Return Values

Returns the old node if the attribute has been replaced.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttributeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNS() -- Adds new attribute

Description

class DOMElement {

void setAttributeNS ( string namespaceURI, string qualifiedName, string value )

}

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

Parameters

namespaceURI

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

DOMElement->setIdAttribute()

(no version information, might be only in CVS)

DOMElement->setIdAttribute() -- Declares the attribute specified by name to be of type ID

Description

class DOMElement {

void setIdAttribute ( string name, bool isId )

}

Declares the attribute name to be of type ID.

Parameters

name

The name of the attribute.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

DOMElement->setIdAttributeNode()

(no version information, might be only in CVS)

DOMElement->setIdAttributeNode() -- Declares the attribute specified by node to be of type ID

Description

class DOMElement {

void setIdAttributeNode ( DOMAttr attr, bool isId )

}

Declares the attribute specified by attr to be of type ID.

Parameters

attr

The attribute node.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

DOMElement->setIdAttributeNS()

(no version information, might be only in CVS)

DOMElement->setIdAttributeNS() -- Declares the attribute specified by local name and namespace URI to be of type ID

Description

class DOMElement {

void setIdAttributeNS ( string namespaceURI, string localName, bool isId )

}

Declares the attribute specified by localName and namespaceURI to be of type ID.

Parameters

namespaceURI

The namespace URI of the attribute.

localName

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.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

DOMEntityReference->__construct()

(no version information, might be only in CVS)

DOMEntityReference->__construct() --  Creates a new DOMEntityReference object

Description

class DOMEntityReference {

__construct ( string name )

}

Creates a new DOMEntityReference object.

Parameters

name

The name of the entity reference.

Examples

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> */

?>

DOMImplementation->__construct()

(no version information, might be only in CVS)

DOMImplementation->__construct() --  Creates a new DOMImplementation object

Description

class DOMImplementation {

__construct ( (void); )

}

Creates a new DOMImplementation object.

DOMImplementation->createDocument()

(no version information, might be only in CVS)

DOMImplementation->createDocument() --  Creates a DOMDocument object of the specified type with its document element

Description

class DOMImplementation {

DOMDocument createDocument ( [string namespaceURI [, string qualifiedName [, DOMDocumentType doctype]]] )

}

Creates a DOMDocument object of the specified type with its document element.

Parameters

namespaceURI

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or NULL.

Return Values

A new DOMDocument object. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespaceURI and qualifiedName.

DOMImplementation->createDocumentType()

(no version information, might be only in CVS)

DOMImplementation->createDocumentType() --  Creates an empty DOMDocumentType object

Description

class DOMImplementation {

DOMDocumentType createDocumentType ( [string qualifiedName [, string publicId [, string systemId]]] )

}

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

Parameters

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

A new DOMDocumentType node with its ownerDocument set to NULL.

Examples

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();

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Errors/Exceptions

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

DOMImplementation->hasFeature()

(no version information, might be only in CVS)

DOMImplementation->hasFeature() --  Test if the DOM implementation implements a specific feature

Description

class DOMImplementation {

bool hasFeature ( string feature, string version )

}

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the Conformance section of the DOM specification.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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";
  }
}

?>

DOMNamedNodeMap->getNamedItem()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItem() --  Retrieves a node specified by name

Description

class DOMNamedNodeMap {

DOMNode getNamedItem ( string name )

}

Retrieves a node specified by its nodeName.

Parameters

name

The nodeName of the node to retrieve.

Return Values

A node (of any type) with the specified nodeName, or NULL if no node is found.

DOMNamedNodeMap->getNamedItemNS()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItemNS() --  Retrieves a node specified by local name and namespace URI

Description

class DOMNamedNodeMap {

DOMNode getNamedItemNS ( string namespaceURI, string localName )

}

Retrieves a node specified by localName and namespaceURI.

Parameters

namespaceURI

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Return Values

A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.

DOMNamedNodeMap->item()

(no version information, might be only in CVS)

DOMNamedNodeMap->item() -- Retrieves a node specified by index

Description

class DOMNamedNodeMap {

DOMNode item ( int index )

}

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parameters

index

Index into this map.

Return Values

The node at the indexth position in the map, or NULL if that is not a valid index (greater than or equal to the number of nodes in this map).

DOMNode->appendChild()

(no version information, might be only in CVS)

DOMNode->appendChild() --  Adds new child at the end of the children

Description

class DOMNode {

DOMNode appendChild ( DOMNode newnode )

}

This functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument->createElement(), DOMDocument->createTextNode() etc. or simply by using any other node.

Parameters

newnode

The appended child.

Return Values

The node added.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

Examples

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();
?>

DOMNode->cloneNode()

(no version information, might be only in CVS)

DOMNode->cloneNode() --  Clones a node

Description

class DOMNode {

DOMNode cloneNode ( [bool deep] )

}

Creates a copy of the node.

Parameters

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.

Return Values

The cloned node.

DOMNode->hasAttributes()

(no version information, might be only in CVS)

DOMNode->hasAttributes() --  Checks if node has attributes

Description

class DOMNode {

bool hasAttributes ( void )

}

This method checks if the node has attributes. The tested node have to be an XML_ELEMENT_NODE.

Return Values

Returns TRUE on success or FALSE on failure.

DOMNode->hasChildNodes()

(no version information, might be only in CVS)

DOMNode->hasChildNodes() --  Checks if node has children

Description

class DOMNode {

bool hasChildNodes ( void )

}

This function checks if the node has children.

Return Values

Returns TRUE on success or FALSE on failure.

DOMNode->insertBefore()

(no version information, might be only in CVS)

DOMNode->insertBefore() --  Adds a new child before a reference node

Description

class DOMNode {

DOMNode insertBefore ( DOMNode newnode [, DOMNode refnode] )

}

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

Parameters

newnode

The new node.

refnode

The reference node. If not supplied, newnode is appended to the children.

Return Values

The inserted node.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if refnode is not a child of this node.

DOMNode->isDefaultNamespace()

(no version information, might be only in CVS)

DOMNode->isDefaultNamespace() -- Checks if the specified namespaceURI is the default namespace or not

Description

class DOMNode {

bool isDefaultNamespace ( string namespaceURI )

}

Tells whether namespaceURI is the default namespace.

Parameters

namespaceURI

The namespace URI to look for.

Return Values

Return TRUE if namespaceURI is the default namespace, FALSE otherwise.

DOMNode->isSameNode()

(no version information, might be only in CVS)

DOMNode->isSameNode() --  Indicates if two nodes are the same node

Description

class DOMNode {

bool isSameNode ( DOMNode node )

}

This function indicates if two nodes are the same node. The comparison is not based on content

Parameters

node

The compared node.

Return Values

Returns TRUE on success or FALSE on failure.

DOMNode->isSupported()

(no version information, might be only in CVS)

DOMNode->isSupported() --  Checks if feature is supported for specified version

Description

class DOMNode {

bool isSupported ( string feature, string version )

}

Checks if the asked feature is supported for the specified version.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

DOMNode->lookupNamespaceURI()

(no version information, might be only in CVS)

DOMNode->lookupNamespaceURI() --  Gets the namespace URI of the node based on the prefix

Description

class DOMNode {

string lookupNamespaceURI ( string prefix )

}

Gets the namespace URI of the node based on the prefix.

Parameters

prefix

The prefix of the namespace.

Return Values

The namespace URI of the node.

DOMNode->lookupPrefix()

(no version information, might be only in CVS)

DOMNode->lookupPrefix() --  Gets the namespace prefix of the node based on the namespace URI

Description

class DOMNode {

string lookupPrefix ( string namespaceURI )

}

Gets the namespace prefix of the node based on the namespace URI.

Parameters

namespaceURI

The namespace URI.

Return Values

The prefix of the namespace.

DOMNode->normalize()

(no version information, might be only in CVS)

DOMNode->normalize() --  Normalizes the node

Description

class DOMNode {

void normalize ( void )

}

Normalizes the node.

Return Values

No value is returned.

DOMNode->removeChild()

(no version information, might be only in CVS)

DOMNode->removeChild() --  Removes child from list of children

Description

class DOMNode {

DOMNode removeChild ( DOMNode oldnode )

}

This functions removes a child from a list of children.

Parameters

oldnode

The removed child.

Return Values

If the child could be removed the functions returns the old child.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

Examples

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();
?>

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>
 
</book>

DOMNode->replaceChild()

(no version information, might be only in CVS)

DOMNode->replaceChild() --  Replaces a child

Description

class DOMNode {

DOMNode replaceChild ( DOMNode newnode, DOMNode oldnode )

}

This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Parameters

newnode

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument->importNode().

oldnode

The old node.

Return Values

The old node or FALSE if an error occur.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

DOMNodelist->item()

(no version information, might be only in CVS)

DOMNodelist->item() --  Retrieves a node specified by index

Description

class DOMNodeList {

DOMNode item ( int index )

}

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.

Parameters

index

Index of the node into the collection.

Return Values

The node at the indexth position in the DOMNodeList, or NULL if that is not a valid index.

Examples

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";
}

?>

The above example will output:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

DOMProcessingInstruction->__construct()

(no version information, might be only in CVS)

DOMProcessingInstruction->__construct() --  Creates a new DOMProcessingInstruction object

Description

class DOMProcessingInstruction {

__construct ( string name [, string value] )

}

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createProcessingInstruction().

Parameters

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Examples

Example 1. Creating a new DOMProcessingInstruction

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML(); 

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

DOMText->__construct()

(no version information, might be only in CVS)

DOMText->__construct() --  Creates a new DOMText object

Description

class DOMText {

__construct ( [string value] )

}

Creates a new DOMText object.

Parameters

value

The value of the text node. If not supplied an empty text node is created.

Examples

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> */

?>

DOMText->isWhitespaceInElementContent()

(no version information, might be only in CVS)

DOMText->isWhitespaceInElementContent() --  Indicates whether this text node contains whitespace

Description

class DOMText {

bool isWhitespaceInElementContent ( void )

}

Indicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.

Return Values

Returns TRUE on success or FALSE on failure.

DOMText->splitText()

(no version information, might be only in CVS)

DOMText->splitText() --  Breaks this node into two nodes at the specified offset

Description

class DOMText {

DOMText splitText ( int offset )

}

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parameters

offset

The offset at which to split, starting from 0.

Return Values

The new node of the same type, which contains all the content at and after the offset.

DOMXPath->__construct()

(no version information, might be only in CVS)

DOMXPath->__construct() --  Creates a new DOMXPath object

Description

class DOMXPath {

__construct ( DOMDocument doc )

}

Creates a new DOMXPath object.

Parameters

doc

The DOMDocument associated with the DOMXPath.

DOMXPath->evaluate()

(no version information, might be only in CVS)

DOMXPath->evaluate() --  Evaluates the given XPath expression and returns a typed result if possible.

Description

class DOMXPath {

mixed evaluate ( string expression [, DOMNode contextnode] )

}

Executes the given XPath expression and returns a typed result if possible.

Parameters

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.

Return Values

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

Examples

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";

?>

The above example will output:

There are 2 english books

DOMXPath->query()

(no version information, might be only in CVS)

DOMXPath->query() --  Evaluates the given XPath expression

Description

class DOMXPath {

DOMNodeList query ( string expression [, DOMNode contextnode] )

}

Executes the given XPath expression.

Parameters

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.

Return Values

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which do not return nodes will return an empty DOMNodeList.

Examples

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 starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

The above example will output:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextnode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

DOMXPath->registerNamespace()

(no version information, might be only in CVS)

DOMXPath->registerNamespace() --  Registers the namespace with the DOMXPath object

Description

class DOMXPath {

bool registerNamespace ( string prefix, string namespaceURI )

}

Registers the namespaceURI and prefix with the DOMXPath object.

Parameters

prefix

The prefix.

namespaceURI

The URI of the namespace.

Return Values

Returns TRUE on success or FALSE on failure.

dom_import_simplexml

(PHP 5)

dom_import_simplexml --  Gets a DOMElement object from a SimpleXMLElement object

Description

DOMElement dom_import_simplexml ( SimpleXMLElement node )

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

Parameters

node

The SimpleXMLElement node.

Return Values

The DOMElement node added or FALSE if any errors occur.

Examples

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();

?>

XXXI. DOM XML Functions

Introduction

The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only - you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Note: This extension is no longer marked experimental. It will, however, never be released with PHP 5, and will only be distributed with PHP 4. If you need DOM XML support with PHP 5 you can use the DOM extension. This domxml extension is not compatible with the DOM extension.


Requirements

This extension makes use of the GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the libxslt library and EXSLT enhancements from http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced) XSLT features. You will need at least libxslt-1.0.18.


Installation

This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/domxml.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. This extension is only available if PHP was configured with --with-dom[=DIR]. Add --with-dom-xslt[=DIR] to include DOM XSLT support. DIR is the libxslt install directory. Add --with-dom-exslt[=DIR] to include DOM EXSLT support, where DIR is the libexslt install directory.

Windows users will enable php_domxml.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/ Also, there is one additional DLL that must be made available to your system's PATH in order for this extension to work. In PHP 4 this is in the dlls/ directory. It's name: For PHP <= 4.2.0, it's libxml2.dll. For PHP >= 4.3.0, it's iconv.dll. And as of PHP 5.0.0, iconv is compiled into your Windows PHP binaries by default so no extra DLL is needed.


Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().

Table 1. Deprecated functions and their replacements

Old functionNew function
xmldocdomxml_open_mem()
xmldocfiledomxml_open_file()
domxml_new_xmldocdomxml_new_doc()
domxml_dump_memDomDocument_dump_mem()
domxml_dump_mem_fileDomDocument_dump_file()
DomDocument_dump_mem_fileDomDocument_dump_file()
DomDocument_add_rootDomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtdDomDocument_doctype()
DomDocument_rootDomDocument_document_element()
DomDocument_childrenDomNode_child_nodes()
DomDocument_imported_nodeNo replacement.
DomNode_add_childCreate a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_childrenDomNode_child_nodes()
DomNode_parentDomNode_parent_node()
DomNode_new_childCreate a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_contentCreate a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_contentContent is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_contentContent is just a text node and can be added with DomNode_append_child().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 2. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is an element
XML_ATTRIBUTE_NODE (integer) 2Node is an attribute
XML_TEXT_NODE (integer) 3Node is a piece of text
XML_CDATA_SECTION_NODE (integer) 4 
XML_ENTITY_REF_NODE (integer) 5 
XML_ENTITY_NODE (integer) 6Node is an entity like &nbsp;
XML_PI_NODE (integer) 7Node is a processing instruction
XML_COMMENT_NODE (integer) 8Node is a comment
XML_DOCUMENT_NODE (integer) 9Node is a document
XML_DOCUMENT_TYPE_NODE (integer) 10 
XML_DOCUMENT_FRAG_NODE (integer) 11 
XML_NOTATION_NODE (integer) 12 
XML_GLOBAL_NAMESPACE (integer) 1 
XML_LOCAL_NAMESPACE (integer) 2 
XML_HTML_DOCUMENT_NODE (integer)   
XML_DTD_NODE (integer)   
XML_ELEMENT_DECL_NODE (integer)   
XML_ATTRIBUTE_DECL_NODE (integer)   
XML_ENTITY_DECL_NODE (integer)   
XML_NAMESPACE_DECL_NODE (integer)   
XML_ATTRIBUTE_CDATA (integer)   
XML_ATTRIBUTE_ID (integer)   
XML_ATTRIBUTE_IDREF (integer)   
XML_ATTRIBUTE_IDREFS (integer)   
XML_ATTRIBUTE_ENTITY (integer)   
XML_ATTRIBUTE_NMTOKEN (integer)   
XML_ATTRIBUTE_NMTOKENS (integer)   
XML_ATTRIBUTE_ENUMERATION (integer)   
XML_ATTRIBUTE_NOTATION (integer)   
XPATH_UNDEFINED (integer)   
XPATH_NODESET (integer)   
XPATH_BOOLEAN (integer)   
XPATH_NUMBER (integer)   
XPATH_STRING (integer)   
XPATH_POINT (integer)   
XPATH_RANGE (integer)   
XPATH_LOCATIONSET (integer)   
XPATH_USERS (integer)   
XPATH_NUMBER (integer)   

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibility to older versions of the extension, and should not be used when creating new scripts.

This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().

This module defines a number of classes, which are listed - including their method - in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

Table 3. List of classes

Class nameParent classes
DomAttributeDomNode
DomCDataDomNode
DomCommentDomCData : DomNode
DomDocumentDomNode
DomDocumentTypeDomNode
DomElementDomNode
DomEntityDomNode
DomEntityReferenceDomNode
DomProcessingInstructionDomNode
DomTextDomCData : DomNode
ParserCurrently still called DomParser
XPathContext 

Table 4. DomDocument class (DomDocument : DomNode)

Method nameFunction nameRemark
doctypeDomDocument_doctype() 
document_elementDomDocument_document_element() 
create_elementDomDocument_create_element() 
create_text_nodeDomDocument_create_text_node() 
create_commentDomDocument_create_comment() 
create_cdata_sectionDomDocument_create_cdata_section() 
create_processing_instructionDomDocument_create_processing_instruction() 
create_attributeDomDocument_create_attribute() 
create_entity_referenceDomDocument_create_entity_reference() 
get_elements_by_tagnameDomDocument_get_elements_by_tagname() 
get_element_by_idDomDocument_get_element_by_id() 
dump_memDomDocument_dump_mem()not DOM standard
dump_fileDomDocument_dump_file()not DOM standard
html_dump_memDomDocument_html_dump_mem()not DOM standard
xpath_initxpath_initnot DOM standard
xpath_new_contextxpath_new_contextnot DOM standard
xptr_new_contextxptr_new_contextnot DOM standard

Table 5. DomElement class (DomElement : DomNode)

Method nameFunction nameRemark
tagnameDomElement_tagname() 
get_attributeDomElement_get_attribute() 
set_attributeDomElement_set_attribute() 
remove_attributeDomElement_remove_attribute() 
get_attribute_nodeDomElement_get_attribute_node() 
set_attribute_nodeDomElement_set_attribute_node() 
get_elements_by_tagnameDomElement_get_elements_by_tagname() 
has_attributeDomElement_has_attribute() 

Table 7. DomAttribute class (DomAttribute : DomNode)

Method name Remark
nameDomAttribute_name() 
valueDomAttribute_value() 
specifiedDomAttribute_specified() 

Table 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)

Method nameFunction nameRemark
targetDomProcessingInstruction_target() 
dataDomProcessingInstruction_data() 

Table 9. Parser class

Method nameFunction nameRemark
add_chunkParser_add_chunk() 
endParser_end() 

Table 10. XPathContext class

Method nameFunction nameRemark
evalXPathContext_eval() 
eval_expressionXPathContext_eval_expression() 
register_nsXPathContext_register_ns() 

Table 11. DomDocumentType class (DomDocumentType : DomNode)

Method nameFunction nameRemark
nameDomDocumentType_name() 
entitiesDomDocumentType_entities() 
notationsDomDocumentType_notations() 
public_idDomDocumentType_public_id() 
system_idDomDocumentType_system_id() 
internal_subsetDomDocumentType_internal_subset() 

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.


Examples

Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().

Example 1. Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &sp;
  <!-- comment -->
  <informaltable ID='findme' language='&sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Table of Contents
DomAttribute->name --  Returns the name of attribute
DomAttribute->set_value --  Sets the value of an attribute
DomAttribute->specified --  Checks if attribute is specified
DomAttribute->value --  Returns value of attribute
DomDocument->add_root --  Adds a root node [deprecated]
DomDocument->create_attribute -- Create new attribute
DomDocument->create_cdata_section -- Create new cdata node
DomDocument->create_comment -- Create new comment node
DomDocument->create_element_ns --  Create new element node with an associated namespace
DomDocument->create_element -- Create new element node
DomDocument->create_entity_reference --  Create an entity reference
DomDocument->create_processing_instruction -- Creates new PI node
DomDocument->create_text_node -- Create new text node
DomDocument->doctype --  Returns the document type
DomDocument->document_element --  Returns root element node
DomDocument->dump_file --  Dumps the internal XML tree back into a file
DomDocument->dump_mem --  Dumps the internal XML tree back into a string
DomDocument->get_element_by_id --  Searches for an element with a certain id
DomDocument->get_elements_by_tagname --  Returns array with nodes with given tagname in document or empty array, if not found
DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object
DomDocumentType->entities() --  Returns list of entities
DomDocumentType->internal_subset() --  Returns internal subset
DomDocumentType->name() --  Returns name of document type
DomDocumentType->notations() --  Returns list of notations
DomDocumentType->public_id() --  Returns public id of document type
DomDocumentType->system_id() --  Returns the system id of document type
DomElement->get_attribute_node() --  Returns the node of the given attribute
DomElement->get_attribute() --  Returns the value of the given attribute
DomElement->get_elements_by_tagname() --  Gets elements by tagname
DomElement->has_attribute() --  Checks to see if an attribute exists in the current node
DomElement->remove_attribute() --  Removes attribute
DomElement->set_attribute_node() --  Adds new attribute
DomElement->set_attribute() --  Sets the value of an attribute
DomElement->tagname() --  Returns the name of the current element
DomNode->add_namespace --  Adds a namespace declaration to a node
DomNode->append_child --  Adds a new child at the end of the children
DomNode->append_sibling --  Adds new sibling to a node
DomNode->attributes --  Returns list of attributes
DomNode->child_nodes --  Returns children of node
DomNode->clone_node --  Clones a node
DomNode->dump_node --  Dumps a single node
DomNode->first_child --  Returns first child of node
DomNode->get_content --  Gets content of node
DomNode->has_attributes --  Checks if node has attributes
DomNode->has_child_nodes --  Checks if node has children
DomNode->insert_before --  Inserts new node as child
DomNode->is_blank_node --  Checks if node is blank
DomNode->last_child --  Returns last child of node
DomNode->next_sibling --  Returns the next sibling of node
DomNode->node_name --  Returns name of node
DomNode->node_type --  Returns type of node
DomNode->node_value --  Returns value of a node
DomNode->owner_document --  Returns the document this node belongs to
DomNode->parent_node --  Returns the parent of the node
DomNode->prefix --  Returns name space prefix of node
DomNode->previous_sibling --  Returns the previous sibling of node
DomNode->remove_child --  Removes child from list of children
DomNode->replace_child --  Replaces a child
DomNode->replace_node --  Replaces node
DomNode->set_content --  Sets content of node
DomNode->set_name --  Sets name of node
DomNode->set_namespace --  Sets namespace of a node
DomNode->unlink_node --  Deletes node
DomProcessingInstruction->data --  Returns the data of ProcessingInstruction node
DomProcessingInstruction->target --  Returns the target of a ProcessingInstruction node
DomXsltStylesheet->process() --  Applies the XSLT-Transformation on a DomDocument Object
DomXsltStylesheet->result_dump_file() --  Dumps the result from a XSLT-Transformation into a file
DomXsltStylesheet->result_dump_mem() --  Dumps the result from a XSLT-Transformation back into a string
domxml_new_doc --  Creates new empty XML document
domxml_open_file -- Creates a DOM object from an XML file
domxml_open_mem -- Creates a DOM object of an XML document
domxml_version --  Gets the XML library version
domxml_xmltree --  Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object
domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file
domxml_xslt_stylesheet --  Creates a DomXsltStylesheet object from an XSL document in a string
domxml_xslt_version --  Gets the XSLT library version
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
xpath_eval --  Evaluates the XPath Location Path in the given string
xpath_new_context --  Creates new xpath context
xpath_register_ns_auto --  Register the given namespace in the passed XPath context
xpath_register_ns --  Register the given namespace in the passed XPath context
xptr_eval --  Evaluate the XPtr Location Path in the given string
xptr_new_context --  Create new XPath Context

DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name --  Returns the name of attribute

Description

class DomAttribute {

string name ( void )

}

Gets the name of the attribute.

Return Values

Returns the name of the attribute.

Migrating to PHP 5

Use the name property of DOMAttr.

See Also

DomAttribute->value for an example

DomAttribute->set_value

(no version information, might be only in CVS)

DomAttribute->set_value --  Sets the value of an attribute

Description

class DomAttribute {

bool set_value ( string content )

}

This function sets the value of an attribute.

Parameters

content

The new value.

Return Values

Returns TRUE on success or FALSE on failure.

Migrating to PHP 5

Set the value property of DOMAttr.

DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified --  Checks if attribute is specified

Description

class DomAttribute {

bool specified ( void )

}

Checks if the attribute was explicitly given a value in the original document.

Note: This method is not implemented yet.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

The definition of specified in the DOM Recommendations

DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value --  Returns value of attribute

Description

class DomAttribute {

string value ( void )

}

This function returns the value of the attribute.

Examples

Example 1. Getting all the attributes of a node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Error while parsing the document\n";
     exit;
}

$root = $dom->document_element();
$attrs = $root->attributes();

echo 'Attributes of ' . $root->node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute->name . ' : ' . $attribute->value . "\n";
}

?>

The above example will output:

Attributes of chapter
 - language : en

Return Values

Returns the value of the attribute.

Migrating to PHP 5

Use the value property of DOMAttr.

DomDocument->add_root

(no version information, might be only in CVS)

DomDocument->add_root --  Adds a root node [deprecated]

Description

domelement DomDocument->add_root ( string name )

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

Example 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");
$head = $root->new_child("head", "");
$head->new_child("title", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute -- Create new attribute

Description

domattribute DomDocument->create_attribute ( string name, string value )

This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

Description

domcdata DomDocument->create_cdata_section ( string content )

This function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Create new comment node

Description

domcomment DomDocument->create_comment ( string content )

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns --  Create new element node with an associated namespace

Description

domelement DomDocument->create_element_ns ( string uri, string name [, string prefix] )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Create new element node

Description

domelement DomDocument->create_element ( string name )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference --  Create an entity reference

Description

domentityreference DomDocument->create_entity_reference ( string content )

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute(), and domnode_insert_before().

DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

Description

domprocessinginstruction DomDocument->create_processing_instruction ( string content )

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

Description

domtext DomDocument->create_text_node ( string content )

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype --  Returns the document type

Description

domdocumenttype DomDocument->doctype ( void )

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element --  Returns root element node

Description

domelement DomDocument->document_element ( void )

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

Example 1. Retrieving root element

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

The above example will output:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file --  Dumps the internal XML tree back into a file

Description

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

Example 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also domdocument_dump_mem(), and domdocument_html_dump_mem().

DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem --  Dumps the internal XML tree back into a string

Description

string DomDocument->dump_mem ( [bool format [, string encoding]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

Example 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Note: The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id --  Searches for an element with a certain id

Description

domelement DomDocument->get_element_by_id ( string id )

This function is similar to domdocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also domdocument_get_elements_by_tagname()

DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname --  Returns array with nodes with given tagname in document or empty array, if not found

Description

array DomDocument->get_elements_by_tagname ( string name )

See also domdocument_add_root()

DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML

Description

string DomDocument->html_dump_mem ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Example 1. Creating a simple HTML document header

<?php

// Creates the document
$doc = domxml_new_doc("1.0");

$root = $doc->create_element("html");
$root = $doc->append_child($root);

$head = $doc->create_element("head");
$head = $root->append_child($head);

$title = $doc->create_element("title");
$title = $head->append_child($title);

$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);

echo $doc->html_dump_mem();
?>

The above example will output:

<html><head><title>This is the title</title></head></html>

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object

Description

int DomDocument->xinclude ( void )

This function substitutes XIncludes in a DomDocument object.

Example 1. Substituting Xincludes

<?php

// include.xml contains :
// <child>test</child> 

$xml = '<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="include.xml">
    <xi:fallback>
      <error>xinclude: include.xml not found</error>
    </xi:fallback>
  </xi:include>
</root>';

$domxml = domxml_open_mem($xml);
$domxml->xinclude();

echo $domxml->dump_mem();

?>

The above example will output:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <child>test</child>
</root>

If include.xml doesn't exist, you'll see:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <error>xinclude:dom.xml not found</error>
</root>

DomDocumentType->entities()

(no version information, might be only in CVS)

DomDocumentType->entities() --  Returns list of entities

Description

class DomDocumentType {

array entities ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Migrating to PHP 5

Use the entities property of the DOMDocumentType object.

DomDocumentType->internal_subset()

(no version information, might be only in CVS)

DomDocumentType->internal_subset() --  Returns internal subset

Description

class DomDocumentType {

bool internal_subset ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Migrating to PHP 5

Use the internalSubset property of the DOMDocumentType object.

DomDocumentType->name()

(no version information, might be only in CVS)

DomDocumentType->name() --  Returns name of document type

Description

class DomDocumentType {

string name ( void )

}

This function returns the name of the document type.

Return Values

Returns the name of the DomDocumentType, as a string.

Examples

Example 1. Getting the document type's name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$doctype = $dom->doctype();
echo $doctype->name(); // chapter

?>

Migrating to PHP 5

Use the name property of the DOMDocumentType object.

DomDocumentType->notations()

(no version information, might be only in CVS)

DomDocumentType->notations() --  Returns list of notations

Description

class DomDocumentType {

array notations ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Migrating to PHP 5

Use the notations property of the DOMDocumentType object.

DomDocumentType->public_id()

(no version information, might be only in CVS)

DomDocumentType->public_id() --  Returns public id of document type

Description

class DomDocumentType {

string public_id ( void )

}

This function returns the public id of the document type.

Return Values

Returns the public id of the DomDocumentType, as a string.

Examples

The following example echos nothing.

Example 1. Retrieving the public id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

Migrating to PHP 5

Use the publicId property of the DOMDocumentType object.

DomDocumentType->system_id()

(no version information, might be only in CVS)

DomDocumentType->system_id() --  Returns the system id of document type

Description

class DomDocumentType {

string system_id ( void )

}

Returns the system id of the document type.

Return Values

Returns the system id of the DomDocumentType, as a string.

Examples

Example 1. Retrieving the system id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

The above example will output:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

Migrating to PHP 5

Use the systemId property of the DOMDocumentType object.

DomElement->get_attribute_node()

(no version information, might be only in CVS)

DomElement->get_attribute_node() --  Returns the node of the given attribute

Description

class DomElement {

DomAttribute get_attribute_node ( string name )

}

Returns the node of the given attribute in the current element.

Parameters

name

The name of the seeked attribute. This parameter is case sensitive.

Return Values

Returns the node of the attribute as a DomAttribute or FALSE if no attribute with the given name is found.

Examples

Example 1. Getting an attribute node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
if ($attribute = $root->get_attribute_node('language')) {
    echo 'Language is: ' . $attribute->value() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement->getAttributeNode().

DomElement->get_attribute()

(no version information, might be only in CVS)

DomElement->get_attribute() --  Returns the value of the given attribute

Description

class DomElement {

string get_attribute ( string name )

}

Returns the value of the given attribute in the current element.

Since PHP 4.3, if no attribute with given name is found, an empty string is returned.

Parameters

name

The name of the seeked attribute. This parameter is case sensitive.

Return Values

Returns the name of the attribute as a string or an empty string if no attribute with the given name is found.

Examples

Example 1. Getting the value of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

// get chapter
$root = $dom->document_element();
echo $root->get_attribute('language'); // en

?>

Migrating to PHP 5

Use DOMElement->getAttribute().

DomElement->get_elements_by_tagname()

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname() --  Gets elements by tagname

Description

class DomElement {

array get_elements_by_tagname ( string name )

}

Gets all the sub elements with the specific name within the current element.

Parameters

name

The name of the seeked element.

Return Values

Returns an array of DomElement objects.

Examples

Example 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname('element');

foreach ($node_array as $node) {
    echo ' - ' . $node->get_content() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement->getElementsByTagName().

DomElement->has_attribute()

(no version information, might be only in CVS)

DomElement->has_attribute() --  Checks to see if an attribute exists in the current node

Description

class DomElement {

bool has_attribute ( string name )

}

This functions checks to see if an attribute named name exists in the current node.

Parameters

name

The name of the tested attribute.

Return Values

Returns TRUE if the asked attribute exists, FALSE otherwise.

Examples

Example 1. Testing the existence of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();

$buffer = '<html';
if ($root->has_attribute('language')) {
    $buffer .= 'lang="' . $root->get_attribute('language') . '"';
}
$buffer .= '>';

?>

Migrating to PHP 5

Use DOMElement->hasAttribute().

DomElement->remove_attribute()

(no version information, might be only in CVS)

DomElement->remove_attribute() --  Removes attribute

Description

class DomElement {

bool remove_attribute ( string name )

}

Removes an attribute from the current DomElement node.

Parameters

name

The name of the attribute to remove.

Return Values

Returns TRUE on success or FALSE on failure.

Migrating to PHP 5

Use DOMElement->removeAttribute().

DomElement->set_attribute_node()

(no version information, might be only in CVS)

DomElement->set_attribute_node() --  Adds new attribute

Description

class DomElement {

DomNode set_attribute_node ( DomNode attr )

}

Warning

This function is currently not documented; only the argument list is available.

DomElement->set_attribute()

(no version information, might be only in CVS)

DomElement->set_attribute() --  Sets the value of an attribute

Description

class DomElement {

DomAttribute set_attribute ( string name, string value )

}

Sets an attribute with name name to the given value.

Parameters

name

The name of the attribute. If this attribute doesn't exist, it will be created.

value

The value of the attribute.

Return Values

Returns the old DomAttribute node, or the new one if you are creating the attribute for the first time.

Examples

Example 1. Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Migrating to PHP 5

Use DOMElement->setAttribute().

DomElement->tagname()

(no version information, might be only in CVS)

DomElement->tagname() --  Returns the name of the current element

Description

class DomElement {

string tagname ( void )

}

Returns the name of the current node. Calling this function is the same as accessing the tagname property, or calling DomNode->node_name on the current node.

Return Values

Returns the name of the current DomElement node.

Examples

Example 1. Getting the node name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
echo $root->tagname();   // chapter
echo $root->tagname;     // chapter
echo $root->node_name(); // chapter


?>

Migrating to PHP 5

Use the tagName property of the DOMElement object.

DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace --  Adds a namespace declaration to a node

Description

class DOMNode {

bool add_namespace ( string uri, string prefix )

}

This method adds a namespace declaration to a node.

Note: This method is not part of the DOM specification.

Parameters

uri

The namespace URI of the node.

prefix

The namespace prefix of the node.

Return Values

Returns TRUE on success or FALSE on failure.

Migrating to PHP 5

You can set the namespace URI and prefix of a DOMElement or a DOMAttr at creation time by using DOMDocument->createElementNS() or DOMDocument->createAttributeNS().

Note: Remember the an attribute does not inherit its namespace from the element it is attached to.

DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child --  Adds a new child at the end of the children

Description

class DOMNode {

DOMNode append_child ( DOMNode newnode )

}

This functions appends a child to an existing list of children or creates a new list of children.

Parameters

newnode

The node being appended. It can be created with e.g. DomDocument->create_element, DomDocument->create_text_node etc. or simply by using any other node.

Note: You can not append a DOMAttribute using this method. Use DomElement->set_attribute() instead.

Return Values

Returns the appended node on success or FALSE on failure.

ChangeLog

VersionDescription
4.3.0 You are not allowed anymore to insert a node from another document.
4.3.0 Prior to PHP 4.3.0, the new child is duplicated before being appended. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the appended child. If you plan to do further modifications on the appended child you must use the returned node.
4.3.0 and 4.3.1 The new child newnode is first unlinked from its existing context, if it's already a child of DomNode. Therefore the newnode is moved and not copies anymore. This is the behaviour according to the W3C specifications. If you need the old behaviour, use DomNode->clone_node before appending.
4.3.2 The new child newnode is first unlinked from its existing context, if it's already in the tree. Same rules apply.

Examples

The following example adds a new element node to a fresh document and sets the attribute align to left.

Example 1. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

The above example could also be written as the following:

Example 2. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>

A more complex example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.

Example 3. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
?>

The above example could also be done with DomNode->insert_before instead of DomNode->append_child.

Migrating to PHP 5

You should use DOMNode->appendChild().

DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling --  Adds new sibling to a node

Description

domelement DomNode->append_sibling ( domelement newnode )

This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.

This function has been added to provide the behaviour of domnode_append_child() as it works till PHP 4.2.

See also domnode_append_before().

DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes --  Returns list of attributes

Description

array DomNode->attributes ( void )

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes --  Returns children of node

Description

array DomNode->child_nodes ( void )

Returns all children of the node.

See also domnode_next_sibling(), and domnode_previous_sibling().

DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node --  Clones a node

Description

domelement DomNode->clone_node ( void )

Warning

This function is currently not documented; only the argument list is available.

DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node --  Dumps a single node

Description

string DomNode->dump_node ( void )

Warning

This function is currently not documented; only the argument list is available.

See also domdocument_dump_mem().

DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child --  Returns first child of node

Description

domelement DomNode->first_child ( void )

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also domnode_last_child(), and domnode_next_sibling(), domnode_previous_sibling().

DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content --  Gets content of node

Description

string DomNode->get_content ( void )

This function returns the content of the actual node.

Example 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
    $node = $node_array[$i];
    echo "The element[$i] is: " . $node->get_content();
}

?>

DomNode->has_attributes

(no version information, might be only in CVS)

DomNode->has_attributes --  Checks if node has attributes

Description

bool DomNode->has_attributes ( void )

This function checks if the node has attributes.

See also domnode_has_child_nodes().

DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes --  Checks if node has children

Description

bool DomNode->has_child_nodes ( void )

This function checks if the node has children.

See also domnode_child_nodes().

DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before --  Inserts new node as child

Description

domelement DomNode->insert_before ( domelement newnode, domelement refnode )

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().

Example 1. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>

See also domnode_append_child().

DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node --  Checks if node is blank

Description

bool DomNode->is_blank_node ( void )

Warning

This function is currently not documented; only the argument list is available.

DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child --  Returns last child of node

Description

domelement DomNode->last_child ( void )

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also domnode_first_child(), and domnode_next_sibling(), domnode_previous_sibling().

DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling --  Returns the next sibling of node

Description

domelement DomNode->next_sibling ( void )

This function returns the next sibling of the current node. If there is no next sibling it returns FALSE (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

Example 1. Iterate over children

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also domnode_previous_sibling().

DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name --  Returns name of node

Description

string DomNode->node_name ( void )

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

Table 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSection#cdata-section
DomComment#comment
DomDocument#document
DomDocumentTypedocument type name
DomElementtag name
DomEntityname of entity
DomEntityReferencename of entity reference
DomNotationnotation name
DomProcessingInstructiontarget
DomText#text

DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type --  Returns type of node

Description

int DomNode->node_type ( void )

Returns the type of the node. All possible types are listed in the table in the introduction.

Example 1.

<?php

include 'example.inc';

$dom = domxml_open_mem($xmlstr);

$chapter = $dom->document_element();

// Let's see the elements contained in chapter
foreach($chapter->child_nodes() as $node) {
  if ($node->node_type() == XML_ELEMENT_NODE) {
    echo $node->node_name() . "\n";
  }
}

?>

The above example will output:

title
para

DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value --  Returns value of a node

Description

string DomNode->node_value ( void )

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

Table 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSectioncontent
DomCommentcontent of comment
DomDocumentnull
DomDocumentTypenull
DomElementnull
DomEntitynull
DomEntityReferencenull
DomNotationnull
DomProcessingInstructionentire content without target
DomTextcontent of text

DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document --  Returns the document this node belongs to

Description

domdocument DomNode->owner_document ( void )

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

Example 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also domnode_insert_before().

DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node --  Returns the parent of the node

Description

domnode DomNode->parent_node ( void )

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

Example 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix --  Returns name space prefix of node

Description

string DomNode->prefix ( void )

Returns the name space prefix of the node.

DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling --  Returns the previous sibling of node

Description

domelement DomNode->previous_sibling ( void )

This function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also domnode_next_sibling().

DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child --  Removes child from list of children

Description

domtext DomNode->remove_child ( domtext oldchild )

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.

Example 1. Removing a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child --  Replaces a child

Description

domelement DomNode->replace_child ( domelement newnode, domelement oldnode )

(PHP 4.2) This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned.

(PHP 4.3) This function replaces the child oldnode with the passed newnode, even if the new node already is a child of the DomNode. If newnode was already inserted in the document it is first unlinked from its existing context. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned. (This behaviour is according to the W3C specs).

See also domnode_append_child()

DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node --  Replaces node

Description

domelement DomNode->replace_node ( domelement newnode )

(PHP 4.2) This function replaces an existing node with the passed new node. Before the replacement newnode is copied if it has a parent to make sure a node which is already in the document will not be inserted a second time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like domnode_first_child(), domnode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode was already inserted in the document it is first unlinked from its existing context. If the replacement succeeds the old node is returned.

See also domnode_append_child()

DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content --  Sets content of node

Description

bool DomNode->set_content ( string content )

Warning

This function is currently not documented; only the argument list is available.

DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name --  Sets name of node

Description

bool DomNode->set_name ( void )

Sets name of node.

See also domnode_node_name().

DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace --  Sets namespace of a node

Description

void DomNode->set_namespace ( string uri [, string prefix] )

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), and domnode_add_namespace()

DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node --  Deletes node

Description

void DomNode->unlink_node ( void )

Warning

This function is currently not documented; only the argument list is available.

DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data --  Returns the data of ProcessingInstruction node

Description

class DomProcessingInstruction {

string data ( void )

}

This method gets the data of the ProcessingInstruction node.

Return Values

Returns the data of the Processing Instruction.

Migrating to PHP 5

Use the data property of DOMProcessingInstruction.

DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target --  Returns the target of a ProcessingInstruction node

Description

class DomProcessingInstruction {

string target ( void )

}

This method gets the target of the ProcessingInstruction node.

Return Values

Returns the target of the Processing Instruction.

Migrating to PHP 5

Use the target property of DOMProcessingInstruction.

DomXsltStylesheet->process()

(no version information, might be only in CVS)

DomXsltStylesheet->process() --  Applies the XSLT-Transformation on a DomDocument Object

Description

class DomXsltStylesheet {

DomDocument process ( DomDocument xml_doc [, array xslt_params [, bool is_xpath_param [, string profile_filename]]] )

}

Applies an XSLT Transformation on the given DomDocument object.

Parameters

xml_doc

The XML document being transformed, as a DomDocument object.

xslt_params

An associative array that takes pairs of parameter names and values.

is_xpath_param

If set to FALSE the values of the xslt_params will be quoted. This is the default behavior. It allows you to pass the values as PHP strings.

Note: If your strings contains both single and double quotes, you must take care of quoting all the values by yourself and set this parameter to TRUE.

profile_filename

Set this to the path of a filename, if you want profiling information.

Return Values

Returns the result of the processing, as a DomDocument object.

ChangeLog

VersionDescription
4.3.0 The profile_filename parameter was added.

DomXsltStylesheet->result_dump_file()

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_file() --  Dumps the result from a XSLT-Transformation into a file

Description

class DomXsltStylesheet {

string result_dump_file ( DomDocument xmldoc, string filename )

}

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.

Examples

Example 1. Saving the result of a XSLT transformation in a file

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");     
?>

DomXsltStylesheet->result_dump_mem()

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_mem() --  Dumps the result from a XSLT-Transformation back into a string

Description

class DomXsltStylesheet {

string result_dump_mem ( DomDocument xmldoc )

}

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.

Examples

Example 1. Outputting the result of a XSLT transformation

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);     
?>

domxml_new_doc

(PHP 4 >= 4.2.1, PECL)

domxml_new_doc --  Creates new empty XML document

Description

DomDocument domxml_new_doc ( string version )

Creates a new Dom document from scratch and returns it.

Parameters

version

The XML version number of the document.

Return Values

Returns a new DomDocument instance.

domxml_open_file

(PHP 4 >= 4.2.1, PECL)

domxml_open_file -- Creates a DOM object from an XML file

Description

DomDocument domxml_open_file ( string filename [, int mode [, array &error]] )

The function parses the XML document in the given file.

Parameters

filename

The path to the XML file. The file is accessed in read-only mode.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

Return Values

Returns a DomDocument instance of the given file.

Examples

Example 1. Opening an XML document from a file

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

ChangeLog

VersionDescription
4.3.0 The parameters mode and error were added.

domxml_open_mem

(PHP 4 >= 4.2.1, PECL)

domxml_open_mem -- Creates a DOM object of an XML document

Description

DomDocument domxml_open_mem ( string str [, int mode [, array &error]] )

The function parses the XML document in the given string.

Parameters

str

The contents of the XML file.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

Return Values

Returns a DomDocument instance of the given XML contents.

ChangeLog

VersionDescription
4.3.0 The mode and error parameters were added.

Examples

Example 1. Opening an XML document in a string

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

domxml_version

(PHP 4 >= 4.1.0, PECL)

domxml_version --  Gets the XML library version

Description

string domxml_version ( void )

Gets the version of the XML library currently used.

Return Values

The version of the XML library, as a string.

Examples

Example 1. domxml_version() Example

<?php

echo domxml_version();

?>

The above example will output something similar to:

20607

domxml_xmltree

(PHP 4 >= 4.2.1, PECL)

domxml_xmltree --  Creates a tree of PHP objects from an XML document

Description

DomDocument domxml_xmltree ( string str )

The function parses the XML document in str and returns a tree PHP objects as the parsed document.

This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file.

However this function may be valuable if you want to read a file and investigate the content.

Parameters

str

The contents of the XML file.

Return Values

Returns a tree of Dom objects starting by a DomDocument.

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object

Description

DomXsltStylesheet domxml_xslt_stylesheet_doc ( DomDocument xsl_doc )

Creates a DomXsltStylesheet object from the given XSL document.

Parameters

xsl_doc

The XSL document, as a DomDocument object.

Return Values

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet with the xsl_doc parameter.

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file

Description

DomXsltStylesheet domxml_xslt_stylesheet_file ( string xsl_file )

Creates a DomXsltStylesheet object from the given XSL file.

Parameters

xsl_file

The path to the XSL document, as a string.

Return Values

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet with DOMDocument::load($xsl_file) as parameter.

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet --  Creates a DomXsltStylesheet object from an XSL document in a string

Description

DomXsltStylesheet domxml_xslt_stylesheet ( string xsl_buf )

Creates a DomXsltStylesheet object from the given XSL buffer.

Parameters

xsl_buf

The XSL document, as a string.

Return Values

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet with DOMDocument::loadXML($xsl_buf) as parameter.

domxml_xslt_version

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_version --  Gets the XSLT library version

Description

int domxml_xslt_version ( void )

Gets the XSLT library version.

Return Values

Returns the version number of the XSLT library, as an integer.

Examples

Example 1. domxml_xslt_version() Example

<?php

echo domxml_xslt_version();

?>

The above example will output something similar to:

10112

xpath_eval_expression

(PHP 4 >= 4.0.4, PECL)

xpath_eval_expression --  Evaluates the XPath Location Path in the given string

Description

class XPathContext {

XPathObject xpath_eval_expression ( string expression [, domnode contextnode] )

}XPathObject xpath_eval_expression ( XPathContext xpath_context, string expression [, domnode contextnode] )

Example 1. xpath_eval_expression() Example

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$xpath = xpath_new_context($dom);
var_dump(xpath_eval_expression($xpath, '/chapter/@language'));

?>

The above example will output:

object(XPathObject)(2) {
   ["type"]=>
   int(1)
   ["nodeset"]=>
   array(1) {
     [0]=>
     object(domattribute)(5) {
       ["type"]=>
       int(2)
       ["name"]=>
       string(8) "language"
       ["value"]=>
       string(2) "en"
       [0]=>
       int(7)
       [1]=>
       int(138004256)
     }
  }
}

See also xpath_eval().

xpath_eval

(PHP 4 >= 4.0.4, PECL)

xpath_eval --  Evaluates the XPath Location Path in the given string

Description

class XPathContext {

XPathObject xpath_eval ( string xpath_expression [, domnode contextnode] )

}XPathObject xpath_eval ( XPathContext xpath_context, string xpath_expression [, domnode contextnode] )

The optional contextnode can be specified for doing relative XPath queries.

See also xpath_new_context().

xpath_new_context

(PHP 4 >= 4.0.4, PECL)

xpath_new_context --  Creates new xpath context

Description

XPathContext xpath_new_context ( domdocument dom_document )

See also xpath_eval().

xpath_register_ns_auto

(PECL)

xpath_register_ns_auto --  Register the given namespace in the passed XPath context

Description

bool xpath_register_ns_auto ( XPathContext xpath_context [, object context_node] )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

xpath_register_ns

(PHP 4 >= 4.2.0, PECL)

xpath_register_ns --  Register the given namespace in the passed XPath context

Description

bool xpath_register_ns ( XPathContext xpath_context, string prefix, string uri )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

xptr_eval

(PHP 4 >= 4.0.4, PECL)

xptr_eval --  Evaluate the XPtr Location Path in the given string

Description

class XPathContext {

int xptr_eval ( string eval_str [, domnode contextnode] )

}int xptr_eval ( XPathContext xpath_context, string eval_str [, domnode contextnode] )

Warning

This function is currently not documented; only the argument list is available.

xptr_new_context

(PHP 4 >= 4.0.4, PECL)

xptr_new_context --  Create new XPath Context

Description

XPathContext xptr_new_context ( void )

Warning

This function is currently not documented; only the argument list is available.

XXXII. enchant Functions

Introduction

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."

Enchat 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)


Requirements

This version uses the functions of the Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later.


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/enchant.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.


Examples

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";
    $spellerrors = enchant_dict_check($d, "soong");
    print_r($dprovides);
    echo "found $spellerrors spell errors\n";
    if ($spellerrors) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>
Table of Contents
enchant_broker_describe -- Enumerates the Enchant providers
enchant_broker_dict_exists -- Wether 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 dictionnaries
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. A PWL file is personal word file one word per line.
enchant_broker_set_ordering -- Declares a preference of dictionaries to use for the language
enchant_dict_add_to_personal -- add a word to personal word list
enchant_dict_add_to_session -- add 'word' to this spell-checking session
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_in_session -- whether or not 'word' exists in this spelling-session
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.

enchant_broker_describe

(PECL)

enchant_broker_describe -- Enumerates the Enchant providers

Description

array enchant_broker_describe ( resource broker )

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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);

?>

The above example will output something similar to:

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
        )

)

enchant_broker_dict_exists

(PECL)

enchant_broker_dict_exists -- Wether a dictionary exists or not. Using non-empty tag

Description

bool enchant_broker_dict_exists ( resource broker, string tag )

Tells if a dictionary exists or not, using a non-empty tags

Parameters

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Return Values

Returns TRUE when the tag exist or FALSE when not.

Examples

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_free_dict

(PECL)

enchant_broker_free_dict -- Free a dictionary resource

Description

bool enchant_broker_free_dict ( resource dict )

Free a dictionary resource.

Parameters

dict

Dictionary resource.

Return Values

Returns TRUE on success or FALSE on failure.

enchant_broker_free

(PECL)

enchant_broker_free -- Free the broker resource and its dictionnaries

Description

bool enchant_broker_free ( resource broker )

Free a broker resource with all its dictionaries.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

enchant_broker_get_error

(PECL)

enchant_broker_get_error -- Returns the last error of the broker

Description

string enchant_broker_get_error ( resource broker )

Returns the last error which occurred in this broker.

Parameters

broker

Broker resource.

Return Values

Return the msg string if an error was found or FALSE

enchant_broker_init

(PECL)

enchant_broker_init -- create a new broker object capable of requesting

Description

resource enchant_broker_init ( void )

Parameters

Return Values

Returns a broker resource on success or FALSE.

enchant_broker_list_dicts

(no version information, might be only in CVS)

enchant_broker_list_dicts -- Returns a list of available dictionaries

Description

mixed enchant_broker_list_dicts ( resource broker )

Returns a list of available dictionaries with their details.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

The above example will output something similar to:

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
        )

)

See Also

enchant_broker_describe ()

enchant_broker_request_dict

(PECL)

enchant_broker_request_dict -- create a new dictionary using a tag

Description

resource enchant_broker_request_dict ( resource broker, string tag )

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parameters

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Return Values

Returns a dictionary resource on success or FALSE on failure.

Examples

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);
}
?>

See Also

enchant_dict_describe()
enchant_broker_dict_exists()
enchant_broker_dict_free()

enchant_broker_request_pwl_dict

(PECL)

enchant_broker_request_pwl_dict -- creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Description

resource enchant_broker_request_pwl_dict ( resource broker, string filename )

creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Parameters

broker

Broker resource

filename

Path to the PWL file.

Return Values

Returns a dictionary resource on success or FALSE on failure.

See Also

enchant_dict_describe()
enchant_broker_dict_exists()
enchant_broker_dict_free()

enchant_broker_set_ordering

(PECL)

enchant_broker_set_ordering -- Declares a preference of dictionaries to use for the language

Description

bool enchant_broker_set_ordering ( resource broker, string tag, string ordering )

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.

Parameters

broker

Broker resource

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

Return Values

Returns TRUE on success or FALSE on failure.

enchant_dict_add_to_personal

(PECL)

enchant_dict_add_to_personal -- add a word to personal word list

Description

void enchant_dict_add_to_personal ( resource dict, string word )

Add a word to personal word list of the given dictionary.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

enchant_dict_add_to_session

(PECL)

enchant_dict_add_to_session -- add 'word' to this spell-checking session

Description

void enchant_dict_add_to_session ( resource dict, string word )

Add a word to the given dictionary. It will be added only for the active spell-checking session.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

enchant_dict_check

(PECL)

enchant_dict_check -- Check whether a word is correctly spelled or not.

Description

bool enchant_dict_check ( resource dict, string word )

If the word is correctly spelled return TRUE, otherwise return FALSE

Parameters

dict

Dictionary resource

word

The word to check

Return Values

Returns TRUE if the word is spelled correctly, FALSE if not.

enchant_dict_describe

(PECL)

enchant_dict_describe -- Describes an individual dictionary

Description

mixed enchant_dict_describe ( resource dict )

Returns the details of the dictionary.

Parameters

dict

Dictinaray resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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);
}
?>

The above example will output something similar to:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

enchant_dict_get_error

(PECL)

enchant_dict_get_error -- Returns the last error of the current spelling-session

Description

string enchant_dict_get_error ( resource dict )

Returns the last error of the current spelling-session

Parameters

dict

Dictinaray resource

Return Values

Returns the error message as string or FALSE if no error occurred.

enchant_dict_is_in_session

(PECL)

enchant_dict_is_in_session -- whether or not 'word' exists in this spelling-session

Description

bool enchant_dict_is_in_session ( resource dict, string word )

Tells whether or not a word already exists in the current session.

Parameters

dict

Dictionary resource

word

The word to lookup

Return Values

Returns TRUE if the word exists or FALSE

enchant_dict_quick_check

(PECL)

enchant_dict_quick_check -- Check the word is correctly spelled and provide suggestions

Description

bool enchant_dict_quick_check ( resource dict, string word [, array &suggestions] )

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parameters

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Return Values

Returns TRUE if the word is correctly spelled or FALSE

Examples

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);
}
?>

The above example will output something similar to:

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_store_replacement

(PECL)

enchant_dict_store_replacement -- add a correction for a word.

Description

void enchant_dict_store_replacement ( resource dict, string mis, string cor )

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.

Parameters

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Return Values

Returns TRUE on success or FALSE on failure.

enchant_dict_suggest

(PECL)

enchant_dict_suggest -- Will return a list of values if any of those pre-conditions are not met.

Description

array enchant_dict_suggest ( resource dict, string word )

Parameters

dict

Dictionary resource

word

Word to use for the suggestions.

Return Values

Will returns an array of suggestions if the word is bad spelled.

Examples

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);

    $spellerrors = enchant_dict_check($d, "soong");
    echo "found $spellerrors spell errors\n";
    if ($spellerrors) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

XXXIII. Error Handling and Logging Functions

Introduction

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Errors and Logging Configuration Options

NameDefaultChangeableChangelog
error_reportingNULLPHP_INI_ALL 
display_errors"1"PHP_INI_ALL 
display_startup_errors"0"PHP_INI_ALLAvailable since PHP 4.0.3.
log_errors"0"PHP_INI_ALL 
log_errors_max_len"1024"PHP_INI_ALLAvailable since PHP 4.3.0.
ignore_repeated_errors"0"PHP_INI_ALLAvailable since PHP 4.3.0.
ignore_repeated_source"0"PHP_INI_ALLAvailable since PHP 4.3.0.
report_memleaks"1"PHP_INI_ALLAvailable since PHP 4.3.0.
track_errors"0"PHP_INI_ALL 
html_errors"1"PHP_INI_ALLPHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2.
docref_root""PHP_INI_ALLAvailable since PHP 4.3.0.
docref_ext""PHP_INI_ALLAvailable since PHP 4.3.2.
error_prepend_stringNULLPHP_INI_ALL 
error_append_stringNULLPHP_INI_ALL 
error_logNULLPHP_INI_ALL 
warn_plus_overloadingNULLPHP_INI?? 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

error_reporting integer

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

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

Note: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

PHP Constants outside of PHP: Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. 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.

In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.

display_errors boolean

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Note: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Note: Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

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

Note: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

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

html_errors boolean

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

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by '/manual/' you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash '/'. But see the second example above which does not have nor need it.

Note: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

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

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.

warn_plus_overloading boolean

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


Predefined Constants

The constants below are always available as part of the PHP core.

Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

Table 2. Errors and Logging

ValueConstantDescriptionNote
1 E_ERROR (integer) Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.  
2 E_WARNING (integer) Run-time warnings (non-fatal errors). Execution of the script is not halted.  
4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.  
8 E_NOTICE (integer) Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.  
16 E_CORE_ERROR (integer) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. since PHP 4
32 E_CORE_WARNING (integer) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. since PHP 4
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. since PHP 4
128 E_COMPILE_WARNING (integer) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. since PHP 4
256 E_USER_ERROR (integer) User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
512 E_USER_WARNING (integer) User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
1024 E_USER_NOTICE (integer) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
2048 E_STRICT (integer) Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. since PHP 5
4096 E_RECOVERABLE_ERROR (integer) Catchable fatal error. It indicates that a probably dangerous error occured, 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
8191 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT in PHP < 6. 6143 in PHP 5.2.x and 2047 previously

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini, however, and that no bitwise operators will be understood within php3.ini.


Examples

Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

Example 1. Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) 
{
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR              => 'Error',
                E_WARNING            => 'Warning',
                E_PARSE              => 'Parsing Error',
                E_NOTICE             => 'Notice',
                E_CORE_ERROR         => 'Core Error',
                E_CORE_WARNING       => 'Core Warning',
                E_COMPILE_ERROR      => 'Compile Error',
                E_COMPILE_WARNING    => 'Compile Warning',
                E_USER_ERROR         => 'User Error',
                E_USER_WARNING       => 'User Warning',
                E_USER_NOTICE        => 'User Notice',
                E_STRICT             => 'Runtime Notice',
                E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
    
    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";
    
    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}


function distance($vect1, $vect2) 
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero", 
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero", 
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>


See Also

See also syslog().

Table of Contents
debug_backtrace -- Generates a backtrace
debug_print_backtrace --  Prints a backtrace
error_get_last -- Get the last occurred error
error_log -- Send an error message somewhere
error_reporting -- Sets which PHP errors are reported
restore_error_handler -- Restores the previous error handler function
restore_exception_handler --  Restores the previously defined exception handler function
set_error_handler -- Sets a user-defined error handler function
set_exception_handler --  Sets a user-defined exception handler function
trigger_error -- Generates a user-level error/warning/notice message
user_error -- Alias of trigger_error()

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace -- Generates a backtrace

Description

array debug_backtrace ( void )

debug_backtrace() generates a PHP backtrace.

Return Values

Returns an associative array. The possible returned elements are as follows:

Table 1. Possible returned elements from debug_backtrace()

NameTypeDescription
functionstring The current function name. See also __FUNCTION__.
lineinteger The current line number. See also __LINE__.
filestring The current file name. See also __FILE__.
classstring The current class name. See also __CLASS__
objectobject The current object.
typestring The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
argsarray If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

ChangeLog

VersionDescription
5.1.1 Added the current object as a possible return element.

Examples

Example 1. debug_backtrace() example

<?php
// filename: a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: b.php
include_once '/tmp/a.php';
?>

Results similar to the following when executing /tmp/b.php:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

debug_print_backtrace

(PHP 5)

debug_print_backtrace --  Prints a backtrace

Description

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example 1. debug_print_backtrace() example

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>
<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

The above example will output something similar to:

#0  eval() called at [/tmp/include.php:5]
#1  a() called at [/tmp/include.php:17]
#2  include(/tmp/include.php) called at [/tmp/test.php:3]

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

error_get_last

(no version information, might be only in CVS)

error_get_last -- Get the last occurred error

Description

array error_get_last ( void )

Gets information about the last error that occured.

Return Values

Returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet.

Examples

Example 1. An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

The above example will output something similar to:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

error_log

(PHP 3, PHP 4, PHP 5)

error_log -- Send an error message somewhere

Description

bool error_log ( string message [, int message_type [, string destination [, string extra_headers]]] )

Sends an error message to the web server's error log, a TCP port or to a file.

Parameters

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as follows:

Table 1. error_log() log types

0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information. This option is only available in PHP 3.
3 message is appended to the file destination. A newline is not automatically added to the end of the message string.

destination

The destination. Its meaning depends on the message_type parameter as described above.

extra_headers

The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// other ways of calling error_log():
error_log("You messed up!", 2, "127.0.0.1:7000");
error_log("You messed up!", 2, "loghost");
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

error_reporting

(PHP 3, PHP 4, PHP 5)

error_reporting -- Sets which PHP errors are reported

Description

int error_reporting ( [int level] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

Parameters

level

The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

The available error level constants are listed below. The actual meanings of these error levels are described in the predefined constants.

Table 1. error_reporting() level constants and bit values

valueconstant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR

Return Values

Returns the old error_reporting level.

ChangeLog

VersionDescription
5.0.0E_STRICT introduced (not part of E_ALL).
5.2.0E_RECOVERABLE_ERROR introduced.
6E_STRICT became part of E_ALL.

Examples

Example 1. error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Notes

Warning

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

See Also

The display_errors directive
ini_set()

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler -- Restores the previous error handler function

Description

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

Examples

Example 1. restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

The above example will output:

Invalid serialized value.

Notes

Note: Calling restore_error_handler() from the error_handler function is ignored.

restore_exception_handler

(PHP 5)

restore_exception_handler --  Restores the previously defined exception handler function

Description

bool restore_exception_handler ( void )

Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler -- Sets a user-defined error handler function

Description

mixed set_error_handler ( callback error_handler [, int error_types] )

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

Parameters

error_handler

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int errno, string errstr [, string errfile [, int errline [, array errcontext]]] )

errno

The first parameter, errno, contains the level of the error raised, as an integer.

errstr

The second parameter, errstr, contains the error message, as a string.

errfile

The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.

errline

The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.

errcontext

The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

Return Values

Returns a string containing the previously defined error handler (if any), or NULL on error. If the previous handler was a class method, this function will return an indexed array with the class and the method name.

ChangeLog

VersionDescription
5.2.0 The error handler must return FALSE to populate $php_errormsg.
5.0.0 The error_types parameter was introduced.
4.3.0 Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler.
4.0.2 Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

Examples

Example 1. Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error 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:
        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
?>

The above example will output something similar to:

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 />

set_exception_handler

(PHP 5)

set_exception_handler --  Sets a user-defined exception handler function

Description

string set_exception_handler ( callback exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parameters

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

Return Values

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Examples

Example 1. set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error -- Generates a user-level error/warning/notice message

Description

bool trigger_error ( string error_msg [, int error_type] )

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

Parameters

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Return Values

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Examples

Example 1. trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if (assert($divisor == 0)) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

user_error

(PHP 4, PHP 5)

user_error -- Alias of trigger_error()

Description

This function is an alias of: trigger_error().

XXXIV. Exif Functions

Introduction

With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.


Requirements

Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.


Installation

To enable exif-support configure PHP with --enable-exif

Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

Table 1. Exif configuration options

NameDefaultChangeableChangelog
exif.encode_unicode"ISO-8859-15"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.encode_jis""PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_jis_motorola"JIS"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_jis_intel"JIS"PHP_INI_ALLAvailable since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

EXIF_USE_MBSTRING (integer)

The exif_imagetype() lists several related built-in constants.

Table of Contents
exif_imagetype -- Determine the type of an image
exif_read_data -- Reads the EXIF headers from JPEG or TIFF
exif_tagname -- Get the header name for an index
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
read_exif_data -- Alias of exif_read_data()

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype -- Determine the type of an image

Description

int exif_imagetype ( string filename )

exif_imagetype() reads the first bytes of an image and checks its signature.

exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.

Parameters

filename

The image being checked.

Return Values

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

ChangeLog

VersionDescription
4.3.2 Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0Support for SWC

Predefined Constants

The following constants are defined, and represent possible exif_imagetype() return values:

Table 1. Imagetype Constants

ValueConstant
1IMAGETYPE_GIF
2IMAGETYPE_JPEG
3IMAGETYPE_PNG
4IMAGETYPE_SWF
5IMAGETYPE_PSD
6IMAGETYPE_BMP
7IMAGETYPE_TIFF_II (intel byte order)
8 IMAGETYPE_TIFF_MM (motorola byte order)
9IMAGETYPE_JPC
10IMAGETYPE_JP2
11IMAGETYPE_JPX
12IMAGETYPE_JB2
13IMAGETYPE_SWC
14IMAGETYPE_IFF
15IMAGETYPE_WBMP
16IMAGETYPE_XBM

Examples

Example 1. exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

See Also

getimagesize()

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data -- Reads the EXIF headers from JPEG or TIFF

Description

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]] )

exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.

Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.

When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.

The tag UserComment has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

exif_read_data() also validates EXIF data tags according to the EXIF specification (http://exif.org/Exif2-2.PDF, page 20).

Note: Windows ME/XP can both wipe the Exif headers when connecting to a camera. More information available at http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.

Parameters

filename

The name of the image file being read. This cannot be an URL.

sections

Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.

FILEFileName, FileSize, FileDateTime, SectionsFound
COMPUTED html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.
ANY_TAGAny information that has a Tag e.g. IFD0, EXIF, ...
IFD0 All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENTComment headers of JPEG images.
EXIF The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays

Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.

thumbnail

When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.

Return Values

It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.

ChangeLog

VersionDescription
4.3.0 Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached)
4.3.0 If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini
4.3.0 If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong.

Examples

Example 1. exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\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";
    }
}
?>

The first call fails because the image has no header information.

The above example will output something similar to:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname -- Get the header name for an index

Description

string exif_tagname ( string index )

Warning

This function is currently not documented; only the argument list is available.

Parameters

index

The image index

Return Values

Returns the header name, or FALSE if index is undefined.

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]] )

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.

It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.

Parameters

filename

The name of the image file being read. This image contains an embedded thumbnail.

width

The return width of the returned thumbnail.

height

The returned height of the returned thumbnail.

imagetype

The returned image type of the returned thumbnail. This is either TIFF or JPEG.

Return Values

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

ChangeLog

VersionDescription
4.3.0 The optional parameters width, height, and imagetype all became available.
4.3.0 May return thumbnails in the TIFF format.

Examples

Example 1. exif_thumbnail() example

<?php
if (array_key_exists('file', $_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header('Content-type: ' .image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo 'No thumbnail available';
}
?>

read_exif_data

(PHP 4 >= 4.0.1, PHP 5)

read_exif_data -- Alias of exif_read_data()

Description

This function is an alias of: exif_read_data().

XXXV. Expect Functions

Introduction

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.


Requirements

This module uses the functions of the expect library. You need libexpect version >= 5.43.0.


Installation

This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/expect.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. 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. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Table 1. Expect Configure Options

NameDefaultChangeableChangelog
expect.timeout"10"PHP_INI_ALL 
expect.loguser"1"PHP_INI_ALL 
expect.logfile""PHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

expect.timeout integer

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 boolean

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.


Resource Types

expect_popen() returns an open PTY stream used by expect_expectl().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

EXP_GLOB (integer)

Indicates that the pattern is a glob-style string pattern.

EXP_EXACT (integer)

Indicates that the pattern is an exact string.

EXP_REGEXP (integer)

Indicates that the pattern is a regexp-style string pattern.

EXP_EOF (integer)

Value, returned by expect_expectl(), when EOF is reached.

EXP_TIMEOUT (integer)

Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout

EXP_FULLBUFFER (integer)

Value, returned by expect_expectl() if no pattern have been matched.


Examples

This example connects to the remote host via SSH, and prints the remote uptime.

Example 1. Expect Usage Example

<?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);
?>
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

expect_expectl

(no version information, might be only in CVS)

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

Description

int expect_expectl ( resource expect, array cases [, array &match] )

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).

Parameters

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:

Table 1. Expect Case Array

Index KeyValue TypeDescriptionIs MandatoryDefault Value
0stringpattern, that will be matched against the output from the streamyes 
1mixedvalue, that will be returned by this function, if the pattern matchesyes 
2integer pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP noEXP_GLOB

Return Values

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

ChangeLog

VersionDescription
0.2.1 Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

Examples

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 (0 => "password:", 1 => PASSWORD),
  array (0 => "yes/no)?", 1 => YESNO)
);

while (true) {
 switch (expect_expectl ($stream, $cases))
 {
  case PASSWORD:
   fwrite ($stream, "password\n");
   break;

  case YESNO:
   fwrite ($stream, "yes\n");
   break;

  case EXP_TIMEOUT:
  case EXP_EOF:
   break 2;
  
  default:
   die ("Error has occurred!\n");
 }
}

fclose ($stream);
?>

See Also

expect_popen()

expect_popen

(no version information, might be only in CVS)

expect_popen -- Execute command via Bourne shell, and open the PTY stream to the process

Description

resource expect_popen ( string command )

Execute command via Bourne shell, and open the PTY stream to the process.

Parameters

command

Command to execute.

Return Values

Returns an open PTY stream to the process'es stdio, stdout and stderr.

On failure this function returns FALSE.

Examples

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);
?>

See Also

popen()

XXXVI. File Alteration Monitor Functions

Introduction

FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at http://oss.sgi.com/projects/fam/.

A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.

The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.


Requirements

This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.


Installation

To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

There are two resource types used in the FAM module. The first one is the connection to the FAM service returned by fam_open(), the second a monitoring resource returned by the fam_monitor_XXX functions.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 1. FAM event constants

ConstantDescription
FAMChanged (integer) Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) A file or directory was deleted or renamed.
FAMStartExecuting (integer) An executable file started executing.
FAMStopExecuting (integer) An executable file that was running finished.
FAMCreated (integer) A file was created in a directory.
FAMMoved (integer) This event never occurs.
FAMAcknowledge (integer) An event in response to fam_cancel_monitor().
FAMExists (integer) An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) Event after the last FAMEExists event.
Table of Contents
fam_cancel_monitor -- Terminate monitoring
fam_close -- Close FAM connection
fam_monitor_collection -- Monitor a collection of files in a directory for changes
fam_monitor_directory -- Monitor a directory for changes
fam_monitor_file -- Monitor a regular file for changes
fam_next_event -- Get next pending FAM event
fam_open -- Open connection to FAM daemon
fam_pending -- Check for pending FAM events
fam_resume_monitor -- Resume suspended monitoring
fam_suspend_monitor -- Temporarily suspend monitoring

fam_cancel_monitor

(PHP 5 <= 5.0.4)

fam_cancel_monitor -- Terminate monitoring

Description

bool fam_cancel_monitor ( resource fam, resource fam_monitor )

Terminates monitoring on a resource.

In addition an FAMAcknowledge event occurs.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

fam_close

(PHP 5 <= 5.0.4)

fam_close -- Close FAM connection

Description

void fam_close ( resource fam )

Closes a connection to the FAM service.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

No value is returned.

See Also

fam_monitor_open()

fam_monitor_collection

(PHP 5 <= 5.0.4)

fam_monitor_collection -- Monitor a collection of files in a directory for changes

Description

resource fam_monitor_collection ( resource fam, string dirname, int depth, string mask )

Requests monitoring for a collection of files within a directory.

A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Directory path to the monitored files

depth

The maximum search depth starting from this directory

mask

A shell pattern mask restricting the file names to look for

Return Values

Returns a monitoring resource or FALSE on errors.

fam_monitor_directory

(PHP 5 <= 5.0.4)

fam_monitor_directory -- Monitor a directory for changes

Description

resource fam_monitor_directory ( resource fam, string dirname )

Requests monitoring for a directory and all contained files.

A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) changes.

The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Path to the monitored directory

Return Values

Returns a monitoring resource or FALSE on errors.

fam_monitor_file

(PHP 5 <= 5.0.4)

fam_monitor_file -- Monitor a regular file for changes

Description

resource fam_monitor_file ( resource fam, string filename )

Requests monitoring for a single file. A FAM event will be generated whenever the file status changes (i.e. the result of function stat() on that file).

The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

filename

Path to the monitored file

Return Values

Returns a monitoring resource or FALSE on errors.

fam_next_event

(PHP 5 <= 5.0.4)

fam_next_event -- Get next pending FAM event

Description

array fam_next_event ( resource fam )

Returns the next pending FAM event.

The function will block until an event is available which can be checked for using fam_pending().

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

Returns an array that contains a FAM event code in the 'code' element, the path of the file this event applies to in the 'filename' element and optionally a hostname in the 'hostname' element.

The possible event codes are described in detail in the constants part of this section.

See Also

fam_pending()

fam_open

(PHP 5 <= 5.0.4)

fam_open -- Open connection to FAM daemon

Description

resource fam_open ( [string appname] )

Opens a connection to the FAM service daemon.

Parameters

appname

A string identifying the application for logging reasons

Return Values

Returns a resource representing a connection to the FAM service on success or FALSE on errors.

See Also

fam_close()

fam_pending

(PHP 5 <= 5.0.4)

fam_pending -- Check for pending FAM events

Description

int fam_pending ( resource fam )

Checks for pending FAM events.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

Returns non-zero if events are available to be fetched using fam_next_event(), zero otherwise.

fam_resume_monitor

(PHP 5 <= 5.0.4)

fam_resume_monitor -- Resume suspended monitoring

Description

bool fam_resume_monitor ( resource fam, resource fam_monitor )

Resumes monitoring of a resource previously suspended using fam_suspend_monitor().

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

fam_suspend_monitor

(PHP 5 <= 5.0.4)

fam_suspend_monitor -- Temporarily suspend monitoring

Description

bool fam_suspend_monitor ( resource fam, resource fam_monitor )

fam_suspend_monitor() temporarily suspend monitoring of a resource.

Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

XXXVII. Forms Data Format Functions

Introduction

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/acrobat/forms.jsp 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..


Requirements

You need the FDF toolkit SDK available from http://partners.adobe.com/asn/acrobat/forms.jsp. 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.


Installation

You must compile PHP with --with-fdftk[=DIR].

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 to Win32 Users: In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: fdftk.dll


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

fdf

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().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FDFValue (integer)

FDFStatus (integer)

FDFFile (integer)

FDFID (integer)

FDFFf (integer)

FDFSetFf (integer)

FDFClearFf (integer)

FDFFlags (integer)

FDFSetF (integer)

FDFClrF (integer)

FDFAP (integer)

FDFAS (integer)

FDFAction (integer)

FDFAA (integer)

FDFAPRef (integer)

FDFIF (integer)

FDFEnter (integer)

FDFExit (integer)

FDFDown (integer)

FDFUp (integer)

FDFFormat (integer)

FDFValidate (integer)

FDFKeystroke (integer)

FDFCalculate (integer)

FDFNormalAP (integer)

FDFRolloverAP (integer)

FDFDownAP (integer)


Examples

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);
?>

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

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_add_doc_javascript -- Adds javascript code to the FDF document

Description

bool fdf_add_doc_javascript ( resource fdf_document, string script_name, string script_code )

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.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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
%âãÏÓ
1 0 obj
<<
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

fdf_add_template

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

fdf_add_template -- Adds a template into the FDF document

Description

bool fdf_add_template ( resource fdf_document, int newpage, string filename, string template, int rename )

Warning

This function is currently not documented; only the argument list is available.

fdf_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_close -- Close an FDF document

Description

void fdf_close ( resource fdf_document )

Closes the FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

No value is returned.

See Also

fdf_open()

fdf_create

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_create -- Create a new FDF document

Description

resource fdf_create ( void )

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

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_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values -- Call a user defined function for each document value

Description

bool fdf_enum_values ( resource fdf_document, callback function [, mixed userdata] )

Warning

This function is currently not documented; only the argument list is available.

fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno -- Return error code for last fdf operation

Description

int fdf_errno ( void )

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

Return Values

Returns the error code as an integer, or zero if there was no errors.

See Also

fdf_error()

fdf_error

(PHP 4 >= 4.3.0, PHP 5)

fdf_error -- Return error description for FDF error code

Description

string fdf_error ( [int error_code] )

Gets a textual description for the FDF error code given in error_code.

Parameters

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

Return Values

Returns the error message as a string, or the string no error if nothing went wrong.

See Also

fdf_errno()

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_ap -- Get the appearance of a field

Description

bool fdf_get_ap ( resource fdf_document, string field, int face, string filename )

Gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_attachment -- Extracts uploaded file embedded in the FDF

Description

array fdf_get_attachment ( resource fdf_document, string fieldname, string savepath )

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath.

Parameters

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.

Return Values

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

Examples

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]";
?>

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_encoding -- Get the value of the /Encoding key

Description

string fdf_get_encoding ( resource fdf_document )

Gets the value of the /Encoding key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

fdf_get_file

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_file -- Get the value of the /F key

Description

string fdf_get_file ( resource fdf_document )

Gets the value of the /F key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

See Also

fdf_set_file()

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_flags -- Gets the flags of a field

Description

int fdf_get_flags ( resource fdf_document, string fieldname, int whichflags )

Warning

This function is currently not documented; only the argument list is available.

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_opt -- Gets a value from the opt array of a field

Description

mixed fdf_get_opt ( resource fdf_document, string fieldname [, int element] )

Warning

This function is currently not documented; only the argument list is available.

fdf_get_status

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_status -- Get the value of the /STATUS key

Description

string fdf_get_status ( resource fdf_document )

Gets the value of the /STATUS key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

fdf_get_value

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_value -- Get the value of a field

Description

mixed fdf_get_value ( resource fdf_document, string fieldname [, int which] )

Gets the value for the requested field.

Parameters

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.

Return Values

Returns the field value.

ChangeLog

VersionDescription
4.3.0 Support for arrays and the which parameter were added.

See Also

fdf_set_value()

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_version -- Gets version number for FDF API or file

Description

string fdf_get_version ( [resource fdf_document] )

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

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_header

(PHP 4 >= 4.3.0, PHP 5)

fdf_header -- Sets FDF-specific output headers

Description

void 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.

Return Values

No value is returned.

fdf_next_field_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_next_field_name -- Get the next field name

Description

string fdf_next_field_name ( resource fdf_document [, string fieldname] )

Gets the name of the field after the given field. This name can be used with several functions.

Parameters

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.

Return Values

Returns the field name as a string.

Examples

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";
}
?>

See Also

fdf_get_value()

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_open_string -- Read a FDF document from a string

Description

resource fdf_open_string ( string fdf_data )

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.

Parameters

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example 1. Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

fdf_open

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_open -- Open a FDF document

Description

resource fdf_open ( string filename )

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

Parameters

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().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

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_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item -- Sets target frame for form

Description

bool fdf_remove_item ( resource fdf_document, string fieldname, int item )

Warning

This function is currently not documented; only the argument list is available.

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_save_string -- Returns the FDF document as a string

Description

string fdf_save_string ( resource fdf_document )

Returns the FDF document as a string.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the document as a string, or FALSE on error.

Examples

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;
?>

The above example will output:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /Fields 2 0 R >>
>>
endobj
2 0 obj
[
<< /T (foo)/V (bar)>>
]
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

fdf_save

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_save -- Save a FDF document

Description

bool fdf_save ( resource fdf_document [, string filename] )

Saves a FDF document.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_ap

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_ap -- Set the appearance of a field

Description

bool fdf_set_ap ( resource fdf_document, string field_name, int face, string filename, int page_number )

Sets the appearance of a field (i.e. the value of the /AP key).

Parameters

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

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_encoding

(PHP 4 >= 4.1.0, PHP 5)

fdf_set_encoding -- Sets FDF character encoding

Description

bool fdf_set_encoding ( resource fdf_document, string encoding )

Sets the character encoding for the FDF document.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_file

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_file -- Set PDF document to display FDF data in

Description

bool fdf_set_file ( resource fdf_document, string url [, string target_frame] )

Selects a different PDF document to display the form results in then the form it originated from.

Parameters

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().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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_set_flags

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_flags -- Sets a flag of a field

Description

bool fdf_set_flags ( resource fdf_document, string fieldname, int whichFlags, int newFlags )

Sets certain flags of the given field.

Parameters

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

Return Values

Returns TRUE on success or FALSE on failure.

See Also

fdf_set_opt()

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_javascript_action -- Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( resource fdf_document, string fieldname, int trigger, string script )

Sets a javascript action for the given field.

Parameters

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

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDF

Description

bool fdf_set_on_import_javascript ( resource fdf_document, string script, bool before_data_import )

Warning

This function is currently not documented; only the argument list is available.

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_opt -- Sets an option of a field

Description

bool fdf_set_opt ( resource fdf_document, string fieldname, int element, string str1, string str2 )

Sets options of the given field.

Parameters

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

Return Values

Returns TRUE on success or FALSE on failure.

See Also

fdf_set_flags()

fdf_set_status

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_status -- Set the value of the /STATUS key

Description

bool fdf_set_status ( resource fdf_document, string status )

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.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_submit_form_action -- Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( resource fdf_document, string fieldname, int trigger, string script, int flags )

Sets a submit form action for the given field.

Parameters

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

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_target_frame -- Set target frame for form display

Description

bool fdf_set_target_frame ( resource fdf_document, string frame_name )

Sets the target frame to display a result PDF defined with fdf_save_file() in.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

fdf_save_file()

fdf_set_value

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_value -- Set the value of a field

Description

bool fdf_set_value ( resource fdf_document, string fieldname, mixed value [, int isName] )

Sets the value for the given field.

Parameters

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 beginning with PHP 4.3, but ignored internally.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
4.3.0 Support for arrays in the value parameter was added.

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_version -- Sets version number for a FDF file

Description

bool fdf_set_version ( resource fdf_document, string version )

Sets the FDF version for the given document.

Some features supported by this extension are only available in newer FDF versions.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

XXXVIII. Fileinfo Functions

Introduction

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.


Requirements

magic_open library is needed to build this extension.


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/fileinfo


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FILEINFO_NONE (integer)

No special handling.

FILEINFO_SYMLINK (integer)

Follow symlinks.

FILEINFO_MIME (integer)

Return a mime string, instead of a textual description.

FILEINFO_COMPRESS (integer)

Decompress compressed files.

FILEINFO_DEVICES (integer)

Look at the contents of blocks or character special devices.

FILEINFO_CONTINUE (integer)

Return all matches, not just the first.

FILEINFO_PRESERVE_ATIME (integer)

If possible preserve the original access time.

FILEINFO_RAW (integer)

Don't translate unprintable characters to a \ooo octal representation.

Table of Contents
finfo_buffer -- Return information about a string buffer
finfo_close -- Close fileinfo resource
finfo_file -- Return information about a file
finfo_open -- Create a new fileinfo resource
finfo_set_flags -- Set libmagic configuration options

finfo_buffer

(PECL)

finfo_buffer -- Return information about a string buffer

Description

string finfo_buffer ( resource finfo, string string [, int options [, resource context]] )

class finfo {

string buffer ( string string [, int options [, resource context]] )

}

This function is used to get information about binary data in a string.

Parameters

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

Examples

Example 1. A finfo_buffer() example

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

The above example will output something similar to:

application/x-sh

See Also

finfo_file()

finfo_close

(PECL)

finfo_close -- Close fileinfo resource

Description

bool finfo_close ( resource finfo )

class finfo {

__destruct(); }

This function closes the resource opened by finfo_open().

Parameters

finfo

Fileinfo resource returned by finfo_open().

Return Values

Returns TRUE on success or FALSE on failure.

finfo_file

(PECL)

finfo_file -- Return information about a file

Description

string finfo_file ( resource finfo, string file_name [, int options [, resource context]] )

class finfo {

string file ( string file_name [, int options [, resource context]] )

}

This function is used to get information about a file.

Parameters

finfo

Fileinfo resource returned by finfo_open().

file_name

Name of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

Examples

Example 1. A finfo_file() example

<?php
$finfo = finfo_open(FILEINFO_MIME); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel

See Also

finfo_buffer()

finfo_open

(PECL)

finfo_open

(no version information, might be only in CVS)

finfo->__construct() -- Create a new fileinfo resource

Description

Procedural style

resource finfo_open ( [int options [, string arg]] )

Object oriented style (constructor):

class finfo {

__construct ( [int options [, string magic_file]] )

}

This function opens a magic database and returns its resource.

Parameters

options

One or disjunction of more Fileinfo constants.

magic_file

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

Return Values

Returns a magic database resource on success or FALSE on failure.

Examples

Example 1. Object oriented style

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

/* close connection */
$finfo->close();
?>

Example 2. Procedural style

<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);

/* close connection */
finfo_close($finfo);
?>

The above example will output:

text/plain

See Also

finfo_close()

finfo_set_flags

(PECL)

finfo_set_flags -- Set libmagic configuration options

Description

bool finfo_set_flags ( resource finfo, int options )

class finfo {

bool set_flags ( int options )

}

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

Parameters

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Return Values

Returns TRUE on success or FALSE on failure.

XXXIX. filePro Functions

Introduction

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.2.0.


Installation

filePro support in PHP is not enabled by default. To enable the bundled read-only filePro support you need to use the--enable-filepro configuration option when compiling PHP.

Table of Contents
filepro_fieldcount -- Find out how many fields are in a filePro database
filepro_fieldname -- Gets the name of a field
filepro_fieldtype -- Gets the type of a field
filepro_fieldwidth -- Gets the width of a field
filepro_retrieve -- Retrieves data from a filePro database
filepro_rowcount -- Find out how many rows are in a filePro database
filepro -- Read and verify the map file

filepro_fieldcount

(PHP 3, PHP 4, PHP 5)

filepro_fieldcount -- Find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void )

Returns the number of fields (columns) in the opened filePro database.

Return Values

Returns the number of fields in the opened filePro database, or FALSE on errors.

See Also

filepro()

filepro_fieldname

(PHP 3, PHP 4, PHP 5)

filepro_fieldname -- Gets the name of a field

Description

string filepro_fieldname ( int field_number )

Returns the name of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the name of the field as a string, or FALSE on errors.

filepro_fieldtype

(PHP 3, PHP 4, PHP 5)

filepro_fieldtype -- Gets the type of a field

Description

string filepro_fieldtype ( int field_number )

Returns the edit type of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the edit type of the field as a string, or FALSE on errors.

filepro_fieldwidth

(PHP 3, PHP 4, PHP 5)

filepro_fieldwidth -- Gets the width of a field

Description

int filepro_fieldwidth ( int field_number )

Returns the width of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the width of the field as a integer, or FALSE on errors.

filepro_retrieve

(PHP 3, PHP 4, PHP 5)

filepro_retrieve -- Retrieves data from a filePro database

Description

string filepro_retrieve ( int row_number, int field_number )

Returns the data from the specified location in the database.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

Parameters

row_number

The row number. Must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1)

field_number

The field number. Accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)

Return Values

Returns the specified data, or FALSE on errors.

filepro_rowcount

(PHP 3, PHP 4, PHP 5)

filepro_rowcount -- Find out how many rows are in a filePro database

Description

int filepro_rowcount ( void )

Returns the number of rows in the opened filePro database.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

Return Values

Returns the number of rows in the opened filePro database, or FALSE on errors.

See Also

filepro()

filepro

(PHP 3, PHP 4, PHP 5)

filepro -- Read and verify the map file

Description

bool filepro ( string directory )

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

Parameters

directory

The map directory.

Return Values

Returns TRUE on success or FALSE on failure.

XL. Filesystem Functions


Requirements

No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Filesystem and Streams Configuration Options

NameDefaultChangeableChangelog
allow_url_fopen"1"PHP_INI_SYSTEMPHP_INI_ALL in PHP <= 4.3.4. Available since PHP 4.0.4.
allow_url_include"0"PHP_INI_SYSTEMAvailable since PHP 5.2.0.
user_agentNULLPHP_INI_ALLAvailable since PHP 4.3.0.
default_socket_timeout"60"PHP_INI_ALLAvailable since PHP 4.3.0.
from""PHP_INI_ALL 
auto_detect_line_endings"0"PHP_INI_ALLAvailable since PHP 4.3.0.

Here's a short explanation of the configuration directives.

allow_url_fopen boolean

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

Note: This setting can only be set in php.ini due to security reasons.

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

Warning

On Windows versions prior to PHP 4.3.0, the following functions do not support remote file accessing: include(), include_once(), require(), require_once() and the imagecreatefromXXX functions in the Reference LXV, Image Functions extension.

allow_url_include boolean

This option allows the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once().

Note: This setting requires allow_url_fopen to be on.

user_agent string

Define the user agent for PHP to send.

default_socket_timeout integer

Default timeout (in seconds) for socket based streams.

Note: This configuration option was introduced in PHP 4.3.0

from string

Define the anonymous ftp password (your email address).

auto_detect_line_endings boolean

When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

Note: This configuration option was introduced in PHP 4.3.0


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GLOB_BRACE (integer)

GLOB_ONLYDIR (integer)

GLOB_MARK (integer)

GLOB_NOSORT (integer)

GLOB_NOCHECK (integer)

GLOB_NOESCAPE (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

PATHINFO_FILENAME (integer)

Since PHP 5.2.0.

FILE_USE_INCLUDE_PATH (integer)

Since PHP 5.0.0. Search for filename in include_path.

FILE_APPEND (integer)

FILE_IGNORE_NEW_LINES (integer)

Since PHP 5.0.0. Strips EOL characters.

FILE_SKIP_EMPTY_LINES (integer)

Since PHP 5.0.0. Skips empty lines.


See Also

For related functions, see also the Directory and Program Execution sections.

For a list and explanation of the various URL wrappers that can be used as remote files, see also Appendix O.

Table of Contents
basename -- Returns filename component of path
chgrp -- Changes file group
chmod -- Changes file mode
chown -- Changes file owner
clearstatcache -- Clears file status cache
copy -- Copies file
delete -- See unlink() or unset()
dirname -- Returns directory name component of path
disk_free_space -- Returns available space in directory
disk_total_space -- Returns the total size of a directory
diskfreespace -- Alias of disk_free_space()
fclose -- Closes an open file pointer
feof -- Tests for end-of-file on a file pointer
fflush -- Flushes the output to a file
fgetc -- Gets character from file pointer
fgetcsv -- Gets line from file pointer and parse for CSV fields
fgets -- Gets line from file pointer
fgetss -- Gets line from file pointer and strip HTML tags
file_exists -- Checks whether a file or directory exists
file_get_contents -- Reads entire file into a string
file_put_contents -- Write a string to a file
file -- Reads entire file into an array
fileatime -- Gets last access time of file
filectime -- Gets inode change time of file
filegroup -- Gets file group
fileinode -- Gets file inode
filemtime -- Gets file modification time
fileowner -- Gets file owner
fileperms -- Gets file permissions
filesize -- Gets file size
filetype -- Gets file type
flock -- Portable advisory file locking
fnmatch -- Match filename against a pattern
fopen -- Opens file or URL
fpassthru -- Output all remaining data on a file pointer
fputcsv -- Format line as CSV and write to file pointer
fputs -- Alias of fwrite()
fread -- Binary-safe file read
fscanf -- Parses input from a file according to a format
fseek -- Seeks on a file pointer
fstat -- Gets information about a file using an open file pointer
ftell -- Tells file pointer read/write position
ftruncate -- Truncates a file to a given length
fwrite -- Binary-safe file write
glob -- Find pathnames matching a pattern
is_dir -- Tells whether the filename is a directory
is_executable -- Tells whether the filename is executable
is_file -- Tells whether the filename is a regular file
is_link -- Tells whether the filename is a symbolic link
is_readable -- Tells whether the filename is readable
is_uploaded_file -- Tells whether the file was uploaded via HTTP POST
is_writable -- Tells whether the filename is writable
is_writeable -- Alias of is_writable()
lchgrp -- Changes group ownership of symlink
lchown -- Changes user ownership of symlink
link -- Create a hard link
linkinfo -- Gets information about a link
lstat -- Gives information about a file or symbolic link
mkdir -- Makes directory
move_uploaded_file -- Moves an uploaded file to a new location
parse_ini_file -- Parse a configuration file
pathinfo -- Returns information about a file path
pclose -- Closes process file pointer
popen -- Opens process file pointer
readfile -- Outputs a file
readlink -- Returns the target of a symbolic link
realpath -- Returns canonicalized absolute pathname
rename -- Renames a file or directory
rewind -- Rewind the position of a file pointer
rmdir -- Removes directory
set_file_buffer -- Alias of stream_set_write_buffer()
stat -- Gives information about a file
symlink -- Creates a symbolic link
tempnam -- Create file with unique file name
tmpfile -- Creates a temporary file
touch -- Sets access and modification time of file
umask -- Changes the current umask
unlink -- Deletes a file

basename

(PHP 3, PHP 4, PHP 5)

basename -- Returns filename component of path

Description

string basename ( string path [, string suffix] )

Given a string containing a path to a file, this function will return the base name of the file. If the filename ends in suffix this will also be cut off.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Example 1. basename() example

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);        // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

Note: The suffix parameter was added in PHP 4.1.0.

See also dirname().

chgrp

(PHP 3, PHP 4, PHP 5)

chgrp -- Changes file group

Description

bool chgrp ( string filename, mixed group )

Attempts to change the group of the file filename to group.

Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parameters

filename

Path to the file.

group

A group name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

See Also

chown()
chmod()

chmod

(PHP 3, PHP 4, PHP 5)

chmod -- Changes file mode

Description

bool chmod ( string filename, int mode )

Attempts to change the mode of the file specified by filename to that given in mode.

Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

Returns TRUE on success or FALSE on failure.

Note: The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

See also chown() and chgrp().

chown

(PHP 3, PHP 4, PHP 5)

chown -- Changes file owner

Description

bool chown ( string filename, mixed user )

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parameters

filename

Path to the file.

user

A user name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

See Also

chmod()

clearstatcache

(PHP 3, PHP 4, PHP 5)

clearstatcache -- Clears file status cache

Description

void clearstatcache ( void )

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file.

Note: This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

copy

(PHP 3, PHP 4, PHP 5)

copy -- Copies file

Description

bool copy ( string source, string dest )

Makes a copy of the file source to dest.

If you wish to move a file, use the rename() function.

Parameters

source

Path to the source file.

dest

The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Warning

If the destination file already exists, it will be overwritten.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
4.3.0 Both source and dest may now be URLs if the "fopen wrappers" have been enabled. See fopen() for more details.

Examples

Example 1. copy() example

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

Notes

Note: Windows compatibility: If you copy a file with no size, copy() will return FALSE, but the file will be correctly copied.

See Also

move_uploaded_file()
rename()
The section of the manual about handling file uploads

delete

(no version information, might be only in CVS)

delete -- See unlink() or unset()

Description

void delete ( void )

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

Return Values

No value is returned.

See Also

unlink() to delete files
unset() to delete variables

dirname

(PHP 3, PHP 4, PHP 5)

dirname -- Returns directory name component of path

Description

string dirname ( string path )

Given a string containing a path to a file, this function will return the name of the directory.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Example 1. dirname() example

<?php
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
?>

Note: In PHP 4.0.3, dirname() was fixed to be POSIX-compliant. Essentially, this means that if there are no slashes in path , a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed. Note that this means that you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

dirname() has changed its behaviour in PHP 4.3.0. Check the following examples:

<?php

//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/'); // returns 'c:'

?>

dirname() has been binary safe since PHP 5.0.0

See also basename(), pathinfo(), and realpath().

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space -- Returns available space in directory

Description

float disk_free_space ( string directory )

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Return Values

Returns the number of available bytes as a float.

Examples

Example 1. disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
disk_free_space("C:");
disk_free_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space -- Returns the total size of a directory

Description

float disk_total_space ( string directory )

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Return Values

Returns the total number of bytes as a float.

Examples

Example 1. disk_total_space() example

<?php
// $df contains the total number of bytes available on "/"
$df = disk_total_space("/");

// On Windows:
disk_total_space("C:");
disk_total_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

diskfreespace

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

diskfreespace -- Alias of disk_free_space()

Description

This function is an alias of: disk_free_space().

fclose

(PHP 3, PHP 4, PHP 5)

fclose -- Closes an open file pointer

Description

bool fclose ( resource handle )

The file pointed to by handle is closed.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A simple fclose() example

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

feof

(PHP 3, PHP 4, PHP 5)

feof -- Tests for end-of-file on a file pointer

Description

bool feof ( resource handle )

Tests for end-of-file on a file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Notes

Warning

If a connection opened by fsockopen() wasn't closed by the server, feof() will wait until a timeout has been reached to return TRUE. The default timeout value is 60 seconds. You may use stream_set_timeout() to change this value.

Warning

If passed file pointer is not valid you may get an infinite loop, because EOF fails to return TRUE.

Example 1. feof() example with an invalid file pointer

<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush -- Flushes the output to a file

Description

bool fflush ( resource handle )

This function forces a write of all buffered output to the resource pointed to by the file handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE on success or FALSE on failure.

fgetc

(PHP 3, PHP 4, PHP 5)

fgetc -- Gets character from file pointer

Description

string fgetc ( resource handle )

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Example 1. A fgetc() example

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Note: This function is binary-safe.

See also fread(), fopen(), popen(), fsockopen(), and fgets().

fgetcsv

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

fgetcsv -- Gets line from file pointer and parse for CSV fields

Description

array fgetcsv ( resource handle [, int length [, string delimiter [, string enclosure]]] )

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Parameters

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length

Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower.

delimiter

Set the field delimiter (one character only). Defaults as a comma.

enclosure

Set the field enclosure character (one character only). Defaults as a double quotation mark.

Return Values

Returns an indexed array containing the fields read.

Note: A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

fgetcsv() returns FALSE on error, including end of file.

ChangeLog

VersionDescription
4.3.5 fgetcsv() is now binary safe
4.3.0 The enclosure parameter was added

Examples

Example 1. Read and print the entire contents of a CSV file

<?php
$row = 1;
$handle = fopen("test.csv", "r");
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);
?>

Notes

Note: Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

fgets

(PHP 3, PHP 4, PHP 5)

fgets -- Gets line from file pointer

Description

string fgets ( resource handle [, int length] )

Gets a line from file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Note: Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

ChangeLog

VersionDescription
4.3.0 fgets() is now binary safe
4.2.0 The length parameter became optional

Examples

Example 1. Reading a file line by line

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

Notes

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

Note: People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

fgetss

(PHP 3, PHP 4, PHP 5)

fgetss -- Gets line from file pointer and strip HTML tags

Description

string fgetss ( resource handle [, int length [, string allowable_tags]] )

Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.

You can use the optional third parameter to specify tags which should not be stripped.

Note: allowable_tags was added in PHP 3.0.13, PHP 4.0.0.

Parameter length is optional since PHP 5.

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

See also fgets(), fopen(), fsockopen(), popen(), and strip_tags().

file_exists

(PHP 3, PHP 4, PHP 5)

file_exists -- Checks whether a file or directory exists

Description

bool file_exists ( string filename )

Checks whether a file or directory exists.

Parameters

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Warning

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Note: The check is done using the real UID/GID instead of the effective one.

Examples

Example 1. Testing whether a file exists

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents -- Reads entire file into a string

Description

string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] )

Identical to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

Note: context parameter can be skipped by NULL.

ChangeLog

VersionDescription
5.0.0 Added the context support.
5.1.0 Added the offset and maxlen parameters.

Notes

Note: This function is binary-safe.

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix O for a list of supported URL protocols.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

file_put_contents

(PHP 5)

file_put_contents -- Write a string to a file

Description

int file_put_contents ( string filename, mixed data [, int flags [, resource context]] )

Identical to calling fopen(), fwrite(), and fclose() successively.

You can also specify the data parameter as an array (not multi-dimension arrays). This is equivalent to file_put_contents($filename, implode('', $array)).

Parameters

filename

The file name where to write the data

data

The data to write. Can be either a string, an array or a stream resource (explained above).

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

flags

flags can take FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (acquire an exclusive lock), however the FILE_USE_INCLUDE_PATH option should be used with caution. As of PHP 6, it can also take one of FILE_TEXT or FILE_BINARY to specify how newlines should be handled when outputting the file. See fopen()'s "t" and "b" modes for more information.

context

A context resource

Return Values

The function returns the amount of bytes that were written to the file, or FALSE on failure.

ChangeLog

VersionDescription
5.0.0 Added context support
5.1.0 Added support for LOCK_EX and the ability to pass a stream resource to the data parameter
6.0.0 Added support for FILE_TEXT and FILE_BINARY

Notes

Note: This function is binary-safe.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix O for a list of supported URL protocols.

file

(PHP 3, PHP 4, PHP 5)

file -- Reads entire file into an array

Description

array file ( string filename [, int flags [, resource context]] )

Reads an entire file into an array.

Note: You can use file_get_contents() to return the contents of a file as a string.

Parameters

filename

Path to the file.

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix O for a list of supported URL protocols.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH

Search for the file in the include_path.

FILE_IGNORE_NEW_LINES

Do not add newline at the end of each array element

FILE_SKIP_EMPTY_LINES

Skip empty lines

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

ChangeLog

VersionDescription
5.0.0 The context parameter was added
5.0.0 Prior to PHP 5.0.0 the flags parameter only covered include_path and was enabled with 1
4.3.0 file() became binary safe

Examples

Example 1. file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

fileatime

(PHP 3, PHP 4, PHP 5)

fileatime -- Gets last access time of file

Description

int fileatime ( string filename )

Returns the time the file was last accessed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories. Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

Example 1. fileatime() example

<?php

// outputs e.g.  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));
}

?>

See also filemtime(), fileinode(), and date().

filectime

(PHP 3, PHP 4, PHP 5)

filectime -- Gets inode change time of file

Description

int filectime ( string filename )

Gets the inode change time of a file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Examples

Example 1. A filectime() example

<?php

// outputs e.g.  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));
}

?>

Notes

Note: Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note: Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See Also

filemtime()

filegroup

(PHP 3, PHP 4, PHP 5)

filegroup -- Gets file group

Description

int filegroup ( string filename )

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Parameters

filename

Path to the file.

Return Values

Returns the group ID of the file, or FALSE in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

fileinode

(PHP 3, PHP 4, PHP 5)

fileinode -- Gets file inode

Description

int fileinode ( string filename )

Gets the file inode.

Parameters

filename

Path to the file.

Return Values

Returns the inode number of the file, or FALSE in case of an error.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See Also

stat()

filemtime

(PHP 3, PHP 4, PHP 5)

filemtime -- Gets file modification time

Description

int filemtime ( string filename )

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last modified, or FALSE in case of an error. The time is returned as a Unix timestamp, which is suitable for the date() function.

Examples

Example 1. filemtime() example

<?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));
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

fileowner

(PHP 3, PHP 4, PHP 5)

fileowner -- Gets file owner

Description

int fileowner ( string filename )

Gets the file owner.

Parameters

filename

Path to the file.

Return Values

Returns the user ID of the owner of the file, or FALSE in case of an error. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See Also

stat()

fileperms

(PHP 3, PHP 4, PHP 5)

fileperms -- Gets file permissions

Description

int fileperms ( string filename )

Gets permissions for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the permissions on the file, or FALSE in case of an error.

Examples

Example 1. Display permissions as an octal value

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

The above example will output:

1777
0644

Example 2. Display full permissions

<?php
$perms = fileperms('/etc/passwd');

if (($perms & 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}

// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

The above example will output:

-rw-r--r--

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

filesize

(PHP 3, PHP 4, PHP 5)

filesize -- Gets file size

Description

int filesize ( string filename )

Gets the size for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, filesize() may return unexpected results for files which are larger than 2GB. For files between 2GB and 4GB in size this can usually be overcome by using sprintf("%u", filesize($file)).

Examples

Example 1. filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See Also

file_exists()

filetype

(PHP 3, PHP 4, PHP 5)

filetype -- Gets file type

Description

string filetype ( string filename )

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.

Returns FALSE if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

Example 1. filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

See also is_dir(), is_file(), is_link(), file_exists(), stat(), and mime_content_type().

flock

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

flock -- Portable advisory file locking

Description

bool flock ( resource handle, int operation [, int &wouldblock] )

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work).

Note: flock() is mandatory under Windows.

flock() operates on handle which must be an open file pointer. operation is one of the following values:

  • To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).

  • To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).

  • To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).

  • If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition). The lock is released also by fclose() (which is also called automatically when script finished).

Returns TRUE on success or FALSE on failure.

Example 1. flock() example

<?php

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't lock the file !";
}

fclose($fp);

?>

Note: Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

Warning

flock() will not work on NFS and many other networked file systems. Check your operating system documentation for more details.

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this environments (this is especially true for Windows 98 users).

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatch -- Match filename against a pattern

Description

bool fnmatch ( string pattern, string string [, int flags] )

fnmatch() checks if the passed string would match the given shell wildcard pattern.

This is especially useful for filenames, but may also be used on regular strings. The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of ereg() or preg_match() for frontend search expression input may be way more convenient for non-programming users.

Example 1. Checking a color name against a shell wildcard pattern.

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

Warning

For now this function is not available on Windows or other non-POSIX compliant systems.

See also glob(), ereg(), preg_match() and the Unix manpage on fnmatch(3) for flag names (as long as they are not documented here ).

fopen

(PHP 3, PHP 4, PHP 5)

fopen -- Opens file or URL

Description

resource fopen ( string filename, string mode [, bool use_include_path [, resource context]] )

fopen() binds a named resource, specified by filename, to a stream.

Parameters

filename

If filename is of the form "scheme://...", it is assumed to be a URL and 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.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode, or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note: The list of supported protocols can be found in Appendix O. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

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:\\data\\info.txt", "r");
?>

mode

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

Table 1. A list of possible modes for fopen() using mode

modeDescription
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

Note: Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.

If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note: For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

Note: Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns a file pointer resource on success, or FALSE on error.

Errors/Exceptions

If the open fails, the function an error of level E_WARNING is generated. You may use @ to suppress this warning.

ChangeLog

VersionDescription
4.3.2 As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned below
4.3.2 The 'x' and 'x+' option was added

Examples

Example 1. fopen() examples

<?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");
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

fpassthru

(PHP 3, PHP 4, PHP 5)

fpassthru -- Output all remaining data on a file pointer

Description

int fpassthru ( resource handle )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

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 may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

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 readfile(), which saves you the fopen() call.

Note: When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().

You are encouraged to use the b flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.

Example 1. Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

See also readfile(), fopen(), popen(), and fsockopen()

fputcsv

(PHP 5 >= 5.1.0RC1)

fputcsv -- Format line as CSV and write to file pointer

Description

int fputcsv ( resource handle [, array fields [, string delimiter [, string enclosure]]] )

fputcsv() formats a line (passed as a fields array) as CSV and write it to the specified file handle. Returns the length of the written string, or FALSE on failure.

The optional delimiter parameter sets the field delimiter (one character only). Defaults as a comma: ,.

The optional enclosure parameter sets the field enclosure (one character only) and defaults to a double quotation mark: ".

Example 1. fputcsv() example

<?php

$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}

fclose($fp);
?>

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

See also fgetcsv().

fputs

(PHP 3, PHP 4, PHP 5)

fputs -- Alias of fwrite()

Description

This function is an alias of: fwrite().

fread

(PHP 3, PHP 4, PHP 5)

fread -- Binary-safe file read

Description

string fread ( resource handle, int length )

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops when up to length bytes have been read, EOF (end of file) is reached, (for network streams) when a packet becomes available, or (after opening userspace stream) when 8192 bytes have been read whichever comes first.

Returns the read string or FALSE in case of error.

<?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);
?>

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$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: If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file(), and fpassthru().

fscanf

(PHP 4 >= 4.0.1, PHP 5)

fscanf -- Parses input from a file according to a format

Description

mixed fscanf ( resource handle, string format [, mixed &...] )

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf(). If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream.

Example 1. fscanf() Example

<?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. Contents of users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

Note: Prior to PHP 4.3.0, the maximum number of characters read from the file was 512 (or up to the first \n, whichever came first). As of PHP 4.3.0 arbitrarily long lines will be read and scanned.

See also fread(), fgets(), fgetss(), sscanf(), printf(), and sprintf().

fseek

(PHP 3, PHP 4, PHP 5)

fseek -- Seeks on a file pointer

Description

int fseek ( resource handle, int offset [, int whence] )

Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence, whose values are defined as follows:

SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Set position to current location plus offset.
SEEK_END - Set position to end-of-file plus offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.)

If whence is not specified, it is assumed to be SEEK_SET.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Example 1. fseek() example

<?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);

?>

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats. fseek() gives also undefined results for append-only streams (opened with "a" flag).

Note: The whence argument was added after PHP 4.0.0.

Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

See also ftell() and rewind().

fstat

(PHP 4, PHP 5)

fstat -- Gets information about a file using an open file pointer

Description

array fstat ( resource handle )

Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Example 1. fstat() example

<?php

// open a file
$fp = fopen("/etc/passwd", "r");

// gather statistics
$fstat = fstat($fp);

// close the file
fclose($fp);

// print only the associative part
print_r(array_slice($fstat, 13));

?>

The above example will output something similar to:

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: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

ftell

(PHP 3, PHP 4, PHP 5)

ftell -- Tells file pointer read/write position

Description

int ftell ( resource handle )

Tells the file pointer read/write position.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Return Values

Returns the position of the file pointer referenced by handle; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Examples

Example 1. ftell() example

<?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);

?>

ftruncate

(PHP 4, PHP 5)

ftruncate -- Truncates a file to a given length

Description

bool ftruncate ( resource handle, int size )

Takes the filepointer, handle, and truncates the file to length, size. Returns TRUE on success or FALSE on failure.

Note: The file pointer is changed only in append mode. In write mode, additional fseek() call is needed.

Note: Prior to PHP 4.3.3, ftruncate() returns an integer value of 1 on success, instead of boolean TRUE.

See also fopen() and fseek().

fwrite

(PHP 3, PHP 4, PHP 5)

fwrite -- Binary-safe file write

Description

int fwrite ( resource handle, string string [, int length] )

fwrite() writes the contents of string to the file stream pointed to by handle. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

fwrite() returns the number of bytes written, or FALSE on error.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Note: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Note: If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Example 1. A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

See also fread(), fopen(), fsockopen(), popen(), and file_put_contents().

glob

(PHP 4 >= 4.3.0, PHP 5)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Parameters

pattern

The pattern. No tilde expansion or parameter substitution is done.

flags

Valid flags:

  • GLOB_MARK - Adds a slash to each item returned

  • GLOB_NOSORT - Return files as they appear in the directory (no sorting)

  • GLOB_NOCHECK - Return the search pattern if no files matching it were found

  • GLOB_NOESCAPE - Backslashes do not quote metacharacters

  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

  • GLOB_ONLYDIR - Return only directory entries which match the pattern

  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

ChangeLog

VersionDescription
5.1.0 GLOB_ERR was added
4.3.3 GLOB_ONLYDIR bacame available on Windows and other systems not using the GNU C library

Examples

Example 1. Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

The above example will output something similar to:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: This function isn't available on some systems (e.g. old Sun OS).

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

is_dir

(PHP 3, PHP 4, PHP 5)

is_dir -- Tells whether the filename is a directory

Description

bool is_dir ( string filename )

Tells whether the given filename is a directory.

Parameters

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory.

Return Values

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Examples

Example 1. is_dir() example

<?php
var_dump(is_dir('a_file.txt')) . "\n";
var_dump(is_dir('bogus_dir/abc')) . "\n";

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

bool(false)
bool(false)
bool(true)

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

is_executable

(PHP 3, PHP 4, PHP 5)

is_executable -- Tells whether the filename is executable

Description

bool is_executable ( string filename )

Tells whether the filename is executable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is executable, or FALSE on error.

ChangeLog

VersionDescription
5.0.0 is_executable() became available with Windows

Examples

Example 1. is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

is_file

(PHP 3, PHP 4, PHP 5)

is_file -- Tells whether the filename is a regular file

Description

bool is_file ( string filename )

Tells whether the given file is a regular file.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Examples

Example 1. is_file() example

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

The above example will output:

bool(true)
bool(false)

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

is_link

(PHP 3, PHP 4, PHP 5)

is_link -- Tells whether the filename is a symbolic link

Description

bool is_link ( string filename )

Tells whether the given file is a symbolic link.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

is_readable

(PHP 3, PHP 4, PHP 5)

is_readable -- Tells whether the filename is readable

Description

bool is_readable ( string filename )

Tells whether the filename is readable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Examples

Example 1. is_readable() example

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

Note: The check is done using the real UID/GID instead of the effective one.

is_uploaded_file

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file -- Tells whether the file was uploaded via HTTP POST

Description

bool is_uploaded_file ( string filename )

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the clients machine $_FILES['userfile']['name'] does not work.

Example 1. is_uploaded_file() example

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo "Displaying contents\n";
   readfile($_FILES['userfile']['tmp_name']);
} else {
   echo "Possible file upload attack: ";
   echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}

?>

is_uploaded_file() is available only in versions of PHP 3 after PHP 3.0.16, and in versions of PHP 4 after 4.0.2. If you are stuck using an earlier version, you can use the following function to help protect yourself:

Note: The following example will not work in versions of PHP 4 after 4.0.2. It depends on internal functionality of PHP which changed after that version.

Example 2. is_uploaded_file() example for PHP 4 < 4.0.3

<?php
/* Userland test for uploaded file. */
function is_uploaded_file_4_0_2($filename)
{
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* This is how to use it, since you also don't have
 * move_uploaded_file() in these older versions: */
if (is_uploaded_file_4_0_2($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

See also move_uploaded_file(), and the section Handling file uploads for a simple usage example.

is_writable

(PHP 4, PHP 5)

is_writable -- Tells whether the filename is writable

Description

bool is_writable ( string filename )

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writeable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Example 1. is_writable() example

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See also is_readable(), file_exists(), and fwrite().

is_writeable

(PHP 3, PHP 4, PHP 5)

is_writeable -- Alias of is_writable()

Description

This function is an alias of: is_writable().

lchgrp

(no version information, might be only in CVS)

lchgrp -- Changes group ownership of symlink

Description

bool lchgrp ( string filename, mixed group )

Attempts to change the group of the symlink filename to group.

Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.

Parameters

filename

Path to the symlink.

group

The group specified by name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

lchown

(no version information, might be only in CVS)

lchown -- Changes user ownership of symlink

Description

bool lchown ( string filename, mixed user )

Attempts to change the owner of the symlink filename to user user.

Only the superuser may change the owner of a symlink.

Parameters

filename

Path to the file.

user

User name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.

link

(PHP 3, PHP 4, PHP 5)

link -- Create a hard link

Description

bool link ( string target, string link )

link() creates a hard link.

Parameters

target

Target of the link.

link

The link name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Note: This function is not implemented on Windows platforms.

linkinfo

(PHP 3, PHP 4, PHP 5)

linkinfo -- Gets information about a link

Description

int linkinfo ( string path )

Gets information about a link.

This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h).

Parameters

path

Path to the link.

Return Values

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns 0 or FALSE in case of error.

Examples

Example 1. linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

Notes

Note: This function is not implemented on Windows platforms.

lstat

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

lstat -- Gives information about a file or symbolic link

Description

array lstat ( string filename )

Gathers the statistics of the file or symbolic link named by filename.

Parameters

filename

Path to a file or a symbolic link.

Return Values

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

See Also

stat()

mkdir

(PHP 3, PHP 4, PHP 5)

mkdir -- Makes directory

Description

bool mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )

Attempts to create the directory specified by pathname.

Parameters

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Note: mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
5.0.0 The recursive parameter was added
5.0.0 As of PHP 5.0.0 mkdir() can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support mkdir()
4.2.0 The mode parameter became optional.

Examples

Example 1. mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

See Also

rmdir()

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- Moves an uploaded file to a new location

Description

bool move_uploaded_file ( string filename, string destination )

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

Note: move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Warning

If the destination file already exists, it will be overwritten.

See also is_uploaded_file(), and the section Handling file uploads for a simple usage example.

parse_ini_file

(PHP 4, PHP 5)

parse_ini_file -- Parse a configuration file

Description

array parse_ini_file ( string filename [, bool process_sections] )

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array. By setting the last process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

Note: This function has nothing to do with the php.ini file. It is already processed, the time you run your script. This function can be used to read in your own application's configuration files.

Note: If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Note: Since PHP 4.2.1 this function is also affected by safe mode and open_basedir.

Note: As of PHP 5.0.0 this function also handles new lines in values.

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, and false. Values null, no and false results in "", yes and true results in "1". Characters {}|&~![()" must not be used anywhere in the key and have a special meaning in the value.

The structure of the ini file is similar to that of the php.ini's.

Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example:

Example 1. Contents of 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"

Example 2. parse_ini_file() example

<?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);

?>

Would produce:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] = Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

Keys and section names consisting from numbers are evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo -- Returns information about a file path

Description

mixed pathinfo ( string path [, int options] )

pathinfo() returns an associative array containing information about path. The following array elements are returned: dirname, basename and extension if any.

You can specify which elements are returned with optional parameter options. It composes from PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION and PATHINFO_FILENAME (available since PHP 5.2.0). It defaults to return all elements. This function returns string if not all elements are requested.

Example 1. pathinfo() Example

<?php
$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

Would produce:

/www/htdocs
index.html
html
index

Note: For information on retrieving the current path info, read the section on predefined reserved variables.

See also dirname(), basename(), parse_url() and realpath().

pclose

(PHP 3, PHP 4, PHP 5)

pclose -- Closes process file pointer

Description

int pclose ( resource handle )

Closes a file pointer to a pipe opened by popen().

Parameters

handle

The file pointer must be valid, and must have been returned by a successful call to popen().

Return Values

Returns the termination status of the process that was run.

See Also

popen()

popen

(PHP 3, PHP 4, PHP 5)

popen -- Opens process file pointer

Description

resource popen ( string command, string mode )

Opens a pipe to a process executed by forking the command given by command.

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite().

If an error occurs, returns FALSE.

Note: If you're looking for bi-directional support (two-way), use proc_open().

Example 1. popen() example

<?php
$handle = popen("/bin/ls", "r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/spooge 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

Note: When safe mode is enabled, you can only execute executables within the safe_mode_exec_dir. For practical reasons it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See also pclose(), fopen(), and proc_open().

readfile

(PHP 3, PHP 4, PHP 5)

readfile -- Outputs a file

Description

int readfile ( string filename [, bool use_include_path [, resource context]] )

Reads a file and writes it to the output buffer.

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix O for a list of supported URL protocols.

You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

See also fpassthru(), file(), fopen(), include(), require(), virtual(), file_get_contents(), and Appendix O.

readlink

(PHP 3, PHP 4, PHP 5)

readlink -- Returns the target of a symbolic link

Description

string readlink ( string path )

readlink() does the same as the readlink C function.

Parameters

path

The symbolic link path.

Return Values

Returns the contents of the symbolic link path or FALSE on error.

Examples

Example 1. readlink() example

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

Notes

Note: This function is not implemented on Windows platforms.

realpath

(PHP 4, PHP 5)

realpath -- Returns canonicalized absolute pathname

Description

string realpath ( string path )

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exist. On BSD systems realpath() doesn't fail if only the last path component doesn't exist, while other systems will return FALSE.

Example 1. realpath() example

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?>

The above example will output:

/etc/passwd

See also basename(), dirname(), and pathinfo().

rename

(PHP 3, PHP 4, PHP 5)

rename -- Renames a file or directory

Description

bool rename ( string oldname, string newname [, resource context] )

Attempts to rename oldname to newname.

Parameters

oldname

Note: The old name. The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
5.0.0 rename() can now also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support rename().
4.3.3 rename() is now able to rename files across partitions on *nix based systems.

Examples

Example 1. Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

rewind

(PHP 3, PHP 4, PHP 5)

rewind -- Rewind the position of a file pointer

Description

bool rewind ( resource handle )

Sets the file position indicator for handle to the beginning of the file stream.

Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

fseek()
ftell()

rmdir

(PHP 3, PHP 4, PHP 5)

rmdir -- Removes directory

Description

bool rmdir ( string dirname [, resource context] )

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
5.0.0 As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support rmdir().

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

See Also

mkdir()
unlink()

set_file_buffer

(PHP 3 >= 3.0.8, PHP 4 >= 4.0.1, PHP 5)

set_file_buffer -- Alias of stream_set_write_buffer()

Description

This function is an alias of: stream_set_write_buffer().

stat

(PHP 3, PHP 4, PHP 5)

stat -- Gives information about a file

Description

array stat ( string filename )

Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink.

lstat() is identical to stat() except it would instead be based off the symlinks status.

Parameters

filename

Path to the file.

Return Values

Table 1. stat() and fstat() result format

NumericAssociative (since PHP 4.0.6)Description
0devdevice number
1inoinode number
2modeinode protection mode
3nlinknumber of links
4uiduserid of owner
5gidgroupid of owner
6rdevdevice type, if inode device *
7sizesize in bytes
8atimetime of last access (Unix timestamp)
9mtimetime of last modification (Unix timestamp)
10ctimetime of last inode change (Unix timestamp)
11blksizeblocksize of filesystem IO *
12blocksnumber of blocks allocated
* Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

In case of error, stat() returns FALSE.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

ChangeLog

VersionDescription
4.0.6 In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support stat() family of functionality.

symlink

(PHP 3, PHP 4, PHP 5)

symlink -- Creates a symbolic link

Description

bool symlink ( string target, string link )

symlink() creates a symbolic link to the existing target with the specified name link.

Parameters

target

Target of the link.

link

The link name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.

See Also

link() to create hard links
readlink() along with linkinfo()

tempnam

(PHP 3, PHP 4, PHP 5)

tempnam -- Create file with unique file name

Description

string tempnam ( string dir, string prefix )

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.

Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default.

Returns the new temporary filename, or FALSE on failure.

Example 1. tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Note: This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically.

See also tmpfile(), sys_get_temp_dir() and unlink().

tmpfile

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

tmpfile -- Creates a temporary file

Description

resource tmpfile ( void )

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

The file is automatically removed when closed (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file, or FALSE on failure.

Examples

Example 1. tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

The above example will output:

writing to tempfile

touch

(PHP 3, PHP 4, PHP 5)

touch -- Sets access and modification time of file

Description

bool touch ( string filename [, int time [, int atime]] )

Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. If time is not supplied, the current system time is used. If the third parameter, is present, the access time of the given filename is set to the value of atime. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created. Returns TRUE on success or FALSE on failure.

Warning

It is not currently possible to change the modification time of a directory with this function under Windows.

Example 1. touch() example

<?php
if (touch($FileName)) {
    echo "$FileName modification time has been changed to present time";
} else {
    echo "Sorry, could not change modification time of $FileName";
}
?>

umask

(PHP 3, PHP 4, PHP 5)

umask -- Changes the current umask

Description

int umask ( [int mask] )

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

umask() without arguments simply returns the current umask.

Note: Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.

Example 1. umask() example

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occured while changing back the umask');
}
?>

unlink

(PHP 3, PHP 4, PHP 5)

unlink -- Deletes a file

Description

bool unlink ( string filename [, resource context] )

Deletes filename. Similar to the Unix C unlink() function.

Parameters

filename

Path to the file.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLX, Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

VersionDescription
5.0.0 As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Appendix O for a listing of which wrappers support unlink().

See Also

rmdir() for removing directories

XLI. Filter Functions

Introduction

This extension serves for validating and filtering data coming usually from some insecure source such as user input.

The following filters currently exist, be sure to read the Filter Constants section for information that describes the behavior of each constant:

Table 1. Existing filters

IDNameOptionsFlagsDescription
FILTER_VALIDATE_INT"int" min_range, max_range FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX Validates value as integer, optionally from the specified range.
FILTER_VALIDATE_BOOLEAN"boolean"   Returns TRUE for "1", "true", "on" and "yes", FALSE for "0", "false", "off", "no", and "", NULL otherwise.
FILTER_VALIDATE_FLOAT"float" decimal FILTER_FLAG_ALLOW_THOUSAND Validates value as float.
FILTER_VALIDATE_REGEXP"validate_regexp" regexp   Validates value against regexp, a Perl-compatible regular expression.
FILTER_VALIDATE_URL"validate_url"  FILTER_FLAG_SCHEME_REQUIRED, FILTER_FLAG_HOST_REQUIRED, FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED Validates value as URL, optionally with required components.
FILTER_VALIDATE_EMAIL"validate_email"  Validates value as e-mail.
FILTER_VALIDATE_IP"validate_ip"  FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE Validates value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.
FILTER_SANITIZE_STRING"string"  FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP Strip tags, optionally strip or encode special characters.
FILTER_SANITIZE_STRIPPED"stripped"  Alias of "string" filter.
FILTER_SANITIZE_ENCODED"encoded"  FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH URL-encode string, optionally strip or encode special characters.
FILTER_SANITIZE_SPECIAL_CHARS"special_chars"  FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_UNSAFE_RAW"unsafe_raw"  FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP Do nothing, optionally strip or encode special characters.
FILTER_SANITIZE_EMAIL"email"   Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
FILTER_SANITIZE_URL"url"   Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_SANITIZE_NUMBER_INT"number_int"   Remove all characters except digits and +-.
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_MAGIC_QUOTES"magic_quotes"  Apply addslashes().
FILTER_CALLBACK"callback"callback function or method Call user-defined function to filter data.


Requirements

No external libraries are needed to build this extension.


Installation

A short installation note: just type

$ pecl install filter
in your console.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 2. Filter Configuration Options

NameDefaultChangeableChangelog
filter.defaultunsafe_rawPHP_INI_PERDIR 
filter.default_flags PHP_INI_PERDIR 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

filter.default string

Filter all $_GET, $_POST, $_COOKIE and $_REQUEST data by this filter. Original data can be accessed through filter_input().

Accepts the name of the filter you like to use by default. See the existing filter list for the list of the filter names.

filter.default_flags integer

Default flags


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

INPUT_POST (integer)

POST variables.

INPUT_GET (integer)

GET variables.

INPUT_COOKIE (integer)

COOKIE variables.

INPUT_ENV (integer)

ENV variables.

INPUT_SERVER (integer)

SERVER variables.

INPUT_SESSION (integer)

SESSION variables. (not implemented yet)

INPUT_REQUEST (integer)

REQUEST variables. (not implemented yet)

FILTER_FLAG_NONE (integer)

No flags.

FILTER_REQUIRE_SCALAR (integer)

Flag used to require scalar as input

FILTER_REQUIRE_ARRAY (integer)

Require an array as input.

FILTER_FORCE_ARRAY (integer)

Always returns an array.

FILTER_NULL_ON_FAILURE (integer)

Use NULL instead of FALSE on failure.

FILTER_VALIDATE_INT (integer)

ID of "int" filter.

FILTER_VALIDATE_BOOLEAN (integer)

ID of "boolean" filter.

FILTER_VALIDATE_FLOAT (integer)

ID of "float" filter.

FILTER_VALIDATE_REGEXP (integer)

ID of "validate_regexp" filter.

FILTER_VALIDATE_URL (integer)

ID of "validate_url" filter.

FILTER_VALIDATE_EMAIL (integer)

ID of "validate_email" filter.

FILTER_VALIDATE_IP (integer)

ID of "validate_ip" filter.

FILTER_DEFAULT (integer)

ID of default ("string") filter.

FILTER_UNSAFE_RAW (integer)

ID of "unsafe_raw" filter.

FILTER_SANITIZE_STRING (integer)

ID of "string" filter.

FILTER_SANITIZE_STRIPPED (integer)

ID of "stripped" filter.

FILTER_SANITIZE_ENCODED (integer)

ID of "encoded" filter.

FILTER_SANITIZE_SPECIAL_CHARS (integer)

ID of "special_chars" filter.

FILTER_SANITIZE_EMAIL (integer)

ID of "email" filter.

FILTER_SANITIZE_URL (integer)

ID of "url" filter.

FILTER_SANITIZE_NUMBER_INT (integer)

ID of "number_int" filter.

FILTER_SANITIZE_NUMBER_FLOAT (integer)

ID of "number_float" filter.

FILTER_SANITIZE_MAGIC_QUOTES (integer)

ID of "magic_quotes" filter.

FILTER_CALLBACK (integer)

ID of "callback" filter.

FILTER_FLAG_ALLOW_OCTAL (integer)

Allow octal notation (0[0-7]+) in "int" filter.

FILTER_FLAG_ALLOW_HEX (integer)

Allow hex notation (0x[0-9a-fA-F]+) in "int" filter.

FILTER_FLAG_STRIP_LOW (integer)

Strip characters with ASCII value less than 32.

FILTER_FLAG_STRIP_HIGH (integer)

Strip characters with ASCII value greater than 127.

FILTER_FLAG_ENCODE_LOW (integer)

Encode characters with ASCII value less than 32.

FILTER_FLAG_ENCODE_HIGH (integer)

Encode characters with ASCII value greater than 127.

FILTER_FLAG_ENCODE_AMP (integer)

Encode &.

FILTER_FLAG_NO_ENCODE_QUOTES (integer)

Don't encode ' and ".

FILTER_FLAG_EMPTY_STRING_NULL (integer)

(No use for now.)

FILTER_FLAG_ALLOW_FRACTION (integer)

Allow fractional part in "number_float" filter.

FILTER_FLAG_ALLOW_THOUSAND (integer)

Allow thousand separator (,) in "number_float" filter.

FILTER_FLAG_ALLOW_SCIENTIFIC (integer)

Allow scientific notation (e, E) in "number_float" filter.

FILTER_FLAG_SCHEME_REQUIRED (integer)

Require scheme in "validate_url" filter.

FILTER_FLAG_HOST_REQUIRED (integer)

Require host in "validate_url" filter.

FILTER_FLAG_PATH_REQUIRED (integer)

Require path in "validate_url" filter.

FILTER_FLAG_QUERY_REQUIRED (integer)

Require query in "validate_url" filter.

FILTER_FLAG_IPV4 (integer)

Allow only IPv4 address in "validate_ip" filter.

FILTER_FLAG_IPV6 (integer)

Allow only IPv6 address in "validate_ip" filter.

FILTER_FLAG_NO_RES_RANGE (integer)

Deny reserved addresses in "validate_ip" filter.

FILTER_FLAG_NO_PRIV_RANGE (integer)

Deny private addresses in "validate_ip" filter.

Table of Contents
filter_has_var -- Checks if variable of specified type exists
filter_id -- Returns the filter ID belonging to a named filter
filter_input_array -- Gets multiple variables from outside PHP and optionally filters them
filter_input -- Gets variable from outside PHP and optionally filters it
filter_list -- Returns a list of all supported filters
filter_var_array -- Gets multiple variables and optionally filters them
filter_var -- Filters a variable with a specified filter

filter_has_var

(no version information, might be only in CVS)

filter_has_var -- Checks if variable of specified type exists

Description

bool filter_has_var ( int type, string variable_name )

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV.

variable_name

Name of a variable to check.

Return Values

Returns TRUE on success or FALSE on failure.

filter_id

(no version information, might be only in CVS)

filter_id -- Returns the filter ID belonging to a named filter

Description

int filter_id ( string filtername )

Parameters

filtername

Name of a filter to get.

Return Values

ID of a filter on success or NULL if filter doesn't exist.

See Also

filter_list()

filter_input_array

(no version information, might be only in CVS)

filter_input_array -- Gets multiple variables from outside PHP and optionally filters them

Description

mixed filter_input_array ( int type [, mixed definition] )

This function is useful for retrieving many values without repetitively calling filter_input().

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, INPUT_SESSION, or INPUT_REQUEST.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Return Values

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Examples

Example 1. A filter_input_array() example

<?php
error_reporting(E_ALL | E_STRICT);
/* data actually came from POST
$_POST = 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_FLAG_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_FLAG_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FLAG_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

filter_input

(no version information, might be only in CVS)

filter_input -- Gets variable from outside PHP and optionally filters it

Description

mixed filter_input ( int type, string variable_name [, int filter [, mixed options]] )

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, INPUT_SESSION (not implemented yet) and INPUT_REQUEST (not implemented yet).

variable_name

Name of a variable to get.

filter

Filter to apply. Defaults to FILTER_DEFAULT.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Return Values

Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Examples

Example 1. A filter_input() example

<?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>";
?>

The above example will output something similar to:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

filter_list

(no version information, might be only in CVS)

filter_list -- Returns a list of all supported filters

Description

array filter_list ( void )

Return Values

Returns an array of names of all supported filters, empty array if there are no such filters. Indexes of this array are not filter IDs, they can be obtained with filter_id() from a name instead.

Examples

Example 1. A filter_list() example

<?php
print_r(filter_list());
?>

The above example will output something similar to:

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
)

filter_var_array

(no version information, might be only in CVS)

filter_var_array -- Gets multiple variables and optionally filters them

Description

mixed filter_var_array ( array data [, mixed definition] )

This function is useful for retrieving many values without repetitively calling filter_var().

Parameters

data

An array with string keys containing the data to filter.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Return Values

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set.

Examples

Example 1. A filter_var_array() example

<?php
error_reporting(E_ALL | E_STRICT);
$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";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

filter_var

(no version information, might be only in CVS)

filter_var -- Filters a variable with a specified filter

Description

mixed filter_var ( mixed variable [, int filter [, mixed options]] )

Parameters

variable

Value to filter, arrays are filtered recursively.

filter

ID of a filter to use. Defaults to FILTER_SANITIZE_STRING.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed.

Return Values

Returns the filtered data, or FALSE if the filter fails.

Examples

Example 1. A filter_var() example

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
?>

The above example will output:

string(15) "bob@example.com"
bool(false)

XLII. Firebird/InterBase Functions

Introduction

Firebird/InterBase is a relational database offering many ANSI SQL-92 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird/InterBase offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Borland/Inprise. More information about InterBase is available at http://www.borland.com/interbase/.

Firebird is a commercially independent project of C and C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at http://www.firebirdsql.org/.

Note: This extension supports InterBase versions 5 and up and all versions of Firebird. Support for InterBase version 5.x will be dropped in PHP 5.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On


Installation

To enable InterBase support configure PHP --with-interbase[=DIR], where DIR is the InterBase base install directory, which defaults to /usr/interbase.

Note to Win32 Users: In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: gds32.dll

In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therefore you don't need to worry because gds32.dll will already be in the PATH.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. InterBase configuration options

NameDefaultChangeableChangelog
ibase.allow_persistent"1"PHP_INI_SYSTEM 
ibase.max_persistent"-1"PHP_INI_SYSTEM 
ibase.max_links"-1"PHP_INI_SYSTEM 
ibase.default_dbNULLPHP_INI_SYSTEMAvailable since PHP 5.0.0.
ibase.default_userNULLPHP_INI_ALL 
ibase.default_passwordNULLPHP_INI_ALL 
ibase.default_charsetNULLPHP_INI_ALLAvailable since PHP 5.0.0.
ibase.timestampformat"%Y-%m-%d %H:%M:%S"PHP_INI_ALL 
ibase.dateformat"%Y-%m-%d"PHP_INI_ALL 
ibase.timeformat"%H:%M:%S"PHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.

Here's a short explanation of the configuration directives.

ibase.allow_persistent boolean

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent integer

The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.

ibase.max_links integer

The maximum number of Firebird/InterBase connections per process, including persistent connections.

ibase.default_db string

The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.

ibase.default_user string

The user name to use when connecting to a database if no user name is specified.

ibase.default_password string

The password to use when connecting to a database if no password is specified.

ibase.default_charset string

The character set to use when connecting to a database if no character set is specified.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants can be passed to ibase_trans() to specify transaction behaviour.

Table 2. Firebird/InterBase transaction flags

ConstantDescription
IBASE_DEFAULT The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READStarts a read-only transaction.
IBASE_WRITEStarts a read-write transaction.
IBASE_CONSISTENCYStarts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCYStarts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTEDStarts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAITIndicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAITIndicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Table 3. Firebird/InterBase fetch flags

ConstantDescription
IBASE_FETCH_BLOBSAlso available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYSCauses arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIMECauses date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service API functions (ibase_server_info(), ibase_db_info(), ibase_backup(), ibase_restore() and ibase_maintain_db()). Please refer to the Firebird/InterBase manuals for the meaning of these options.

IBASE_BKP_IGNORE_CHECKSUMS

IBASE_BKP_IGNORE_LIMBO

IBASE_BKP_METADATA_ONLY

IBASE_BKP_NO_GARBAGE_COLLECT

IBASE_BKP_OLD_DESCRIPTIONS

IBASE_BKP_NON_TRANSPORTABLE

IBASE_BKP_CONVERT

Options to ibase_backup()

IBASE_RES_DEACTIVATE_IDX

IBASE_RES_NO_SHADOW

IBASE_RES_NO_VALIDITY

IBASE_RES_ONE_AT_A_TIME

IBASE_RES_REPLACE

IBASE_RES_CREATE

IBASE_RES_USE_ALL_SPACE

Options to ibase_restore()

IBASE_PRP_PAGE_BUFFERS

IBASE_PRP_SWEEP_INTERVAL

IBASE_PRP_SHUTDOWN_DB

IBASE_PRP_DENY_NEW_TRANSACTIONS

IBASE_PRP_DENY_NEW_ATTACHMENTS

IBASE_PRP_RESERVE_SPACE

IBASE_PRP_RES_USE_FULL

IBASE_PRP_RES

IBASE_PRP_WRITE_MODE

IBASE_PRP_WM_ASYNC

IBASE_PRP_WM_SYNC

IBASE_PRP_ACCESS_MODE

IBASE_PRP_AM_READONLY

IBASE_PRP_AM_READWRITE

IBASE_PRP_SET_SQL_DIALECT

IBASE_PRP_ACTIVATE

IBASE_PRP_DB_ONLINE

IBASE_RPR_CHECK_DB

IBASE_RPR_IGNORE_CHECKSUM

IBASE_RPR_KILL_SHADOWS

IBASE_RPR_MEND_DB

IBASE_RPR_VALIDATE_DB

IBASE_RPR_FULL

IBASE_RPR_SWEEP_DB

Options to ibase_maintain_db()

IBASE_STS_DATA_PAGES

IBASE_STS_DB_LOG

IBASE_STS_HDR_PAGES

IBASE_STS_IDX_PAGES

IBASE_STS_SYS_RELATIONS

Options to ibase_db_info()

IBASE_SVC_SERVER_VERSION

IBASE_SVC_IMPLEMENTATION

IBASE_SVC_GET_ENV

IBASE_SVC_GET_ENV_LOCK

IBASE_SVC_GET_ENV_MSG

IBASE_SVC_USER_DBPATH

IBASE_SVC_SVR_DB_INFO

IBASE_SVC_GET_USERS

Options to ibase_server_info()

Table of Contents
ibase_add_user -- Add a user to a security database (only for IB6 or later)
ibase_affected_rows -- Return the number of rows that were affected by the previous query
ibase_backup -- Initiates a backup task in the service manager and returns immediately
ibase_blob_add -- Add data into a newly created blob
ibase_blob_cancel -- Cancel creating blob
ibase_blob_close -- Close blob
ibase_blob_create -- Create a new blob for adding data
ibase_blob_echo -- Output blob contents to browser
ibase_blob_get -- Get len bytes data from open blob
ibase_blob_import -- Create blob, copy file in it, and close it
ibase_blob_info -- Return blob length and other useful info
ibase_blob_open -- Open blob for retrieving data parts
ibase_close -- Close a connection to an InterBase database
ibase_commit_ret -- Commit a transaction without closing it
ibase_commit -- Commit a transaction
ibase_connect -- Open a connection to an InterBase database
ibase_db_info -- Request statistics about a database
ibase_delete_user -- Delete a user from a security database (only for IB6 or later)
ibase_drop_db -- Drops a database
ibase_errcode -- Return an error code
ibase_errmsg -- Return error messages
ibase_execute -- Execute a previously prepared query
ibase_fetch_assoc -- Fetch a result row from a query as an associative array
ibase_fetch_object -- Get an object from a InterBase database
ibase_fetch_row -- Fetch a row from an InterBase database
ibase_field_info -- Get information about a field
ibase_free_event_handler -- Cancels a registered event handler
ibase_free_query -- Free memory allocated by a prepared query
ibase_free_result -- Free a result set
ibase_gen_id -- Increments the named generator and returns its new value
ibase_maintain_db -- Execute a maintenance command on the database server
ibase_modify_user -- Modify a user to a security database (only for IB6 or later)
ibase_name_result -- Assigns a name to a result set
ibase_num_fields -- Get the number of fields in a result set
ibase_num_params -- Return the number of parameters in a prepared query
ibase_param_info -- Return information about a parameter in a prepared query
ibase_pconnect -- Open a persistent connection to an InterBase database
ibase_prepare -- Prepare a query for later binding of parameter placeholders and execution
ibase_query -- Execute a query on an InterBase database
ibase_restore -- Initiates a restore task in the service manager and returns immediately
ibase_rollback_ret -- Roll back a transaction without closing it
ibase_rollback -- Roll back a transaction
ibase_server_info -- Request information about a database server
ibase_service_attach -- Connect to the service manager
ibase_service_detach -- Disconnect from the service manager
ibase_set_event_handler -- Register a callback function to be called when events are posted
ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queries
ibase_trans -- Begin a transaction
ibase_wait_event -- Wait for an event to be posted by the database

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user -- Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_affected_rows

(PHP 5)

ibase_affected_rows -- Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ( [resource link_identifier] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

Parameters

link_identifier

A transaction context. If link_identifier is a connection resource, its default transaction is used.

Return Values

Returns the number of rows as an integer.

ibase_backup

(PHP 5)

ibase_backup -- Initiates a backup task in the service manager and returns immediately

Description

mixed ibase_backup ( resource service_handle, string source_db, string dest_file [, int options [, bool verbose]] )

Warning

This function is currently not documented; only the argument list is available.

ibase_blob_add

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_add -- Add data into a newly created blob

Description

void ibase_blob_add ( resource blob_handle, string data )

ibase_blob_add() adds data into a blob created with ibase_blob_create().

Parameters

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

Return Values

No value is returned.

ibase_blob_cancel

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_cancel -- Cancel creating blob

Description

bool ibase_blob_cancel ( resource blob_handle )

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

Parameters

blob_handle

A BLOB handle opened with ibase_create_blob().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_blob_close

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_close -- Close blob

Description

mixed ibase_blob_close ( resource blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_open_blob() or has been opened for writing by ibase_create_blob().

Parameters

blob_handle

A BLOB handle opened with ibase_create_blob() or ibase_open_blob().

Return Values

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_create

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_create -- Create a new blob for adding data

Description

resource ibase_blob_create ( [resource link_identifier] )

ibase_blob_create() creates a new BLOB for filling with data.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

ibase_blob_echo

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_echo -- Output blob contents to browser

Description

bool ibase_blob_echo ( [resource link_identifier, string blob_id] )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

Return Values

Returns TRUE on success or FALSE on failure.

ibase_blob_get

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_get -- Get len bytes data from open blob

Description

string ibase_blob_get ( resource blob_handle, int len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Note: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

Return Values

Returns at most len bytes from the BLOB, or FALSE on failure.

Examples

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_import

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_import -- Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource link_identifier, resource file_handle )

string ibase_blob_import ( resource file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

Parameters

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().

Return Values

Returns the BLOB id on success, or FALSE on error.

Examples

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_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_info -- Return blob length and other useful info

Description

array ibase_blob_info ( resource link_identifier, string blob_id )

array ibase_blob_info ( string blob_id )

Returns the BLOB length and other useful information.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

ibase_blob_open

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_open -- Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource link_identifier, string blob_id )

resource ibase_blob_open ( string blob_id )

Opens an existing BLOB for reading.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

ibase_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_close -- Close a connection to an InterBase database

Description

bool ibase_close ( [resource connection_id] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

Parameters

connection_id

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_commit_ret

(PHP 5)

ibase_commit_ret -- Commit a transaction without closing it

Description

bool ibase_commit_ret ( [resource link_or_trans_identifier] )

Commits a transaction without closing it.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_commit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_commit -- Commit a transaction

Description

bool ibase_commit ( [resource link_or_trans_identifier] )

Commits a transaction.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_connect -- Open a connection to an InterBase database

Description

resource ibase_connect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

Establishes a connection to an InterBase server.

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().

Parameters

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

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

Errors/Exceptions

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).

ChangeLog

VersionDescription
4.0.0 The buffers, dialect and role parameters were added

Examples

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_db_info

(PHP 5)

ibase_db_info -- Request statistics about a database

Description

string ibase_db_info ( resource service_handle, string db, int action [, int argument] )

Warning

This function is currently not documented; only the argument list is available.

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user -- Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( resource service_handle, string user_name )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_drop_db

(PHP 5)

ibase_drop_db -- Drops a database

Description

bool ibase_drop_db ( [resource connection] )

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

Parameters

connection

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_errcode

(PHP 5)

ibase_errcode -- Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call.

Return Values

Returns the error code as an integer, or FALSE if no error occured.

See Also

ibase_errmsg()

ibase_errmsg

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_errmsg -- Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call.

Return Values

Returns the error message as a string, or FALSE if no error occured.

See Also

ibase_errcode()

ibase_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_execute -- Execute a previously prepared query

Description

resource ibase_execute ( resource query [, mixed bind_arg [, mixed ...]] )

Execute a query prepared by ibase_prepare().

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.

Parameters

query

An InterBase query prepared by ibase_prepare().

bind_arg

...

Return 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: In PHP 5.0.0 and up, this function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

Examples

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);
}

?>

See Also

ibase_query()

ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc -- Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource result [, int fetch_flag] )

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.

Parameters

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.

Return Values

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_object

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( resource result_id [, int fetch_flag] )

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

Parameters

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.

Return Values

Returns an object with the next row information, or FALSE if there are no more rows.

Examples

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource result_identifier [, int fetch_flag] )

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.

Parameters

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.

Return Values

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_field_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_field_info -- Get information about a field

Description

array ibase_field_info ( resource result, int field_number )

Returns an array with information about a field after a select query has been run.

Parameters

result

An InterBase result identifier.

field_number

Field offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

Examples

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_free_event_handler

(PHP 5)

ibase_free_event_handler -- Cancels a registered event handler

Description

bool ibase_free_event_handler ( resource event )

This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle.

Parameters

event

An event resource, created by ibase_set_event_handler().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_free_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_query -- Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource query )

Frees a prepared query.

Parameters

query

A query prepared with ibase_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_result -- Free a result set

Description

bool ibase_free_result ( resource result_identifier )

Frees a result set.

Parameters

result_identifier

A result set created by ibase_query() or ibase_execute().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_gen_id

(PHP 5)

ibase_gen_id -- Increments the named generator and returns its new value

Description

mixed ibase_gen_id ( string generator [, int increment [, resource link_identifier]] )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns new generator value as integer, or as string if the value is too big.

ibase_maintain_db

(PHP 5)

ibase_maintain_db -- Execute a maintenance command on the database server

Description

bool ibase_maintain_db ( resource service_handle, string db, int action [, int argument] )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user -- Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

Warning

This function is currently not documented; only the argument list is available.

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_name_result

(PHP 5)

ibase_name_result -- Assigns a name to a result set

Description

bool ibase_name_result ( resource result, string name )

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements.

Parameters

result

An InterBase result set.

name

Tbe name to be assigned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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_num_fields

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_num_fields -- Get the number of fields in a result set

Description

int ibase_num_fields ( resource result_id )

Get the number of fields in a result set.

Parameters

result_id

An InterBase result identifier.

Return Values

Returns the number of fields as an integer.

Examples

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_num_params

(PHP 5)

ibase_num_params -- Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource query )

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

Parameters

query

The prepared query handle.

Return Values

Returns the number of parameters as an integer.

ibase_param_info

(PHP 5)

ibase_param_info -- Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource query, int param_number )

Returns an array with information about a parameter after a query has been prepared.

Parameters

query

An InterBase prepared query handle.

param_number

Parameter offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

ibase_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_pconnect -- Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

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'.

Parameters

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

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

ChangeLog

VersionDescription
4.0.0 The buffers, dialect and role parameters were added

ibase_prepare

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_prepare -- Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( string query )

resource ibase_prepare ( resource link_identifier, string query )

resource ibase_prepare ( resource link_identifier, string trans, string query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

Parameters

query

An InterBase query.

Return Values

Returns a prepared query handle, or FALSE on error.

ibase_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_query -- Execute a query on an InterBase database

Description

resource ibase_query ( [resource link_identifier, string query [, int bind_args]] )

Performs a query on an InterBase database.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

Return 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: 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.

Errors/Exceptions

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).

Examples

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_restore

(PHP 5)

ibase_restore -- Initiates a restore task in the service manager and returns immediately

Description

mixed ibase_restore ( resource service_handle, string source_file, string dest_db [, int options [, bool verbose]] )

Warning

This function is currently not documented; only the argument list is available.

ibase_rollback_ret

(PHP 5)

ibase_rollback_ret -- Roll back a transaction without closing it

Description

bool ibase_rollback_ret ( [resource link_or_trans_identifier] )

Rolls back a transaction without closing it.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_rollback

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_rollback -- Roll back a transaction

Description

bool ibase_rollback ( [resource link_or_trans_identifier] )

Rolls back a transaction.

Parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_server_info

(PHP 5)

ibase_server_info -- Request information about a database server

Description

string ibase_server_info ( resource service_handle, int action )

Warning

This function is currently not documented; only the argument list is available.

ibase_service_attach

(PHP 5)

ibase_service_attach -- Connect to the service manager

Description

resource ibase_service_attach ( string host, string dba_username, string dba_password )

Warning

This function is currently not documented; only the argument list is available.

ibase_service_detach

(PHP 5)

ibase_service_detach -- Disconnect from the service manager

Description

bool ibase_service_detach ( resource service_handle )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler -- Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

resource ibase_set_event_handler ( resource connection, callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

This function registers a PHP user function as event handler for the specified events.

Parameters

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_name1

An event name.

event_name2

...

Return Values

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

Examples

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_timefmt

(PHP 3 >= 3.0.6, PHP 4)

ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queries

Description

bool ibase_timefmt ( string format [, int columntype] )

Sets the format of timestamp, date or time type columns returned from queries.

You can set defaults for these formats with the PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Note: This function has been removed from PHP 5, use ini_set() instead.

Parameters

format

Internally, the columns are formatted by c-function strftime(), so refer to its documentation regarding to the format of the string.

columntype

columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ibase_timefmt() example

<?php
/* InterBase 6 TIME-type columns will be returned in
 * the form '05 hours 37 minutes'. */
ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?>

ibase_trans

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_trans -- Begin a transaction

Description

resource ibase_trans ( [int trans_args [, resource link_identifier]] )

Begins a transaction.

Note: The behaviour of this function has been changed in PHP 5.0.0. The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Note: In PHP 5.0.0. and up, this function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

Parameters

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.

Return Values

Returns a transaction handle, or FALSE on error.

ibase_wait_event

(PHP 5)

ibase_wait_event -- Wait for an event to be posted by the database

Description

string ibase_wait_event ( string event_name1 [, string event_name2 [, string ...]] )

string ibase_wait_event ( resource connection, string event_name1 [, string event_name2 [, string ...]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

Parameters

event_name1

The event name.

event_name2

...

Return Values

Returns the name of the event that was posted.

XLIII. Firebird/Interbase Functions (PDO_FIREBIRD)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

Table of Contents
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

PDO_FIREBIRD DSN

(no version information, might be only in CVS)

PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

Description

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

DataSource

The hostname on which the database server resides.

Port

The port number for the server on which the database is running.

Database

The name of the database.

User

The name of the user that will connect to the database.

Password

The password for the user.

Examples

Example 1. PDO_FIREBIRD DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:

firebird:User=john;Password=mypass;Database=DATABASE.GDE;DataSource=localhost;Port=3050

XLIV. FriBiDi Functions

Introduction

FriBiDi is a free implementation of the Unicode Bidirectional Algorithm.


Requirements

You must download and install the FriBiDi package.


Installation

This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/fribidi.

In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.

Windows users will enable php_fribidi.dll inside of php.ini in order to use these functions. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FRIBIDI_CHARSET_UTF8 (integer)

Unicode

FRIBIDI_CHARSET_8859_6 (integer)

Arabic

FRIBIDI_CHARSET_8859_8 (integer)

Hebrew

FRIBIDI_CHARSET_CP1255 (integer)

Hebrew/Yiddish

FRIBIDI_CHARSET_CP1256 (integer)

Arabic

FRIBIDI_CHARSET_ISIRI_3342 (integer)

Persian

FRIBIDI_CHARSET_CAP_RTL (integer)

Used for test purposes, will treat CAPS as non-English letters

FRIBIDI_RTL (integer)

Right to left

FRIBIDI_LTR (integer)

Left to right

FRIBIDI_AUTO (integer)

Autodetect the base direction

Table of Contents
fribidi_log2vis -- Convert a logical string to a visual one

fribidi_log2vis

(PHP 4 >= 4.0.4, PECL)

fribidi_log2vis -- Convert a logical string to a visual one

Description

string fribidi_log2vis ( string str, string direction, int charset )

Converts a logical string to a vissual one.

Parameters

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Return Values

Returns the visual string on success, or FALSE on failure.

XLV. FrontBase Functions

Introduction

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at http://www.frontbase.com/.

Documentation for FrontBase can be found at http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.


Requirements

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from http://www.frontbase.com/.


Installation

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql[=DIR] option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql. This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. FrontBase configuration options

NameDefaultChangeableChangelog
fbsql.allow_persistent"1"PHP_INI_SYSTEMAvailable since PHP 4.2.0.
fbsql.generate_warnings"0"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.autocommit"1"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.max_persistent"-1"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.max_links"128"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.max_connections"128"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.max_results"128"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.batchSize"1000"PHP_INI_SYSTEM 
fbsql.default_hostNULLPHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.default_user"_SYSTEM"PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.default_password""PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.default_database""PHP_INI_SYSTEMAvailable since PHP 4.0.6.
fbsql.default_database_password""PHP_INI_SYSTEMAvailable since PHP 4.0.6.
For further details and definitions of the PHP_INI_* constants, see the Appendix I.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FBSQL_ASSOC (integer)

FBSQL_NUM (integer)

FBSQL_BOTH (integer)

FBSQL_LOCK_DEFERRED (integer)

FBSQL_LOCK_OPTIMISTIC (integer)

FBSQL_LOCK_PESSIMISTIC (integer)

FBSQL_ISO_READ_UNCOMMITTED (integer)

FBSQL_ISO_READ_COMMITTED (integer)

FBSQL_ISO_REPEATABLE_READ (integer)

FBSQL_ISO_SERIALIZABLE (integer)

FBSQL_ISO_VERSIONED (integer)

FBSQL_UNKNOWN (integer)

FBSQL_STOPPED (integer)

FBSQL_STARTING (integer)

FBSQL_RUNNING (integer)

FBSQL_STOPPING (integer)

FBSQL_NOEXEC (integer)

FBSQL_LOB_DIRECT (integer)

FBSQL_LOB_HANDLE (integer)

Table of Contents
fbsql_affected_rows -- Get number of affected rows in previous FrontBase operation
fbsql_autocommit -- Enable or disable autocommit
fbsql_blob_size -- Get the size of a BLOB
fbsql_change_user -- Change logged in user of the active connection
fbsql_clob_size -- Get the size of a CLOB
fbsql_close -- Close FrontBase connection
fbsql_commit -- Commits a transaction to the database
fbsql_connect -- Open a connection to a FrontBase Server
fbsql_create_blob -- Create a BLOB
fbsql_create_clob -- Create a CLOB
fbsql_create_db -- Create a FrontBase database
fbsql_data_seek -- Move internal result pointer
fbsql_database_password -- Sets or retrieves the password for a FrontBase database
fbsql_database -- Get or set the database name used with a connection
fbsql_db_query -- Send a FrontBase query
fbsql_db_status -- Get the status for a given database
fbsql_drop_db -- Drop (delete) a FrontBase database
fbsql_errno -- Returns the error number from previous operation
fbsql_error -- Returns the error message from previous operation
fbsql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
fbsql_fetch_assoc -- Fetch a result row as an associative array
fbsql_fetch_field -- Get column information from a result and return as an object
fbsql_fetch_lengths -- Get the length of each output in a result
fbsql_fetch_object -- Fetch a result row as an object
fbsql_fetch_row -- Get a result row as an enumerated array
fbsql_field_flags -- Get the flags associated with the specified field in a result
fbsql_field_len -- Returns the length of the specified field
fbsql_field_name -- Get the name of the specified field in a result
fbsql_field_seek -- Set result pointer to a specified field offset
fbsql_field_table -- Get name of the table the specified field is in
fbsql_field_type -- Get the type of the specified field in a result
fbsql_free_result -- Free result memory
fbsql_get_autostart_info -- 
fbsql_hostname -- Get or set the host name used with a connection
fbsql_insert_id -- Get the id generated from the previous INSERT operation
fbsql_list_dbs -- List databases available on a FrontBase server
fbsql_list_fields -- List FrontBase result fields
fbsql_list_tables -- List tables in a FrontBase database
fbsql_next_result -- Move the internal result pointer to the next result
fbsql_num_fields -- Get number of fields in result
fbsql_num_rows -- Get number of rows in result
fbsql_password -- Get or set the user password used with a connection
fbsql_pconnect -- Open a persistent connection to a FrontBase Server
fbsql_query -- Send a FrontBase query
fbsql_read_blob -- Read a BLOB from the database
fbsql_read_clob -- Read a CLOB from the database
fbsql_result -- Get result data
fbsql_rollback -- Rollback a transaction to the database
fbsql_rows_fetched -- Get the number of rows affected by the last statement
fbsql_select_db -- Select a FrontBase database
fbsql_set_characterset -- Change input/output character set
fbsql_set_lob_mode -- Set the LOB retrieve mode for a FrontBase result set
fbsql_set_password -- Change the password for a given user
fbsql_set_transaction -- Set the transaction locking and isolation
fbsql_start_db -- Start a database on local or remote server
fbsql_stop_db -- Stop a database on local or remote server
fbsql_table_name -- Get table name of field
fbsql_tablename -- Alias of of fbsql_table_name()
fbsql_username -- Get or set the username for the connection
fbsql_warnings -- Enable or disable FrontBase warnings

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_affected_rows -- Get number of affected rows in previous FrontBase operation

Description

int fbsql_affected_rows ( [resource link_identifier] )

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier.

Note: If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

Note: When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

If the last query failed, this function will return -1.

fbsql_autocommit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_autocommit -- Enable or disable autocommit

Description

bool fbsql_autocommit ( resource link_identifier [, bool OnOff] )

Returns the current autocommit status.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

OnOff

If this optional parameter is given the auto commit status will be changed.

With OnOff set to TRUE each statement will be committed automatically, if no errors was found.

With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

Return Values

Returns the current autocommit status, as a boolean.

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_blob_size -- Get the size of a BLOB

Description

int fbsql_blob_size ( string blob_handle [, resource link_identifier] )

Returns the size of the given BLOB.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns the BLOB size as an integer, or FALSE on error.

fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user -- Change logged in user of the active connection

Description

bool fbsql_change_user ( string user, string password [, string database [, resource link_identifier]] )

fbsql_change_user() changes the logged in user of the specified connection. If the new user and password authorization fails, the current connected user stays active.

Parameters

user

The new user name.

password

The new user password.

database

If specified, this will be the default or current database after the user has been changed.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_clob_size -- Get the size of a CLOB

Description

int fbsql_clob_size ( string clob_handle [, resource link_identifier] )

Returns the size of the given CLOB.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns the CLOB size as an integer, or FALSE on error.

fbsql_close

(PHP 4 >= 4.0.6, PHP 5)

fbsql_close -- Close FrontBase connection

Description

bool fbsql_close ( [resource link_identifier] )

Closes the connection to the FrontBase server that's associated with the specified link identifier.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. fbsql_close() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?>

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_commit -- Commits a transaction to the database

Description

bool fbsql_commit ( [resource link_identifier] )

Ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_connect -- Open a connection to a FrontBase Server

Description

resource fbsql_connect ( [string hostname [, string username [, string password]]] )

fbsql_connect() establishes a connection to a FrontBase server.

If a second call is made to fbsql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling fbsql_close().

Parameters

hostname

The server host name. Defaults to 'NULL'.

username

The user name for the connection. Defaults to _SYSTEM.

password

The user name for the connection. Defaults to the empty string.

Return Values

Returns a positive FrontBase link identifier on success, or FALSE on errors.

Examples

Example 1. fbsql_connect() example

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?>

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_blob -- Create a BLOB

Description

string fbsql_create_blob ( string blob_data [, resource link_identifier] )

Creates a BLOB from the given data.

Parameters

blob_data

The BLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a resource handle to the newly created BLOB, which can be used with insert and update commands to store the BLOB in the database.

Examples

Example 1. fbsql_create_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "blobfile.bin";
$fp = fopen($filename, "rb");
$blobdata = fread($fp, filesize($filename));
fclose($fp);

$blobHandle = fbsql_create_blob($blobdata, $link);

$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link);
?>

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_clob -- Create a CLOB

Description

string fbsql_create_clob ( string clob_data [, resource link_identifier] )

Creates a CLOB from the given data.

Parameters

clob_data

The CLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a resource handle to the newly created CLOB, which can be used with insert and update commands to store the CLOB in the database.

Examples

Example 1. fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "clob_file.txt";
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename));
fclose($fp);

$clobHandle = fbsql_create_clob($clobdata, $link);

$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
$rs = fbsql_query($sql, $link);
?>

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_create_db -- Create a FrontBase database

Description

bool fbsql_create_db ( string database_name [, resource link_identifier [, string database_options]] )

Attempts to create a new database on the specied server.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

database_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. fbsql_create_db() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
if (fbsql_create_db("my_db")) {
    echo "Database created successfully\n";
} else {
    printf("Error creating database: %s\n", fbsql_error());
}
?>

See Also

fbsql_drop_db()

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_data_seek -- Move internal result pointer

Description

bool fbsql_data_seek ( resource result, int row_number )

Moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number.

The next call to fbsql_fetch_row() would return that row.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row_number

The row number. Starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. fbsql_data_seek() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");

fbsql_select_db("samp_db")
    or die("Could not select database");

$query = "SELECT last_name, first_name FROM friends;";
$result = fbsql_query($query)
    or die("Query failed");

// fetch rows in reverse order

for ($i = fbsql_num_rows($result) - 1; $i >=0; $i--) {
    if (!fbsql_data_seek($result, $i)) {
        printf("Cannot seek to row %d\n", $i);
        continue;
    }

    if (!($row = fbsql_fetch_object($result)))
        continue;

    echo $row->last_name . $row->first_name . "<br />\n";
}

fbsql_free_result($result);
?>

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database_password -- Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource link_identifier [, string database_password] )

Sets and retrieves the database password used by the connection. If a database is protected by a database password, the user must call this function before calling fbsql_select_db().

If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrieve the database password for a database.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Return Values

Returns the database password associated with the link identifier.

Examples

Example 1. fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?>

fbsql_database

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database -- Get or set the database name used with a connection

Description

string fbsql_database ( resource link_identifier [, string database] )

Get or set the database name used with the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

database

The database name. If given, the default database of the connexion will be changed to database.

Return Values

Returns the name of the database used with this connection.

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_db_query -- Send a FrontBase query

Description

resource fbsql_db_query ( string database, string query [, resource link_identifier] )

Selects a database and executes a query on it.

Parameters

database

The database to be selected.

query

The SQL query to be executed.

Note: The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a positive FrontBase result identifier to the query result, or FALSE on error.

fbsql_db_status

(PHP 4 >= 4.1.0, PHP 5)

fbsql_db_status -- Get the status for a given database

Description

int fbsql_db_status ( string database_name [, resource link_identifier] )

Gets the current status of the specified database.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns an integer value with the current status. This can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.

  • FBSQL_UNKNOWN - The Status is unknown.

  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.

  • FBSQL_STARTING - The database is starting.

  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.

  • FBSQL_STOPPING - The database is stopping.

  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_drop_db -- Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string database_name [, resource link_identifier] )

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5)

fbsql_errno -- Returns the error number from previous operation

Description

int fbsql_errno ( [resource link_identifier] )

Returns the numerical value of the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Examples

Example 1. fbsql_errno() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

fbsql_error

(PHP 4 >= 4.0.6, PHP 5)

fbsql_error -- Returns the error message from previous operation

Description

string fbsql_error ( [resource link_identifier] )

Returns the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Examples

Example 1. fbsql_error() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource result [, int result_type] )

fbsql_fetch_array() is a combination of fbsql_fetch_row() and fbsql_fetch_assoc().

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

result_type

A constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, or FBSQL_BOTH.

When using FBSQL_BOTH, in addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

Examples

Example 1. fbsql_fetch_array() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select user_id, fullname from table");
while ($row = fbsql_fetch_array($result)) {
    echo "user_id: " . $row["user_id"] . "<br />\n";
    echo "user_id: " . $row[0] . "<br />\n";
    echo "fullname: " . $row["fullname"] . "<br />\n";
    echo "fullname: " . $row[1] . "<br />\n";
}
fbsql_free_result($result);
?>

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_assoc -- Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource result )

Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC as second parameter. It only returns an associative array.

This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use fbsql_fetch_array() and have it return the numeric indices as well.

Examples

Example 1. fbsql_fetch_assoc() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_assoc($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result($result);
?>

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_field -- Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource result [, int field_offset] )

Used in order to obtain information about fields in a certain query result.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0. If not specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

Return Values

Returns an object containing field information, or FALSE on errors.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • type - the type of the column

Examples

Example 1. fbsql_fetch_field() example

<?php
fbsql_connect($host, $user, $password)
    or die("Could not connect");
$result = fbsql_db_query("database", "select * from table")
    or die("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_lengths -- Get the length of each output in a result

Description

array fbsql_fetch_lengths ( resource result )

Stores the lengths of each result column in the last row returned by fbsql_fetch_row(), fbsql_fetch_array() and fbsql_fetch_object() in an array.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array, starting at offset 0, that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_object -- Fetch a result row as an object

Description

object fbsql_fetch_object ( resource result )

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example 1. fbsql_fetch_object() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_row -- Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource result )

fbsql_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array that corresponds to the fetched row where each result column is stored in an offset, starting at offset 0, or FALSE if there are no more rows.

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_flags -- Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource result [, int field_offset] )

Gets the flags associated with the specified field in a result.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field flags of the specified field as a single word per flag separated by a single space, so that you can split the returned value using explode().

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_len -- Returns the length of the specified field

Description

int fbsql_field_len ( resource result [, int field_offset] )

Returns the length of the specified field.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the length of the specified field.

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_name -- Get the name of the specified field in a result

Description

string fbsql_field_name ( resource result [, int field_index] )

Returns the name of the specified field index.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name as a string, or FALSE if the field doesn't exist.

Examples

Example 1. fbsql_field_name() example

<?php
// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

The above example will output:

user_id
password

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_seek -- Set result pointer to a specified field offset

Description

bool fbsql_field_seek ( resource result [, int field_offset] )

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_table -- Get name of the table the specified field is in

Description

string fbsql_field_table ( resource result [, int field_offset] )

Returns the name of the table that the specified field is in.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name of the table, as a string.

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_type -- Get the type of the specified field in a result

Description

string fbsql_field_type ( resource result [, int field_offset] )

fbsql_field_type() is similar to the fbsql_field_name() function, but the field type is returned instead.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the FrontBase documentation.

Examples

Example 1. fbsql_field_type() example

<?php

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />";
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_free_result -- Free result memory

Description

bool fbsql_free_result ( resource result )

Frees all memory associated with the given result identifier.

fbsql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_get_autostart_info

(PHP 4 >= 4.1.0, PHP 5)

fbsql_get_autostart_info -- 

Description

array fbsql_get_autostart_info ( [resource link_identifier] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5)

fbsql_hostname -- Get or set the host name used with a connection

Description

string fbsql_hostname ( resource link_identifier [, string host_name] )

Gets or sets the host name used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

host_name

If provided, this will be the new connection host name.

Return Values

Returns the current host name used for the connection.

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5)

fbsql_insert_id -- Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ( [resource link_identifier] )

Gets the id generated from the previous INSERT operation which created a DEFAULT UNIQUE value.

Note: The value of the FrontBase SQL function fbsql_insert_id() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns the ID generated from the previous INSERT query, or 0 if the previous query does not generate an DEFAULT UNIQUE value.

If you need to save the value for later, be sure to call this function immediately after the query that generates the value.

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_dbs -- List databases available on a FrontBase server

Description

resource fbsql_list_dbs ( [resource link_identifier] )

Return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() to traverse this result pointer.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a result pointer or FALSE on error.

Examples

Example 1. fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example will output something similar to:

database1
database2
database3
...

Note: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_fields -- List FrontBase result fields

Description

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier] )

Retrieves information about the given table.

Parameters

database_name

The database name.

table_name

The table name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a result pointer which can be used with the fbsql_field_xxx functions, or FALSE on error.

Errors/Exceptions

A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Examples

Example 1. fbsql_list_fields() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

The above example will output something similar to:

field1
field2
field3
...

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_tables -- List tables in a FrontBase database

Description

resource fbsql_list_tables ( string database [, resource link_identifier] )

Returns a result pointer describing the database.

Parameters

database

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a result pointer which can be used with the fbsql_tablename() function to read the actual table names, or FALSE on error.

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_next_result -- Move the internal result pointer to the next result

Description

bool fbsql_next_result ( resource result )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example 1. fbsql_next_result() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret");
fbsql_select_db("MyDB", $link);
$SQL = "Select * from table1; select * from table2;";
$rs = fbsql_query($SQL, $link);
do {
    while ($row = fbsql_fetch_row($rs)) {
    }
} while (fbsql_next_result($rs));
fbsql_free_result($rs);
fbsql_close($link);
?>

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_fields -- Get number of fields in result

Description

int fbsql_num_fields ( resource result )

Returns the number of fields in the given result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of fields, as an integer.

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_rows -- Get number of rows in result

Description

int fbsql_num_rows ( resource result )

Gets the number of rows in the given result set.

This function is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows returned by the last SELECT statement.

Examples

Example 1. fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

fbsql_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_password -- Get or set the user password used with a connection

Description

string fbsql_password ( resource link_identifier [, string password] )

Get or set the user password used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

password

If provided, this will be the new connection password.

Return Values

Returns the current password used for the connection.

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_pconnect -- Open a persistent connection to a FrontBase Server

Description

resource fbsql_pconnect ( [string hostname [, string username [, string password]]] )

Establishes a persistent connection to a FrontBase server.

To set the server port number, use fbsql_select_db().

fbsql_pconnect() acts very much like fbsql_connect() with two major differences:

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

This type of links is therefore called 'persistent'.

Parameters

hostname

The server host name. Defaults to localhost.

username

The user name for the connection. Defaults to _SYSTEM.

password

The password for the connection. Defaults to the empty string.

Return Values

Returns a positive FrontBase persistent link identifier on success, or FALSE on error.

See Also

fbsql_connect()

fbsql_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_query -- Send a FrontBase query

Description

resource fbsql_query ( string query [, resource link_identifier [, int batch_size]] )

Sends a query to the currently active database on the server.

If the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Parameters

query

The SQL query to be executed.

Note: The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

batch_size

Return Values

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result().

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Examples

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Example 1. fbsql_query() example

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Example 2. fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?>

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_blob -- Read a BLOB from the database

Description

string fbsql_read_blob ( string blob_handle [, resource link_identifier] )

Reads BLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a string containing the specified BLOB data.

Examples

Example 1. fbsql_read_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the blob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the BLOB data in the first row
$blob_data = fbsql_read_blob($row_data[0]);
fbsql_free_result($rs);

?>

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_clob -- Read a CLOB from the database

Description

string fbsql_read_clob ( string clob_handle [, resource link_identifier] )

Reads CLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns a string containing the specified CLOB data.

Examples

Example 1. fbsql_read_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the clob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the CLOB data in the first row
$clob_data = fbsql_read_clob($row_data[0]);
fbsql_free_result($rs);

?>

fbsql_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_result -- Get result data

Description

mixed fbsql_result ( resource result [, int row [, mixed field]] )

Returns the contents of one cell from a FrontBase 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 fbsql_result().

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tabledname.fieldname).

If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Note: Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

See Also

Recommended high-performance alternatives:

fbsql_fetch_row()
fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_object()

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5)

fbsql_rollback -- Rollback a transaction to the database

Description

bool fbsql_rollback ( [resource link_identifier] )

Ends the current transaction by rolling back all statements issued since last commit.

This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_rows_fetched

(PHP 5 >= 5.1.0RC1)

fbsql_rows_fetched -- Get the number of rows affected by the last statement

Description

int fbsql_rows_fetched ( resource result )

Gets the number of rows affected by the last statement.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows, as an integer.

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_select_db -- Select a FrontBase database

Description

bool fbsql_select_db ( [string database_name [, resource link_identifier]] )

Sets the current active database on the given link identifier.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

Parameters

database_name

The name of the database to be selected.

If the database is protected with a database password, the you must call fbsql_database_password() before selecting the database.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_set_characterset

(PHP 5 >= 5.1.0RC1)

fbsql_set_characterset -- Change input/output character set

Description

void fbsql_set_characterset ( resource link_identifier, int characterset [, int in_out_both] )

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_lob_mode -- Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource result, int lob_mode )

Sets the mode for retrieving LOB data from the database.

When BLOB and CLOB data is retrieved in FrontBase it can be retrieved direct or indirect. Direct retrieved LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be retrieved directly.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

lob_mode

Can be one of:

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.

  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as @'000000000000000000000000'.

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_set_password

(PHP 5)

fbsql_set_password -- Change the password for a given user

Description

bool fbsql_set_password ( resource link_identifier, string user, string password, string old_password )

Changes the password for the given user.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

user

The user name.

password

The new password to be set.

old_password

The old password to be replaced.

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_transaction -- Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource link_identifier, int locking, int isolation )

Sets the transaction locking and isolation.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

locking

The type of locking to be set. It can be one of the following constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or FBSQL_LOCK_PESSIMISTIC.

isolation

The type of isolation to be set. It can be one of the following constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED, FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or FBSQL_ISO_VERSIONED.

Return Values

No value is returned.

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_start_db -- Start a database on local or remote server

Description

bool fbsql_start_db ( string database_name [, resource link_identifier [, string database_options]] )

Start a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

database_options

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_stop_db -- Stop a database on local or remote server

Description

bool fbsql_stop_db ( string database_name [, resource link_identifier] )

Stops a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5)

fbsql_table_name -- Get table name of field

Description

string fbsql_table_name ( resource result, int index )

fbsql_table_name() gets the name of the current table in the given result set.

The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Parameters

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Return Values

Returns the name of the table, as a string.

Examples

Example 1. fbsql_table_name() example

<?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5)

fbsql_tablename -- Alias of of fbsql_table_name()

Description

This function is an alias of: fbsql_table_name().

fbsql_username

(PHP 4 >= 4.0.6, PHP 5)

fbsql_username -- Get or set the username for the connection

Description

string fbsql_username ( resource link_identifier [, string username] )

Get or set the username used for the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments

username

If provided, this is the new username to set.

Return Values

Returns the current username used with the connection, as a string.

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5)

fbsql_warnings -- Enable or disable FrontBase warnings

Description

bool fbsql_warnings ( [bool OnOff] )

Enables or disables FrontBase warnings.

Parameters

OnOff

Whether to enable warnings or no.

Return Values

Returns TRUE if warnings is turned on, FALSE otherwise.

XLVI. FTP Functions

Introduction

The functions in this extension implement client access to file servers speaking the File Transfer Protocol (FTP) as defined in http://www.faqs.org/rfcs/rfc959. This extension is meant for detailed access to an FTP server providing a wide range of control to the executing script. If you only wish to read from or write to a file on an FTP server, consider using the ftp:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.


Requirements

No external libraries are needed to build this extension.


Installation

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4 or greater or --with-ftp when using PHP 3.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect() or ftp_ssl_connect().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

The following constants were introduced in PHP 4.3.0.

FTP_AUTOSEEK (integer)

See ftp_set_option() for information.

FTP_AUTORESUME (integer)

Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)

FTP_FAILED (integer)

Asynchronous transfer has failed

FTP_FINISHED (integer)

Asynchronous transfer has finished

FTP_MOREDATA (integer)

Asynchronous transfer is still active


Examples

Example 1. FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection
if ((!$conn_id) || (!$login_result)) { 
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
        exit; 
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 

// check upload status
if (!$upload) { 
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
    }

// close the FTP stream 
ftp_close($conn_id); 
?>

Table of Contents
ftp_alloc -- Allocates space for a file to be uploaded
ftp_cdup -- Changes to the parent directory
ftp_chdir -- Changes the current directory on a FTP server
ftp_chmod -- Set permissions on a file via FTP
ftp_close -- Closes an FTP connection
ftp_connect -- Opens an FTP connection
ftp_delete -- Deletes a file on the FTP server
ftp_exec -- Requests execution of a command on the FTP server
ftp_fget -- Downloads a file from the FTP server and saves to an open file
ftp_fput -- Uploads from an open file to the FTP server
ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream
ftp_get -- Downloads a file from the FTP server
ftp_login -- Logs in to an FTP connection
ftp_mdtm -- Returns the last modified time of the given file
ftp_mkdir -- Creates a directory
ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)
ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)
ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)
ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)
ftp_nb_put -- Stores a file on the FTP server (non-blocking)
ftp_nlist -- Returns a list of files in the given directory
ftp_pasv -- Turns passive mode on or off
ftp_put -- Uploads a file to the FTP server
ftp_pwd -- Returns the current directory name
ftp_quit -- Alias of ftp_close()
ftp_raw -- Sends an arbitrary command to an FTP server
ftp_rawlist -- Returns a detailed list of files in the given directory
ftp_rename -- Renames a file or a directory on the FTP server
ftp_rmdir -- Removes a directory
ftp_set_option -- Set miscellaneous runtime FTP options
ftp_site -- Sends a SITE command to the server
ftp_size -- Returns the size of the given file
ftp_ssl_connect -- Opens an Secure SSL-FTP connection
ftp_systype -- Returns the system type identifier of the remote FTP server

ftp_alloc

(PHP 5)

ftp_alloc -- Allocates space for a file to be uploaded

Description

bool ftp_alloc ( resource ftp_stream, int filesize [, string &result] )

Sends an ALLO command to the remote FTP server to allocate space for a file to be uploaded.

Note: Many FTP servers do not support this command. These servers may return a failure code (FALSE) indicating the command is not supported or a success code (TRUE) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.

Parameters

ftp_stream

The link identifier of the FTP connection.

filezise

The number of bytes to allocate.

return

A textual representation of the servers response will be returned by reference in result if a variable is provided.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_alloc() example

<?php

$file = "/home/user/myfile";

/* connect to the server */
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'anonymous', 'user@example.com');

if (ftp_alloc($conn_id, filesize($file), $result)) {
  echo "Space successfully allocated on server.  Sending $file.\n";
  ftp_put($conn_id, '/incomming/myfile', $file, FTP_BINARY);
} else {
  echo "Unable to allocate space on server.  Server said: $result\n";
}

ftp_close($conn_id);

?>

ftp_cdup

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_cdup -- Changes to the parent directory

Description

bool ftp_cdup ( resource ftp_stream )

Changes to the parent directory.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_cdup() example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change the current directory to html
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html 

// return to the parent directory
if (ftp_cdup($conn_id)) { 
  echo "cdup successful\n";
} else {
  echo "cdup not successful\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

ftp_chdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_chdir -- Changes the current directory on a FTP server

Description

bool ftp_chdir ( resource ftp_stream, string directory )

Changes the current directory to the specified one.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The target directory.

Return Values

Returns TRUE on success or FALSE on failure. If changing directory fails, PHP will also throw a warning.

Examples

Example 1. ftp_chdir() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection
if ((!$conn_id) || (!$login_result)) {
    die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($conn_id) . "\n";

// try to change the directory to somedir
if (ftp_chdir($conn_id, "somedir")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else { 
    echo "Couldn't change directory\n";
}

// close the connection
ftp_close($conn_id);
?>

ftp_chmod

(PHP 5)

ftp_chmod -- Set permissions on a file via FTP

Description

int ftp_chmod ( resource ftp_stream, int mode, string filename )

Sets the permissions on the specified remote file to mode.

Parameters

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Return Values

Returns the new file permissions on success or FALSE on error.

Examples

Example 1. ftp_chmod() example

<?php
$file = 'public_html/index.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);

// try to chmod $file to 644
if (ftp_chmod($conn_id, 0644, $file) !== false) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

chmod()

ftp_close

(PHP 4 >= 4.2.0, PHP 5)

ftp_close -- Closes an FTP connection

Description

bool ftp_close ( resource ftp_stream )

ftp_close() closes the given link identifier and releases the resource.

Note: After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_close() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// print the current directory
echo ftp_pwd($conn_id); // /

// close this connection
ftp_close($conn_id);
?>

See Also

ftp_connect()

ftp_connect

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_connect -- Opens an FTP connection

Description

resource ftp_connect ( string host [, int port [, int timeout]] )

ftp_connect() opens an FTP connection to the specified host.

Parameters

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns a FTP stream on success or FALSE on error.

Examples

Example 1. ftp_connect() example

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); 

?>

ChangeLog

VersionDescription
4.2.0 timeout was added.

ftp_delete

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_delete -- Deletes a file on the FTP server

Description

bool ftp_delete ( resource ftp_stream, string path )

ftp_delete() deletes the file specified by path from the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

path

The file to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_delete() example

<?php
$file = 'public_html/old.txt';

// 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 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);
?>

ftp_exec

(PHP 4 >= 4.0.3, PHP 5)

ftp_exec -- Requests execution of a command on the FTP server

Description

bool ftp_exec ( resource ftp_stream, string command )

Sends a SITE EXEC command request to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns TRUE if the command was successful (server sent response code: 200); otherwise returns FALSE.

Examples

Example 1. ftp_exec() example

<?php

// variable initialization
$command = 'ls -al >files.txt';

// 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);

// execute command
if (ftp_exec($conn_id, $command)) {
    echo "$command executed successfully\n";
} else {
    echo "could not execute $command\n";
}

// close the connection
ftp_close($conn_id);

?>

See Also

ftp_raw()

ftp_fget

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_fget -- Downloads a file from the FTP server and saves to an open file

Description

bool ftp_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos] )

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer.

Parameters

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_fget() example

<?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
$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 $remote_file and save it to $handle
if (ftp_fget($conn_id, $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($conn_id);
fclose($handle);
?>

ChangeLog

VersionDescription
4.3.0 resumepos was added.

ftp_fput

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_fput -- Uploads from an open file to the FTP server

Description

bool ftp_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos] )

ftp_fput() uploads the data from a file pointer to a remote file on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

handle

An open file pointer on the local file. Reading stops at end of file.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_fput() example

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// 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 upload $file
if (ftp_fput($conn_id, $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($conn_id);
fclose($fp);

?>

ChangeLog

VersionDescription
4.3.0 startpos was added.

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream

Description

mixed ftp_get_option ( resource ftp_stream, int option )

This function returns the value for the requested option from the specified FTP connection.

Parameters

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Table 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Returns the current timeout used for network related operations.
FTP_AUTOSEEK Returns TRUE if this option is on, FALSE otherwise.

Return Values

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

Examples

Example 1. ftp_get_option() example

<?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

ftp_get

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_get -- Downloads a file from the FTP server

Description

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos] )

ftp_get() retrieves a remote file from the FTP server, and saves it into a local file.

Parameters

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_get() example

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// 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);

?>

ChangeLog

VersionDescription
4.3.0 resumepos was added.

ftp_login

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_login -- Logs in to an FTP connection

Description

bool ftp_login ( resource ftp_stream, string username, string password )

Logs in to the given FTP stream.

Parameters

ftp_stream

The link identifier of the FTP connection.

username

The username (USER).

password

The password (PASS).

Return Values

Returns TRUE on success or FALSE on failure. If login fails, PHP will also throw a warning.

Examples

Example 1. ftp_login() example

<?php
                     
$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); 

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// close the connection
ftp_close($conn_id);  
?>

ftp_mdtm

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_mdtm -- Returns the last modified time of the given file

Description

int ftp_mdtm ( resource ftp_stream, string remote_file )

ftp_mdtm() gets the last modified time for a remote file.

Note: Not all servers support this feature!

Note: ftp_mdtm() does not work with directories.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The file from which to extract the last modification time.

Return Values

Returns the last modified time as a Unix timestamp on success, or -1 on error.

Examples

Example 1. ftp_mdtm() example

<?php

$file = 'somefile.txt';

// 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);

//  get the last modified time
$buff = ftp_mdtm($conn_id, $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($conn_id);

?>

ftp_mkdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_mkdir -- Creates a directory

Description

string ftp_mkdir ( resource ftp_stream, string directory )

Creates the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The name of the directory that will be created.

Return Values

Returns the newly created directory name on success or FALSE on error.

Examples

Example 1. ftp_mkdir() example

<?php

$dir = 'www';

// 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 create the directory $dir
if (ftp_mkdir($conn_id, $dir)) {
 echo "successfully created $dir\n";
} else {
 echo "There was a problem while creating $dir\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

ftp_rmdir()

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)

Description

int ftp_nb_continue ( resource ftp_stream )

Continues retrieving/sending a file non-blocking.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example 1. ftp_nb_continue() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Description

int ftp_nb_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos] )

ftp_nb_fget() retrieves a remote file from the FTP server.

The difference between this function and ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example 1. ftp_nb_fget() example

<?php

// open some file for reading
$file = 'index.php';
$fp = fopen($file, 'w');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the download
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)

Description

int ftp_nb_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos] )

ftp_nb_fput() uploads the data from a file pointer to a remote file on the FTP server.

The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

handle

An open file pointer on the local file. Reading stops at end of file.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example 1. ftp_nb_fput() example

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Description

int ftp_nb_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos] )

ftp_nb_get() retrieves a remote file from the FTP server, and saves it into a local file.

The difference between this function and ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example 1. ftp_nb_get() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example 2. Resuming a download with ftp_nb_get()

<?php

// Initate 
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY, 
                      filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README", 
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example 3. Resuming a download at position 100 to a new file with ftp_nb_get()

<?php

// Disable Autoseek
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Initiate
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */
   
   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
?>

In the example above, newfile is 100 bytes smaller than README on the FTP server because we started reading at offset 100. If we didn't disable FTP_AUTOSEEK, the first 100 bytes of newfile would be '\0'.

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_put -- Stores a file on the FTP server (non-blocking)

Description

int ftp_nb_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

ftp_nb_put() stores a local file on the FTP server.

The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

local_file

The local file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example 1. ftp_nb_put() example

<?php

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Example 2. Resuming an upload with ftp_nb_put()

<?php

// Initiate
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

ftp_nlist

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_nlist -- Returns a list of files in the given directory

Description

array ftp_nlist ( resource ftp_stream, string directory )

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to be listed. This parameter can also include arguments, eg. ftp_nlist($conn_id, "-la /your/dir"); Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns an array of filenames from the specified directory on success or FALSE on error.

Examples

Example 1. ftp_nlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

See Also

ftp_rawlist()

ftp_pasv

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_pasv -- Turns passive mode on or off

Description

bool ftp_pasv ( resource ftp_stream, bool pasv )

ftp_pasv() turns on or off passive mode. In passive mode, data connections are initiated by the client, rather than by the server. It may be needed if the client is behind firewall.

Parameters

ftp_stream

The link identifier of the FTP connection.

pasv

If TRUE, the passive mode is turned on, else it's turned off.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_pasv() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// 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);

// turn passive mode on
ftp_pasv($conn_id, true);

// upload a file
if (ftp_put($conn_id, $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($conn_id);
?>

ftp_put

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_put -- Uploads a file to the FTP server

Description

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

ftp_put() stores a local file on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

local_file

The local file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_put() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// 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";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

ChangeLog

VersionDescription
4.3.0 startpos was added.

ftp_pwd

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_pwd -- Returns the current directory name

Description

string ftp_pwd ( resource ftp_stream )

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the current directory name or FALSE on error.

Examples

Example 1. ftp_pwd() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change directory to public_html
ftp_chdir($conn_id, 'public_html');

// print current directory
echo ftp_pwd($conn_id); // /public_html

// close the connection
ftp_close($conn_id);
?>

ftp_quit

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_quit -- Alias of ftp_close()

Description

This function is an alias of: ftp_close().

ftp_raw

(PHP 5)

ftp_raw -- Sends an arbitrary command to an FTP server

Description

array ftp_raw ( resource ftp_stream, string command )

Sends an arbitrary command to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns the server's response as an array of strings. No parsing is performed on the response string, nor does ftp_raw() determine if the command succeeded.

Examples

Example 1. Using ftp_raw() to login to an FTP server manually.

<?php
$fp = ftp_connect("ftp.example.com");

/* This is the same as: 
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

See Also

ftp_exec()

ftp_rawlist

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rawlist -- Returns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource ftp_stream, string directory [, bool recursive] )

ftp_rawlist() executes the FTP LIST command, and returns the result as an array.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory path.

recursive

If set to TRUE, the issued command will be LIST -R.

Return Values

Returns an array where each element corresponds to one line of text.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Examples

Example 1. ftp_rawlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the file list for /
$buff = ftp_rawlist($conn_id, '/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

The above example will output something similar to:

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"
}

ChangeLog

VersionDescription
4.3.0 recursive was added.

See Also

ftp_nlist()

ftp_rename

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rename -- Renames a file or a directory on the FTP server

Description

bool ftp_rename ( resource ftp_stream, string oldname, string newname )

ftp_rename() renames a file or a directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

oldname

The old file/directory name.

newname

The new name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_rename() example

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// 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 rename $old_file to $new_file
if (ftp_rename($conn_id, $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($conn_id);
?>

ftp_rmdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rmdir -- Removes a directory

Description

bool ftp_rmdir ( resource ftp_stream, string directory )

Removes the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to delete. This must be either an absolute or relative path to an empty directory.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. ftp_rmdir() example

<?php

$dir = 'www/';

// 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 delete the directory $dir
if (ftp_rmdir($conn_id, $dir)) {
    echo "Successfully deleted $dir\n";
} else {
    echo "There was a problem while deleting $dir\n";
}

ftp_close($conn_id);

?>

See Also

ftp_mkdir()

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_set_option -- Set miscellaneous runtime FTP options

Description

bool ftp_set_option ( resource ftp_stream, int option, mixed value )

This function controls various runtime options for the specified FTP stream.

Parameters

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Table 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.

value

This parameter depends on which option is chosen to be altered.

Return Values

Returns TRUE if the option could be set; FALSE if not. A warning message will be thrown if the option is not supported or the passed value doesn't match the expected value for the given option.

Examples

Example 1. ftp_set_option() example

<?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

ftp_site

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

ftp_site -- Sends a SITE command to the server

Description

bool ftp_site ( resource ftp_stream, string command )

ftp_site() sends the given SITE command to the FTP server.

SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The SITE command. Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Sending a SITE command to an ftp server

<?php
/* Connect to FTP server */
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Unable to connect to ftp.example.com');

/* Login as "user" with password "pass" */
if (!ftp_login($conn, 'user', 'pass')) die('Error logging into ftp.example.com');

/* Issue: "SITE CHMOD 0600 /home/user/privatefile" command to ftp server */
if (ftp_site($conn, 'CHMOD 0600 /home/user/privatefile')) {
   echo "Command executed successfully.\n";
} else {
   die('Command failed.');
}
?>

See Also

ftp_raw()

ftp_size

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_size -- Returns the size of the given file

Description

int ftp_size ( resource ftp_stream, string remote_file )

ftp_size() returns the size of the given file in bytes.

Note: Not all servers support this feature.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file.

Return Values

Returns the file size on success, or -1 on error.

Examples

Example 1. ftp_size() example

<?php

$file = 'somefile.txt';

// 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);

// get the size of $file
$res = ftp_size($conn_id, $file);

if ($res != -1) {
    echo "size of $file is $res bytes";
} else {
    echo "couldn't get the size";
}

// close the connection
ftp_close($conn_id);

?>

See Also

ftp_rawlist()

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5)

ftp_ssl_connect -- Opens an Secure SSL-FTP connection

Description

resource ftp_ssl_connect ( string host [, int port [, int timeout]] )

ftp_ssl_connect() opens a SSL-FTP connection to the specified host.

Why this function may not exist: ftp_ssl_connect() is only available if OpenSSL support is enabled into your version of PHP. If it's undefined and you've compiled FTP support then this is why. For Windows you must compile your own PHP binaries to support this function.

Parameters

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns a SSL-FTP stream on success or FALSE on error.

ChangeLog

VersionDescription
5.2.2 The function was changed to return FALSE when it can't use an SSL connection, instead of fallbacking to a non-SSL one as previously.

Examples

Example 1. ftp_ssl_connect() example

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

See Also

ftp_connect()

ftp_systype

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_systype -- Returns the system type identifier of the remote FTP server

Description

string ftp_systype ( resource ftp_stream )

Returns the system type identifier of the remote FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the remote system type, or FALSE on error.

Examples

Example 1. ftp_systype() example

<?php

// ftp connection
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// get the system type
if ($type = ftp_systype($ftp)) {
    echo "Example.com is powered by $type\n";
} else {
    echo "Couldn't get the systype";
}

?>

The above example will output something similar to:

Example.com is powered by UNIX

XLVII. Function Handling Functions

Introduction

These functions all handle various operations involved in working with functions.


Requirements

No external libraries are needed to build this extension.


Installation

There is no installation needed to use these functions; they are part of the PHP core.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Predefined Constants

This extension has no constants defined.

Table of Contents
call_user_func_array -- Call a user function given with an array of parameters
call_user_func -- Call a user function given by the first parameter
create_function -- Create an anonymous (lambda-style) function
func_get_arg -- Return an item from the argument list
func_get_args -- Returns an array comprising a function's argument list
func_num_args -- Returns the number of arguments passed to the function
function_exists -- Return TRUE if the given function has been defined
get_defined_functions -- Returns an array of all defined functions
register_shutdown_function -- Register a function for execution on shutdown
register_tick_function -- Register a function for execution on each tick
unregister_tick_function -- De-register a function for execution on each tick

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array -- Call a user function given with an array of parameters

Description

mixed call_user_func_array ( callback function, array param_arr )

Call a user defined function with the parameters in param_arr.

Parameters

function

The function to be called.

param_arr

The parameters to be passed to the function, as an indexed array.

Return Values

Returns the function result, or FALSE on error.

Examples

Example 1. call_user_func_array() example

<?php
function debug($var, $val)
{
    echo "***DEBUGGING\nVARIABLE: $var\nVALUE:";
    if (is_array($val) || is_object($val) || is_resource($val)) {
        print_r($val);
    } else {
        echo "\n$val\n";
    }
    echo "***\n";
}

$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array('debug', array("host", $host));
call_user_func_array('debug', array("c", $c));
call_user_func_array('debug', array("_POST", $_POST));
?>

See Also

call_user_func()
information about the callback type

call_user_func

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

call_user_func -- Call a user function given by the first parameter

Description

mixed call_user_func ( callback function [, mixed parameter [, mixed ...]] )

Call a user defined function given by the function parameter.

Parameters

function

The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter.

parameter

Zero or more parameters to be passed to the function.

Note: Note that the parameters for call_user_func() are not passed by reference.

<?php
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a; // 0

call_user_func_array('increment', array(&$a)); // You can use this instead
echo $a; // 1
?>

Return Values

Returns the function result, or FALSE on error.

Examples

Example 1. call_user_func() example

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

Example 2. Using a class method

<?php
class myclass {
    function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
?>

See Also

call_user_func_array()
is_callable()
information about the callback type

create_function

(PHP 4 >= 4.0.1, PHP 5)

create_function -- Create an anonymous (lambda-style) function

Description

string create_function ( string args, string code )

Creates an anonymous function from the parameters passed, and returns a unique name for it.

Parameters

Usually these parameters will be passed as single quote delimited strings. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

args

The function arguments.

code

The function code.

Return Values

Returns a unique function name as a string, or FALSE on error.

Examples

Example 1. Creating an anonymous function with create_function()

You can use this function, to (for example) create a function from information gathered at run time:

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Example 2. Making a general processing function with create_function()

<?php
function process($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . " , ".crc32(b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

The above example will output:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Example 3. Using anonymous functions as callback functions

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>

The above example will output:

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

an array of strings ordered from shorter to longer

<?php

$sv = array("small", "larger", "a big string", "it is a string thing");
print_r($sv);

?>

The above example will output:

Array
(
  [0] => small
  [1] => larger
  [2] => a big string
  [3] => it is a string thing
)

sort it from longer to shorter

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

The above example will output:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

func_get_arg

(PHP 4, PHP 5)

func_get_arg -- Return an item from the argument list

Description

mixed func_get_arg ( int arg_num )

Gets the specified argument from a user-defined function's argument list.

This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Parameters

arg_num

The argument offset. Function arguments are counted starting from zero.

Return Values

Returns the specified argument, or FALSE on error.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function, or if arg_num is greater than the number of arguments actually passed.

Examples

Example 1. func_get_arg() example

<?php
function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br />\n";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "<br />\n";
     }
}

foo (1, 2, 3);
?>

Notes

Note: 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.

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

func_get_args

(PHP 4, PHP 5)

func_get_args -- Returns an array comprising a function's argument list

Description

array func_get_args ( void )

Gets an array of the function's argument list.

This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Return Values

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function.

Examples

Example 1. func_get_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

Notes

Note: 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.

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

func_num_args

(PHP 4, PHP 5)

func_num_args -- Returns the number of arguments passed to the function

Description

int func_num_args ( void )

Gets the number of arguments passed to the function.

This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Return Values

Returns the number of arguments passed into the current user-defined function.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function.

Examples

Example 1. func_num_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);    // Prints 'Number of arguments: 3'
?>

Notes

Note: 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.

function_exists

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

function_exists -- Return TRUE if the given function has been defined

Description

bool function_exists ( string function_name )

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name.

Parameters

function_name

The function name, as a string.

Return Values

Returns TRUE if function_name exists and is a function, FALSE otherwise.

Note: This function will return FALSE for constructs, such as include_once() and echo().

Examples

Example 1. function_exists() example

<?php
if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br />\n";
} else {
    echo "IMAP functions are not available.<br />\n";
}
?>

Notes

Note: A function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example).

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5)

get_defined_functions -- Returns an array of all defined functions

Description

array get_defined_functions ( void )

Gets an array of all defined functions.

Return Values

Returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

Examples

Example 1. get_defined_functions() example

<?php
function myrow($id, $data)
{
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

The above example will output something similar to:

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
        )

)

register_shutdown_function

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

register_shutdown_function -- Register a function for execution on shutdown

Description

void register_shutdown_function ( callback function [, mixed parameter [, mixed ...]] )

Registers the function named by function to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

In PHP 4.0.6 and earlier under Apache, the registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents(). Since PHP 4.1, the shutdown functions are called as the part of the request so that it's possible to send the output from them. There is currently no way to process the data with output buffering functions in the shutdown function. 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.

As of PHP 4, it is possible to pass parameters to the shutdown function by passing additional parameters to register_shutdown_function().

Parameters

function

parameter

...

Return Values

No value is returned.

Notes

Note: Typically undefined functions cause fatal errors in PHP, but when the function called with register_shutdown_function() is undefined, an error of level E_WARNING is generated instead. Also, for reasons internal to PHP, this error will refer to Unknown at line #0.

Note: Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

Note: Shutdown function is called during the script shutdown so headers are always already sent.

register_tick_function

(PHP 4 >= 4.0.3, PHP 5)

register_tick_function -- Register a function for execution on each tick

Description

bool register_tick_function ( callback function [, mixed arg [, mixed ...]] )

Registers the given function to be executed when a tick is called.

Parameters

function

The function name as a string, or an array consisting of an object and a method.

arg

...

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. register_tick_function() example

<?php
// 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);
?>

Notes

Warning

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.

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5)

unregister_tick_function -- De-register a function for execution on each tick

Description

void unregister_tick_function ( string function_name )

De-registers the function named by function_name so it is no longer executed when a tick is called.

Parameters

function_name

The function name, as a string.

Return Values

No value is returned.

XLVIII. GeoIP Functions

Introduction

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.


Requirements

This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from http://www.maxmind.com/app/c and compile it yourself.

By default, you will only have access to the Free GeoIP Country or GeoLite City databases. While this module can work with other types of database, you must buy a commercial license from Maxmind.


Installation

This PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/geoip.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GEOIP_COUNTRY_EDITION (integer)

GEOIP_REGION_EDITION_REV0 (integer)

GEOIP_CITY_EDITION_REV0 (integer)

GEOIP_ORG_EDITION (integer)

GEOIP_ISP_EDITION (integer)

GEOIP_CITY_EDITION_REV1 (integer)

GEOIP_REGION_EDITION_REV1 (integer)

GEOIP_PROXY_EDITION (integer)

GEOIP_ASNUM_EDITION (integer)

GEOIP_NETSPEED_EDITION (integer)

GEOIP_DOMAIN_EDITION (integer)

The following constants are for net speed:

GEOIP_UNKNOWN_SPEED (integer)

GEOIP_DIALUP_SPEED (integer)

GEOIP_CABLEDSL_SPEED (integer)

GEOIP_CORPORATE_SPEED (integer)

Table of Contents
geoip_country_code_by_name -- Get the two letter country code
geoip_country_code3_by_name -- Get the three letter country code
geoip_country_name_by_name -- Get the full country name
geoip_database_info -- Get GeoIP Database information
geoip_id_by_name -- Get the Internet connection speed
geoip_org_by_name -- Get the organization name
geoip_record_by_name -- Returns the detailed City information found in the GeoIP Database
geoip_region_by_name -- Get the country code and region

geoip_country_code_by_name

(no version information, might be only in CVS)

geoip_country_code_by_name -- Get the two letter country code

Description

string geoip_country_code_by_name ( string hostname )

The geoip_country_code_by_name() function will return the two letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_country_code_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: US

geoip_country_code3_by_name

(no version information, might be only in CVS)

geoip_country_code3_by_name -- Get the three letter country code

Description

string geoip_country_code3_by_name ( string hostname )

The geoip_country_code3_by_name() function will return the three letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_country_code3_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: USA

geoip_country_name_by_name

(no version information, might be only in CVS)

geoip_country_name_by_name -- Get the full country name

Description

string geoip_country_name_by_name ( string hostname )

The geoip_country_name_by_name() function will return the full country name corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the country name on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_country_name_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: United States

geoip_database_info

(no version information, might be only in CVS)

geoip_database_info -- Get GeoIP Database information

Description

string geoip_database_info ( [int database] )

The geoip_database_info() function returns the corresponding GeoIP Database version as it is defined inside the binary file.

If this function is called without arguments, it returns the version of the GeoIP Free Country Edition.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns the corresponding database version, or NULL on error.

Examples

Example 1. A geoip_region_by_name() example

This will output the current database version string.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_id_by_name

(no version information, might be only in CVS)

geoip_id_by_name -- Get the Internet connection speed

Description

int geoip_id_by_name ( string hostname )

The geoip_id_by_name() function will return the country and region corresponding to a hostname or an IP address.

The return value is numeric and can be compared to the following constants:

  • GEOIP_UNKNOWN_SPEED

  • GEOIP_DIALUP_SPEED

  • GEOIP_CABLEDSL_SPEED

  • GEOIP_CORPORATE_SPEED

Parameters

hostname

The hostname or IP address whose net speed is to be looked-up.

Return Values

Returns the net speed.

Examples

Example 1. A geoip_id_by_name() example

This will output the net speed of the host 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 above example will output:

The connection type is corporate

geoip_org_by_name

(no version information, might be only in CVS)

geoip_org_by_name -- Get the organization name

Description

string geoip_org_by_name ( string hostname )

The geoip_org_by_name() function will return the name of the organization that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_org_by_name() example

This will print to whom the host example.com IP is allocated.

<?php
$org = geoip_country_code_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?>

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

geoip_record_by_name

(no version information, might be only in CVS)

geoip_record_by_name -- Returns the detailed City information found in the GeoIP Database

Description

array geoip_record_by_name ( string hostname )

The geoip_record_by_name() function will return the record information corresponding to a hostname or an IP address.

This function is available for both GeoLite City Edition and commercial GeoIP City Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "country_code" -- Two letter country code (see geoip_country_code_by_name())

  • "region" -- The region code (ex: CA for California)

  • "city" -- The city.

  • "postal_code" -- The Postal Code, FSA or Zip Code.

  • "latitude" -- The Latitude as signed double.

  • "longitude" -- The Longitude as signed double.

  • "dma_code"

  • "area_code" -- The PSTN area code (ex: 212)

Parameters

hostname

The hostname or IP address whose record is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_record_by_name() example

This will print the array containing the record of host example.com.

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?>

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] => 
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)

geoip_region_by_name

(no version information, might be only in CVS)

geoip_region_by_name -- Get the country code and region

Description

array geoip_region_by_name ( string hostname )

The geoip_region_by_name() function will return the country and region corresponding to a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Region Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

Parameters

hostname

The hostname or IP address whose region is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Examples

Example 1. A geoip_region_by_name() example

This will print the array containing the country code and region of the host example.com.

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?>

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
)

XLIX. Gettext Functions

Introduction

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at http://www.gnu.org/software/gettext/manual/gettext.html.


Requirements

To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html


Installation

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.

Table of Contents
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
bindtextdomain -- Sets the path for a domain
dcgettext -- Overrides the domain for a single lookup
dcngettext -- Plural version of dcgettext
dgettext -- Override the current domain
dngettext -- Plural version of dgettext
gettext -- Lookup a message in the current domain
ngettext -- Plural version of gettext
textdomain -- Sets the default domain

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5)

bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string domain, string codeset )

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

Parameters

domain

The domain

codeset

The code set

Return Values

A string on success.

bindtextdomain

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

bindtextdomain -- Sets the path for a domain

Description

string bindtextdomain ( string domain, string directory )

The bindtextdomain() function sets the path for a domain.

Parameters

domain

The domain

directory

The directory path

Return Values

The full pathname for the domain currently being set.

Examples

Example 1. bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

The above example will output:

/usr/share/myapp/locale

dcgettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

dcgettext -- Overrides the domain for a single lookup

Description

string dcgettext ( string domain, string message, int category )

This function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

category

The category

Return Values

A string on success.

See Also

gettext()

dcngettext

(PHP 4 >= 4.2.0, PHP 5)

dcngettext -- Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category )

This function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

category

Return Values

A string on success.

See Also

ngettext()

dgettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

dgettext -- Override the current domain

Description

string dgettext ( string domain, string message )

The dgettext() function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

Return Values

A string on success.

See Also

gettext()

dngettext

(PHP 4 >= 4.2.0, PHP 5)

dngettext -- Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n )

The dngettext() function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

Return Values

A string on success.

See Also

ngettext()

gettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

gettext -- Lookup a message in the current domain

Description

string gettext ( string message )

Looks up a message in the current domain.

Parameters

message

Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Examples

Example 1. gettext()-check

<?php
// Set language to German
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");
?>

Notes

Note: You may use the underscore character '_' as an alias to this function.

See Also

setlocale()

ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n )

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parameters

msgid1

msgid2

n

Return Values

Returns correct plural form of message identified by msgid1 and msgid2 for count n.

Examples

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

?>

textdomain

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

textdomain -- Sets the default domain

Description

string textdomain ( string text_domain )

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parameters

text_domain

The new message domain, or NULL to get the current setting without changing it

Return Values

If successful, this function returns the current message domain, after possibly changing it.

L. GMP Functions

Introduction

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Note: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Warning

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Note: This extension is available on Windows platforms since PHP 5.1.0.


Requirements

You can download the GMP library from http://www.swox.com/gmp/. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.


Installation

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

Most GPM functions operate on or return GMP number resources.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)

GMP_VERSION (string)

The GMP library version


Examples

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.


See Also

More mathematical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.

Table of Contents
gmp_abs -- Absolute value
gmp_add -- Add numbers
gmp_and -- Logical AND
gmp_clrbit -- Clear bit
gmp_cmp -- Compare numbers
gmp_com -- Calculates one's complement
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 -- Alias of gmp_div_q()
gmp_divexact -- Exact division of numbers
gmp_fact -- Factorial
gmp_gcd -- Calculate GCD
gmp_gcdext -- Calculate GCD and multipliers
gmp_hamdist -- Hamming distance
gmp_init -- Create GMP number
gmp_intval -- Convert GMP number to integer
gmp_invert -- Inverse by modulo
gmp_jacobi -- Jacobi symbol
gmp_legendre -- Legendre symbol
gmp_mod -- Modulo operation
gmp_mul -- Multiply numbers
gmp_neg -- Negate number
gmp_nextprime -- Find next prime number
gmp_or -- Logical OR
gmp_perfect_square -- Perfect square check
gmp_popcount -- Population count
gmp_pow -- Raise number into power
gmp_powm -- Raise number into power with modulo
gmp_prob_prime -- Check if number is "probably prime"
gmp_random -- Random number
gmp_scan0 -- Scan for 0
gmp_scan1 -- Scan for 1
gmp_setbit -- Set bit
gmp_sign -- Sign of number
gmp_sqrt -- 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 -- Logical XOR

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs -- Absolute value

Description

resource gmp_abs ( resource a )

Returns absolute value of a.

Example 1. gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

The printout of the above program will be:

274982683358
274982683358

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add -- Add numbers

Description

resource gmp_add ( resource a, resource b )

Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.

Example 1. gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

The printout of the above program will be:

200000000000000

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and -- Logical AND

Description

resource gmp_and ( resource a, resource b )

Calculates logical AND of two GMP numbers.

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";
?>

The printout of the above program will be:

4
0

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit -- Clear bit

Description

void gmp_clrbit ( resource &a, int index )

Clears (sets to 0) bit index in a. The index starts at 0.

Note: Unlike most of the other GMP functions, gmp_clrbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

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";
?>

The printout of the above program will be:

254

See also gmp_setbit() and gmp_testbit().

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp -- Compare numbers

Description

int gmp_cmp ( resource a, resource b )

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";
?>

The printout of the above program will be:

1 -1 0

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com -- Calculates one's complement

Description

resource gmp_com ( resource a )

Returns the one's complement of a.

Example 1. gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

The printout of the above program will be:

-1235

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q -- Divide numbers

Description

resource gmp_div_q ( resource a, resource b [, int round] )

Divides a by b and returns the integer result. The result rounding is defined by the round, which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.

  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.

  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

This function can also be called as gmp_div().

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";
?>

The printout of the above program will be:

20
0
1
0
-1

See also gmp_div_r(), gmp_div_qr()

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_qr -- Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource n, resource d [, int round] )

The function divides n by d and returns array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

See the gmp_div_q() function for description of the round argument.

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]));
?>

See also gmp_div_q(), gmp_div_r().

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r -- Remainder of the division of numbers

Description

resource gmp_div_r ( resource n, resource d [, int round] )

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

Example 1. gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

The printout of the above program will be:

5

See the gmp_div_q() function for description of the round argument.

See also gmp_div_q(), gmp_div_qr()

gmp_div

(PHP 4 >= 4.0.4, PHP 5)

gmp_div -- Alias of gmp_div_q()

Description

This function is an alias of: gmp_div_q().

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact -- Exact division of numbers

Description

resource gmp_divexact ( resource n, resource d )

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

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";
?>

The printout of the above program will be:

5
2863311534

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact -- Factorial

Description

resource gmp_fact ( int a )

Calculates factorial (a!) of a.

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";
?>

The printout of the above program will be:

120
30414093201713378043612608166064768844377641568960512000000000000

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd -- Calculate GCD

Description

resource gmp_gcd ( resource a, resource b )

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Example 1. gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

The printout of the above program will be:

3

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext -- Calculate GCD and multipliers

Description

array gmp_gcdext ( resource a, resource b )

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

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

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
?>

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist -- Hamming distance

Description

int gmp_hamdist ( resource a, resource b )

Returns the hamming distance between a and b. Both operands should be non-negative.

Example 1. gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

The printout of the above program will be:

6
6

See also gmp_popcount(), gmp_xor()

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init -- Create GMP number

Description

resource gmp_init ( mixed number [, int base] )

Creates a GMP number from an integer or string. String representation can be decimal, hexadecimal or octal. Optional parameter base is available since PHP 4.1.0. Its default value is 0.

The base may vary from 2 to 36. 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, otherwise if the first character is "0", octal is assumed, otherwise decimal is assumed.

Example 1. Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Note: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval -- Convert GMP number to integer

Description

int gmp_intval ( resource gmpnumber )

This function allows to convert GMP number to integer.

Warning

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

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";
?>

The printout of the above program will be:

2147483647
2147483647
2147483648

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert -- Inverse by modulo

Description

resource gmp_invert ( resource a, resource b )

Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.

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";
?>

The printout of the above program will be:

9

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi -- Jacobi symbol

Description

int gmp_jacobi ( resource a, resource p )

Computes Jacobi symbol of a and p. p should be odd and must be positive.

Example 1. gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

The printout of the above program will be:

1
0

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre -- Legendre symbol

Description

int gmp_legendre ( resource a, resource p )

Compute the Legendre symbol of a and p. p should be odd and must be positive.

Example 1. gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

The printout of the above program will be:

1
0

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod -- Modulo operation

Description

resource gmp_mod ( resource n, resource d )

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Example 1. gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

The printout of the above program will be:

2

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul -- Multiply numbers

Description

resource gmp_mul ( resource a, resource b )

Multiplies a by b and returns the result.

Example 1. gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

The printout of the above program will be:

24691356000

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg -- Negate number

Description

resource gmp_neg ( resource a )

Returns -a.

Example 1. gmp_neg() example

<?php
$neg1 = gmp_neg("1"); 
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

The printout of the above program will be:

-1
1

gmp_nextprime

(no version information, might be only in CVS)

gmp_nextprime -- Find next prime number

Description

resource gmp_nextprime ( int a )

Return next prime number greater than a.

This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

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";
?>

The printout of the above program is:

11
-997

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or -- Logical OR

Description

resource gmp_or ( resource a, resource b )

Calculates logical inclusive OR of two GMP numbers.

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";
?>

The printout of the above program will be:

fffffff6
fffffff2

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square -- Perfect square check

Description

bool gmp_perfect_square ( resource a )

Returns TRUE if a 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"));
?>

The printout of the above program will be:

bool(true)
bool(false)
bool(true)

See also: gmp_sqrt(), gmp_sqrtrem().

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount -- Population count

Description

int gmp_popcount ( resource a )

Return the population count of a.

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";
?>

The printout of the above program will be:

3
7

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow -- Raise number into power

Description

resource gmp_pow ( resource base, int exp )

Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.

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";
?>

The printout of the above program will be:

2147483648
1

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm -- Raise number into power with modulo

Description

resource gmp_powm ( resource base, resource exp, resource mod )

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Example 1. gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

The printout of the above program will be:

2147483648

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5)

gmp_prob_prime -- Check if number is "probably prime"

Description

int gmp_prob_prime ( resource a [, int reps] )

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a is surely prime. Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

The function uses Miller-Rabin's probabilistic test.

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";
?>

The printout of the above program will be:

0
1
2

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random -- Random number

Description

resource gmp_random ( int limiter )

Generate a random number. The number will be between zero and 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 16 or 32, but this is not guaranteed.

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";
?>

The printout of the above program might be:

1915834968
8642564075890328087

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 -- Scan for 0

Description

int gmp_scan0 ( resource a, int start )

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit. 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";
?>

The printout of the above program will be:

3
7

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 -- Scan for 1

Description

int gmp_scan1 ( resource a, int start )

Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit. 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";
?>

The printout of the above program will be:

3
9

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit -- Set bit

Description

void gmp_setbit ( resource &a, int index [, bool set_clear] )

Sets bit index in a. set_clear defines if the bit is set to 0 or 1. By default the bit is set to 1. Index starts at 0.

Note: Unlike most of the other GMP functions, gmp_setbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

Example 1. gmp_setbit() example

<?php
$a = gmp_init("0xfd");
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a) . "\n";
?>

The printout of the above program will be:

255

See also gmp_clrbit() and gmp_testbit().

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign -- Sign of number

Description

int gmp_sign ( resource a )

Returns 1 if a is positive, -1 if a is negative, and 0 if a 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";
?>

The printout of the above program will be:

1
-1
0

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt -- Calculate square root

Description

resource gmp_sqrt ( resource a )

Calculates square root of a and returns the integer portion of the result.

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";
?>

The printout of the above program will be:

3
2
1234567890

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem --  Square root with remainder

Description

array gmp_sqrtrem ( resource a )

Returns array where first element is the integer square root of a (see also gmp_sqrt()), and the second is the remainder (i.e., the difference between a and the first element squared).

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";     
?>

The printout of the above program will be:

3, 0
2, 3
1024, 0

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval -- Convert GMP number to string

Description

string gmp_strval ( resource gmpnumber [, int base] )

Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.

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));
?>

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub -- Subtract numbers

Description

resource gmp_sub ( resource a, resource b )

Subtracts b from a and returns the result.

Example 1. gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

The printout of the above program will be:

281470681743360

gmp_testbit

(no version information, might be only in CVS)

gmp_testbit -- Tests if a bit is set

Description

bool gmp_testbit ( resource a, int index )

Tests if the specified bit is set.

Parameters

a

A GMP number resource

index

The bit to test

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

E_WARNING is issued when index is less than zero.

Examples

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));
?>

The above example will output:

bool(false)
bool(true)

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor -- Logical XOR

Description

resource gmp_xor ( resource a, resource b )

Calculates logical exclusive OR (XOR) of two GMP numbers.

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";
?>

The printout of the above program will be:

1011110111000100

LI. gnupg Functions

Introduction

This module allows you to interact with gnupg.


Requirements

The gnupg extension requires PHP 4.3. To use this extension in an OO style, PHP 5 is required.

This extension requires the gpgme library


Installation

The gnupg-extension is not bundled with PHP. It is a PECL extension and can be located here: http://pecl.php.net/package/gnupg.


Predefined Constants

GNUPG_SIG_MODE_NORMAL (integer)

GNUPG_SIG_MODE_DETACH (integer)

GNUPG_SIG_MODE_CLEAR (integer)

GNUPG_VALIDITY_UNKNOWN (integer)

GNUPG_VALIDITY_UNDEFINED (integer)

GNUPG_VALIDITY_NEVER (integer)

GNUPG_VALIDITY_MARGINAL (integer)

GNUPG_VALIDITY_FULL (integer)

GNUPG_VALIDITY_ULTIMATE (integer)

GNUPG_PROTOCOL_OpenPGP (integer)

GNUPG_PROTOCOL_CMS (integer)

GNUPG_SIGSUM_VALID (integer)

GNUPG_SIGSUM_GREEN (integer)

GNUPG_SIGSUM_RED (integer)

GNUPG_SIGSUM_KEY_REVOKED (integer)

GNUPG_SIGSUM_KEY_EXPIRED (integer)

GNUPG_SIGSUM_KEY_MISSING (integer)

GNUPG_SIGSUM_SIG_EXPIRED (integer)

GNUPG_SIGSUM_CRL_MISSING (integer)

GNUPG_SIGSUM_CRL_TOO_OLD (integer)

GNUPG_SIGSUM_BAD_POLICY (integer)

GNUPG_SIGSUM_SYS_ERROR (integer)

GNUPG_ERROR_WARNING (integer)

GNUPG_ERROR_EXCEPTION (integer)

GNUPG_ERROR_SILENT (integer)


Notes

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 an unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.


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";
}
?>


Examples

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;
?>
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_encrypt -- Encrypts a given text
gnupg_encryptsign -- Encrypts and signs a given text
gnupg_export -- Exports a key
gnupg_geterror -- Returns the errortext, if a function fails
gnupg_getprotocol -- Returns the currently active protocol for all operations
gnupg_import -- Imports a key
gnupg_keyinfo -- Returns an array with information about all keys that matches the given pattern
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

gnupg_adddecryptkey

(no version information, might be only in CVS)

gnupg_adddecryptkey -- Add a key for decryption

Description

bool gnupg_adddecryptkey ( resource identifier, string fingerprint, string passphrase )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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");
?>

gnupg_addencryptkey

(no version information, might be only in CVS)

gnupg_addencryptkey -- Add a key for encryption

Description

bool gnupg_addencryptkey ( resource identifier, string fingerprint )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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");
?>

gnupg_addsignkey

(no version information, might be only in CVS)

gnupg_addsignkey -- Add a key for signing

Description

bool gnupg_addsignkey ( resource identifier, string fingerprint [, string passphrase] )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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");
?>

gnupg_cleardecryptkeys

(no version information, might be only in CVS)

gnupg_cleardecryptkeys -- Removes all keys which were set for decryption before

Description

bool gnupg_cleardecryptkeys ( resource identifier )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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();
?>

gnupg_clearencryptkeys

(no version information, might be only in CVS)

gnupg_clearencryptkeys -- Removes all keys which were set for encryption before

Description

bool gnupg_clearencryptkeys ( resource identifier )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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();
?>

gnupg_clearsignkeys

(no version information, might be only in CVS)

gnupg_clearsignkeys -- Removes all keys which were set for signing before

Description

bool gnupg_clearsignkeys ( resource identifier )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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();
?>

gnupg_decrypt

(no version information, might be only in CVS)

gnupg_decrypt -- Decrypts a given text

Description

string gnupg_decrypt ( resource identifier, string text )

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

Return Values

On success, this function returns the decrypted text. On failure, this function returns FALSE.

Examples

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_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -> decrypt($encrypted_text);
echo $plain;
?>

gnupg_decryptverify

(no version information, might be only in CVS)

gnupg_decryptverify -- Decrypts and verifies a given text

Description

array gnupg_decryptverify ( resource identifier, string text, string &plaintext )

Decrypts and verifies a given text and returns information about the signature. The parameter plaintext gets filled with the decrypted text.

Return Values

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns FALSE.

Examples

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);
?>

gnupg_encrypt

(no version information, might be only in CVS)

gnupg_encrypt -- Encrypts a given text

Description

string gnupg_encrypt ( resource identifier, string plaintext )

Encrypts the given plaintext with the keys, which were set with gnupg_addencryptkey before and returns the encrypted text.

Return Values

On success, this function returns the encrypted text. On failure, this function returns FALSE.

Examples

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;
?>

gnupg_encryptsign

(no version information, might be only in CVS)

gnupg_encryptsign -- Encrypts and signs a given text

Description

string gnupg_encryptsign ( resource identifier, string plaintext )

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.

Return Values

On success, this function returns the encrypted and signed text. On failure, this function returns FALSE.

Examples

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;
?>

gnupg_export

(no version information, might be only in CVS)

gnupg_export -- Exports a key

Description

string gnupg_export ( resource identifier, string fingerprint )

Exports the key fingerprint.

Return Values

On success, this function returns the keydata. On failure, this function returns FALSE.

Examples

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");
?>

gnupg_geterror

(no version information, might be only in CVS)

gnupg_geterror -- Returns the errortext, if a function fails

Description

string gnupg_geterror ( resource identifier )

Return Values

Returns an errortext, if an error has occurred, otherwise FALSE.

Examples

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();
?>

gnupg_getprotocol

(no version information, might be only in CVS)

gnupg_getprotocol -- Returns the currently active protocol for all operations

Description

int gnupg_getprotocol ( resource identifier )

Return Values

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

Examples

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();
?>

gnupg_import

(no version information, might be only in CVS)

gnupg_import -- Imports a key

Description

array gnupg_import ( resource identifier, string keydata )

Imports the key keydata and returns an array with information about the importprocess.

Return Values

On success, this function returns and info-array about the importprocess. On failure, this function returns FALSE.

Examples

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);
?>

gnupg_keyinfo

(no version information, might be only in CVS)

gnupg_keyinfo -- Returns an array with information about all keys that matches the given pattern

Description

array gnupg_keyinfo ( resource identifier, string pattern )

Return Values

Returns an array with information about all keys that matches the given pattern or FALSE, if an error has occurred.

Examples

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);
?>

gnupg_setarmor

(no version information, might be only in CVS)

gnupg_setarmor -- Toggle armored output

Description

bool gnupg_setarmor ( resource identifier, int armor )

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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;
?>

gnupg_seterrormode

(no version information, might be only in CVS)

gnupg_seterrormode -- Sets the mode for error_reporting

Description

void gnupg_seterrormode ( resource identifier, int errormode )

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.

Return Values

No value is returned.

Examples

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
?>

gnupg_setsignmode

(no version information, might be only in CVS)

gnupg_setsignmode -- Sets the mode for signing

Description

bool gnupg_setsignmode ( resource identifier, int signmode )

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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
?>

gnupg_sign

(no version information, might be only in CVS)

gnupg_sign -- Signs a given text

Description

string gnupg_sign ( resource identifier, string plaintext )

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.

Return Values

On success, this function returns the signed text or the signature. On failure, this function returns FALSE.

Examples

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 -> setsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg -> sign("just a test");
echo $signed;
?>

gnupg_verify

(no version information, might be only in CVS)

gnupg_verify -- Verifies a signed text

Description

array gnupg_verify ( resource identifier, string signed_text, string signature [, string &plaintext] )

Verifies the given signed_text and returns information about the signature. To verify a clearsigned text, set signature to FALSE. If the optional parameter plaintext is passed, it is filled with the plaintext.

Return Values

On success, this function returns informations about the signature. On failure, this function returns FALSE.

Examples

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);
?>

LII. Net_Gopher

Introduction

The gopher protocol, as defined by RFC 1436, is generally considered the ancestor of the modern HTTP protocol. However, gopher was also intended to provide references to non-gopher resources including telnet, wais, nntp, and even http. This extension adds gopher support to PHP's URL Wrappers, and provides a helper function gopher_parsedir() to make sense of gopher formatted directory listings.


Installation

Prerequisite: PHP 4.3.0 or higher.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/net_gopher


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 1. Net_Gopher constants

ConstantValueDescription
GOPHER_DOCUMENT0Standard text/plain document.
GOPHER_DIRECTORY1A resource containing a gopher formatted directory listing.
GOPHER_BINHEX4A BinHex encoded binary file.
GOPHER_DOSBINARY5A DOS formatted binary archive.
GOPHER_UUENCODED6A UUEncoded file.
GOPHER_BINARY9A generic binary file.
GOPHER_INFO255An Informational entry
GOPHER_HTTP254A reference to an HTTP resource.
GOPHER_UNKNOWN-1 An unrecognized entry.

Examples

<?php
readfile("gopher://gopher.example.com/somedocument");
?>

Table of Contents
gopher_parsedir -- Translate a gopher formatted directory entry into an associative array.

gopher_parsedir

(PECL)

gopher_parsedir -- Translate a gopher formatted directory entry into an associative array.

Description

array gopher_parsedir ( string dirent )

gopher_parsedir() parses a gopher formatted directory entry into an associative array.

While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.

Parameters

dirent

The directory entry.

Return Values

Returns an associative array whose components are:

  • type - One of the GOPHER_XXX constants.

  • title - The name of the resource.

  • path - The path of the resource.

  • host - The domain name of the host that has this document (or directory).

  • port - The port at which to connect on host.

Upon failure, the additional data entry of the returned array will hold the parsed line.

Examples

Example 1. Hypothetical output from gopher://gopher.example.com/

0All about my gopher site.	/allabout.txt	gopher.example.com	70
9A picture of my cat.	/pics/cat.png	gopher.example.com	70
1A collection of my writings.	/stories	gopher.example.com	70
hThe HTTP version of this site.	URL:http://www.example.com	gopher.example.com	70
1Mirror of this site in Spain.	/	gopher.ejemplo.co.es	70
iWelcome to my gopher site.		error.host	1
iPlease select one of the options above		error.host	1
iSend complaints to /dev/null		error.host	1
iLong live gopher!		error.host	1

In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.

By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.

Example 2. Using gopher_parsedir()

<?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?>

The above example will output:

Array (
  [type] => 0
  [title] => All about my gopher site.
  [path] => /allabout.txt
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 9
  [title] => A picture of my cat.
  [path] => /pics/cat.png
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => A collection of my writings.
  [path] => /stories
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 254
  [title] => The HTTP version of this site.
  [path] => URL:http://www.example.com
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => Mirror of this site in Spain.
  [path] => /
  [host] => gopher.ejemplo.co.es
  [port] => 70
)
Array (
  [type] => 255
  [title] => Welcome to my gopher site.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Please select one of the options above.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Send complaints to /dev/null
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Long live gopher!
  [path] =>
  [host] => error.host
  [port] => 1
)

LIII. Haru PDF Functions

Introduction

The PECL/haru extension provides bindings for Haru Free PDF Library - free, cross platform, opensource software library for generating PDF files.

You can find the library here: http://libharu.sourceforge.net.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.


Requirements

You need to install libharu first to be able to use PECL/haru. PECL/haru is tested with libharu 2.0.8, older versions might or might not work for you. PECL/haru also requires PHP 5.1.3 or newer.


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/haru.

The latest PECL/haru Win32 DLL can be downloaded here: php_haru.dll.


Runtime Configuration

This extension has no configuration directives defined in php.ini.


Examples

Example 1. Basic PECL/haru example

<?php

$doc = new HaruDoc;

$doc->setPageMode(HaruDoc::PAGE_MODE_USE_THUMBS); /* show thumbnails */

$page = $doc->addPage(); /* add page to the document */
$page->setSize(HaruPage::SIZE_A4, HaruPage::LANDSCAPE); /* set the page to use A4 landscape format */

$courier = $doc->getFont("Courier-Bold"); /* we'll use the bundled font a few lines below */

$page->setRGBStroke(0, 0, 0); /* set colors */
$page->setRGBFill(0.7, 0.8, 0.9);
$page->rectangle(150, 150, 550, 250); /* draw a rectangle */

$page->fillStroke(); /* fill and stroke it */

$page->setDash(array(3, 3), 0); /* set dash style for lines at this page */
$page->setFontAndSize($courier, 60); /* set font and size */

$page->setRGBStroke(0.5, 0.5, 0.1); /* set line color */
$page->setRGBFill(1, 1, 1); /* set filling color */

$page->setTextRenderingMode(HaruPage::FILL_THEN_STROKE); /* fill and stroke text */

/* print the text */
$page->beginText();
$page->textOut(210, 270, "Hello World!");
$page->endText();

$doc->save("/tmp/test.pdf"); /* save the document into a file */

?>

Open the result document in your favourite PDF viewer and you should see a light-blue rectangle and white "Hello World!" on it.


Builtin Fonts And Encodings

Builtin Fonts

These Base14 fonts are built-in into PDF and all viewers can display them. Using these fonts may decrease the size of the result file and make the processing faster, avoiding loading external fonts. However the fonts support only latin1 character set and you have to load external fonts if you need to use an other character set.

The Base14 fonts:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats


Builtin Encodings

Table 1. Single-byte character set encodings

NameDescription
StandardEncoding The default encoding of PDF.
MacRomanEncoding The standard encoding of Mac OS.
WinAnsiEncoding The standard encoding of Windows.
FontSpecific The font built-in encoding.
ISO8859-2 Latin2 (East European)
ISO8859-3 Latin3 (South European)
ISO8859-4 Latin4 (North European)
ISO8859-5 Cyrillic
ISO8859-6 Arabic
ISO8859-7 Greek
ISO8859-8 Hebrew
ISO8859-9 Latin5 (Turkish)
ISO8859-10 Latin6 (Nordic)
ISO8859-11 Thai
ISO8859-13 Latin7 (Baltic Rim)
ISO8859-14 Latin8 (Celtic)
ISO8859-15 Latin9
ISO8859-16 Latin10
CP1250 MS Windows Codepage 1250.
CP1251 MS Windows Codepage 1251.
CP1252 MS Windows Codepage 1252.
CP1253 MS Windows Codepage 1253.
CP1254 MS Windows Codepage 1254.
CP1255 MS Windows Codepage 1255.
CP1256 MS Windows Codepage 1256.
CP1257 MS Windows Codepage 1257.
CP1258 MS Windows Codepage 1258.
KOI8-R Cyrillic character set.

Table 2. Multi-byte character set encodings

NameDescription
GB-EUC-H EUC-CN encoding.
GB-EUC-V Vertical writing version of GB-EUC-H.
GBK-EUC-H Microsoft Code Page 936 (lfCharSet 0x86) GBK encoding.
GBK-EUC-V Vertical writing version of GBK-EUC-H.
ETen-B5-H Microsoft Code Page 950 (lfCharSet 0x88) Big Five character set with ETen extensions.
ETen-B5-V Vertical writing version of ETen-B5-H.
90ms-RKSJ-H Microsoft Code Page 932, JIS X 0208 character.
90ms-RKSJ-V Vertical writing version of 90ms-RKSJ-V.
90msp-RKSJ-H Microsoft Code Page 932, JIS X 0208 character (proportional).
EUC-H JIS X 0208 character set, EUC-JP encoding.
EUC-V Vertical writing version of EUC-H.
KSC-EUC-H KS X 1001:1992 character set, EUC-KR encoding.
KSC-EUC-V Vertical writing version of KSC-EUC-V.
KSCms-UHC-H Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (proportional).
KSCms-UHC-HW-H Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (fixed width).
KSCms-UHC-HW-V Vertical writing version of KSCms-UHC-HW-H.
Table of Contents
HaruException -- Haru PDF Exception Class
HaruDoc -- Haru PDF Document Class
HaruPage -- Haru PDF Page Class
HaruFont -- Haru PDF Font Class
HaruImage -- Haru PDF Image Class
HaruEncoder -- Haru PDF Encoder Class
HaruOutline -- Haru PDF Outline Class
HaruAnnotation -- Haru PDF Annotation Class
HaruDestination -- Haru PDF Destination Class
HaruAnnotation::setBorderStyle -- Set the border style of the annotation
HaruAnnotation::setHighlightMode -- Set the highlighting mode of the annotation
HaruAnnotation::setIcon -- Set the icon style of the annotation
HaruAnnotation::setOpened -- Set the initial state of the annotation
HaruDestination::setFit -- Set the appearance of the page to fit the window
HaruDestination::setFitB -- Set the appearance of the page to fit the bounding box of the page within the window
HaruDestination::setFitBH -- Set the appearance of the page to fit the width of the bounding box
HaruDestination::setFitBV -- Set the appearance of the page to fit the height of the boudning box
HaruDestination::setFitH -- Set the appearance of the page to fit the window width
HaruDestination::setFitR -- Set the appearance of the page to fit the specified rectangle
HaruDestination::setFitV -- Set the appearance of the page to fit the window height
HaruDestination::setXYZ -- Set the appearance of the page
HaruDoc::addPage -- Add new page to the document
HaruDoc::addPageLabel -- Set the numbering style for the specified range of pages
HaruDoc::__construct -- Construct new HaruDoc instance
HaruDoc::createOutline -- Create a HaruOutline instance
HaruDoc::getCurrentEncoder -- Get HaruEncoder currently used in the document
HaruDoc::getCurrentPage -- Return current page of the document
HaruDoc::getEncoder -- Get HaruEncoder instance for the specified encoding
HaruDoc::getFont -- Get HaruFont instance
HaruDoc::getInfoAttr -- Get current value of the specified document attribute
HaruDoc::getPageLayout -- Get current page layout
HaruDoc::getPageMode -- Get current page mode
HaruDoc::getStreamSize -- Get the size of the temporary stream
HaruDoc::insertPage -- Insert new page just before the specified page
HaruDoc::loadJPEG -- Load JPEG image and return new HaruImage instance
HaruDoc::loadPNG -- Load PNG image and return HaruImage instance
HaruDoc::loadRaw -- Load RAW image and return HaruImage instance
HaruDoc::loadTTC -- Load the font with the specified index from TTC file
HaruDoc::loadTTF -- Load TTF font file
HaruDoc::loadType1 -- Load Type1 font
HaruDoc::output -- Write the document data to the output buffer
HaruDoc::readFromStream -- Read data from the temporary stream
HaruDoc::resetError -- Reset error state of the document handle
HaruDoc::resetStream -- Rewind the temporary stream
HaruDoc::save -- Save the document into the specified file
HaruDoc::saveToStream -- Save the document into a temporary stream
HaruDoc::setCompressionMode -- Set compression mode for the document
HaruDoc::setCurrentEncoder -- Set the current encoder for the document
HaruDoc::setEncryptionMode -- Set encryption mode for the document
HaruDoc::setInfoAttr -- Set the info attribute of the document
HaruDoc::setInfoDateAttr -- Set the datetime info attributes of the document
HaruDoc::setOpenAction -- Define which page is shown when the document is opened
HaruDoc::setPageLayout -- Set how pages should be displayed
HaruDoc::setPageMode -- Set how the document should be displayed
HaruDoc::setPagesConfiguration -- Set the number of pages per set of pages
HaruDoc::setPassword -- Set owner and user passwords for the document
HaruDoc::setPermission -- Set permissions for the document
HaruDoc::useCNSEncodings -- Enable Chinese simplified encodings
HaruDoc::useCNSFonts -- Enable builtin Chinese simplified fonts
HaruDoc::useCNTEncodings -- Enable Chinese traditional encodings
HaruDoc::useCNTFonts -- Enable builtin Chinese traditional fonts
HaruDoc::useJPEncodings -- Enable Japanese encodings
HaruDoc::useJPFonts -- Enable builtin Japanese fonts
HaruDoc::useKREncodings -- Enable Korean encodings
HaruDoc::useKRFonts -- Enable builtin Korean fonts
HaruEncoder::getByteType -- Get the type of the byte in the text
HaruEncoder::getType -- Get the type of the encoder
HaruEncoder::getUnicode -- Convert the specified character to unicode
HaruEncoder::getWritingMode -- Get the writing mode of the encoder
HaruFont::getAscent -- Get the vertical ascent of the font
HaruFont::getCapHeight -- Get the distance from the baseline of uppercase letters
HaruFont::getDescent -- Get the vertical descent of the font
HaruFont::getEncodingName -- Get the name of the encoding
HaruFont::getFontName -- Get the name of the font
HaruFont::getTextWidth -- Get the total width of the text, number of characters, number of words and number of spaces
HaruFont::getUnicodeWidth -- Get the width of the character in the font
HaruFont::getXHeight -- Get the distance from the baseline of lowercase letters
HaruFont::measureText -- Calculate the number of characters which can be included within the specified width
HaruImage::getBitsPerComponent -- Get the number of bits used to describe each color component of the image
HaruImage::getColorSpace -- Get the name of the color space
HaruImage::getHeight -- Get the height of the image
HaruImage::getSize -- Get size of the image
HaruImage::getWidth -- Get the width of the image
HaruImage::setColorMask -- Set the color mask of the image
HaruImage::setMaskImage -- Set the image mask
HaruOutline::setDestination -- Set the destination for the outline
HaruOutline::setOpened -- Set the initial state of the outline
HaruPage::arc -- Append an arc to the current path
HaruPage::beginText -- Begin a text object and set the current text position to (0,0)
HaruPage::circle -- Append a circle to the current path
HaruPage::closePath -- Append a straight line from the current point to the start point of the path
HaruPage::concat -- Concatenate current transformation matrix of the page and the specified matrix
HaruPage::createDestination -- Create new HaruDestination instance
HaruPage::createLinkAnnotation -- Create new HaruAnnotation instance
HaruPage::createTextAnnotation -- Create new HaruAnnotation instance
HaruPage::createURLAnnotation -- Create and return new HaruAnnotation instance
HaruPage::curveTo2 -- Append a Bezier curve to the current path
HaruPage::curveTo3 -- Append a Bezier curve to the current path
HaruPage::curveTo -- Append a Bezier curve to the current path
HaruPage::drawImage -- Show image at the page
HaruPage::ellipse -- Append an ellipse to the current path
HaruPage::endPath -- End current path object without filling and painting operations
HaruPage::endText -- End current text object
HaruPage::eofill -- Fill current path using even-odd rule
HaruPage::eoFillStroke -- Fill current path using even-odd rule, then paint the path
HaruPage::fill -- Fill current path using nonzero winding number rule
HaruPage::fillStroke -- Fill current path using nonzero winding number rule, then paint the path
HaruPage::getCharSpace -- Get the current value of character spacing
HaruPage::getCMYKFill -- Get the current filling color
HaruPage::getCMYKStroke -- Get the current stroking color
HaruPage::getCurrentFont -- Get the currently used font
HaruPage::getCurrentFontSize -- Get the current font size
HaruPage::getCurrentPos -- Get the current position for path painting
HaruPage::getCurrentTextPos -- Get the current position for text printing
HaruPage::getDash -- Get the current dash pattern
HaruPage::getFillingColorSpace -- Get the current filling color space
HaruPage::getFlatness -- Get the flatness of the page
HaruPage::getGMode -- Get the current graphics mode
HaruPage::getGrayFill -- Get the current filling color
HaruPage::getGrayStroke -- Get the current stroking color
HaruPage::getHeight -- Get the height of the page
HaruPage::getHorizontalScaling -- Get the current value of horizontal scaling
HaruPage::getLineCap -- Get the current line cap style
HaruPage::getLineJoin -- Get the current line join style
HaruPage::getLineWidth -- Get the current line width
HaruPage::getMiterLimit -- Get the value of miter limit
HaruPage::getRGBFill -- Get the current filling color
HaruPage::getRGBStroke -- Get the current stroking color
HaruPage::getStrokingColorSpace -- Get the current stroking color space
HaruPage::getTextLeading -- Get the current value of line spacing
HaruPage::getTextMatrix -- Get the current text transformation matrix of the page
HaruPage::getTextRenderingMode -- Get the current text rendering mode
HaruPage::getTextRise -- Get the current value of text rising
HaruPage::getTextWidth -- Get the width of the text using current fontsize, character spacing and word spacing
HaruPage::getTransMatrix -- Get the current transformation matrix of the page
HaruPage::getWidth -- Get the width of the page
HaruPage::getWordSpace -- Get the current value of word spacing
HaruPage::lineTo -- Draw a line from the current point to the specified point
HaruPage::measureText -- Calculate the number of characters which can be included within the specified width
HaruPage::moveTextPos -- Move text position to the specified offset
HaruPage::moveTo -- Set starting point for new drawing path
HaruPage::moveToNextLine -- Move text position to the start of the next line
HaruPage::rectangle -- Append a rectangle to the current path
HaruPage::setCharSpace -- Set character spacing for the page
HaruPage::setCMYKFill -- Set filling color for the page
HaruPage::setCMYKStroke -- Set stroking color for the page
HaruPage::setDash -- Set the dash pattern for the page
HaruPage::setFlatness -- Set flatness for the page
HaruPage::setFontAndSize -- Set font and fontsize for the page
HaruPage::setGrayFill -- Set filling color for the page
HaruPage::setGrayStroke -- Sets stroking color for the page
HaruPage::setHeight -- Set height of the page
HaruPage::setHorizontalScaling -- Set horizontal scaling for the page
HaruPage::setLineCap -- Set the shape to be used at the ends of lines
HaruPage::setLineJoin -- Set line join style for the page
HaruPage::setLineWidth -- Set line width for the page
HaruPage::setMiterLimit -- Set the current value of the miter limit of the page
HaruPage::setRGBFill -- Set filling color for the page
HaruPage::setRGBStroke -- Set stroking color for the page
HaruPage::setRotate -- Set rotation angle of the page
HaruPage::setSize -- Set size and direction of the page
HaruPage::setSlideShow -- Set transition style for the page
HaruPage::setTextLeading -- Set text leading (line spacing) for the page
HaruPage::setTextMatrix -- Set the current text transformation matrix of the page
HaruPage::setTextRenderingMode -- Set text rendering mode for the page
HaruPage::setTextRise -- Set the current value of text rising
HaruPage::setWidth -- Set width of the page
HaruPage::setWordSpace -- Set word spacing for the page
HaruPage::showText -- Print text at the current position of the page
HaruPage::showTextNextLine -- Move the current position to the start of the next line and print the text
HaruPage::stroke -- Paint current path
HaruPage::textOut -- Print the text on the specified position
HaruPage::textRect -- Print the text inside the specified region

HaruException

(no version information, might be only in CVS)

HaruException -- Haru PDF Exception Class

Synopsis

class HaruException

Class Members

Methods

HaruDoc

(no version information, might be only in CVS)

HaruDoc -- Haru PDF Document Class

Synopsis

class HaruDoc

Class Members

Predefined Constants

Table 1.

TypeNameDescription
intHaruDoc::CS_DEVICE_GRAY 
intHaruDoc::CS_DEVICE_RGB 
intHaruDoc::CS_DEVICE_CMYK 
intHaruDoc::CS_CAL_GRAY 
intHaruDoc::CS_CAL_RGB 
intHaruDoc::CS_LAB 
intHaruDoc::CS_ICC_BASED 
intHaruDoc::CS_SEPARATION 
intHaruDoc::CS_DEVICE_N 
intHaruDoc::CS_INDEXED 
intHaruDoc::CS_PATTERN 
intHaruDoc::ENABLE_READ 
intHaruDoc::ENABLE_PRINT 
intHaruDoc::ENABLE_EDIT_ALL 
intHaruDoc::ENABLE_COPY 
intHaruDoc::ENABLE_EDIT 
intHaruDoc::ENCRYPT_R2 
intHaruDoc::ENCRYPT_R3 
intHaruDoc::INFO_AUTHOR 
intHaruDoc::INFO_CREATOR 
intHaruDoc::INFO_TITLE 
intHaruDoc::INFO_SUBJECT 
intHaruDoc::INFO_KEYWORDS 
intHaruDoc::INFO_CREATION_DATE 
intHaruDoc::INFO_MOD_DATE 
intHaruDoc::COMP_NONE 
intHaruDoc::COMP_TEXT 
intHaruDoc::COMP_IMAGE 
intHaruDoc::COMP_METADATA 
intHaruDoc::COMP_ALL 
intHaruDoc::PAGE_LAYOUT_SINGLE 
intHaruDoc::PAGE_LAYOUT_ONE_COLUMN 
intHaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT 
intHaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT 
intHaruDoc::PAGE_MODE_USE_NONE 
intHaruDoc::PAGE_MODE_USE_OUTLINE 
intHaruDoc::PAGE_MODE_USE_THUMBS 
intHaruDoc::PAGE_MODE_FULL_SCREEN 

HaruPage

(no version information, might be only in CVS)

HaruPage -- Haru PDF Page Class

Synopsis

class HaruPage

Class Members

Predefined Constants

Table 1.

TypeNameDescription
intHaruPage::GMODE_PAGE_DESCRIPTION 
intHaruPage::GMODE_TEXT_OBJECT 
intHaruPage::GMODE_PATH_OBJECT 
intHaruPage::GMODE_CLIPPING_PATH 
intHaruPage::GMODE_SHADING 
intHaruPage::GMODE_INLINE_IMAGE 
intHaruPage::GMODE_EXTERNAL_OBJECT 
intHaruPage::BUTT_END 
intHaruPage::ROUND_END 
intHaruPage::PROJECTING_SCUARE_END 
intHaruPage::MITER_JOIN 
intHaruPage::ROUND_JOIN 
intHaruPage::BEVEL_JOIN 
intHaruPage::FILL 
intHaruPage::STROKE 
intHaruPage::FILL_THEN_STROKE 
intHaruPage::INVISIBLE 
intHaruPage::FILL_CLIPPING 
intHaruPage::STROKE_CLIPPING 
intHaruPage::FILL_STROKE_CLIPPING 
intHaruPage::CLIPPING 
intHaruPage::TALIGN_LEFT 
intHaruPage::TALIGN_RIGHT 
intHaruPage::TALIGN_CENTER 
intHaruPage::TALIGN_JUSTIFY 
intHaruPage::SIZE_LETTER 
intHaruPage::SIZE_LEGAL 
intHaruPage::SIZE_A3 
intHaruPage::SIZE_A4 
intHaruPage::SIZE_A5 
intHaruPage::SIZE_B4 
intHaruPage::SIZE_B5 
intHaruPage::SIZE_EXECUTIVE 
intHaruPage::SIZE_US4x6 
intHaruPage::SIZE_US4x8 
intHaruPage::SIZE_US5x7 
intHaruPage::SIZE_COMM10 
intHaruPage::PORTRAIT 
intHaruPage::LANDSCAPE 
intHaruPage::TS_WIPE_LIGHT 
intHaruPage::TS_WIPE_UP 
intHaruPage::TS_WIPE_LEFT 
intHaruPage::TS_WIPE_DOWN 
intHaruPage::TS_BARN_DOORS_HORIZONTAL_OUT 
intHaruPage::TS_BARN_DOORS_HORIZONTAL_IN 
intHaruPage::TS_BARN_DOORS_VERTICAL_OUT 
intHaruPage::TS_BARN_DOORS_VERTICAL_IN 
intHaruPage::TS_BOX_OUT 
intHaruPage::TS_BOX_IN 
intHaruPage::TS_BLINDS_HORIZONTAL 
intHaruPage::TS_BLINDS_VERTICAL 
intHaruPage::TS_DISSOLVE 
intHaruPage::TS_GLITTER_RIGHT 
intHaruPage::TS_GLITTER_DOWN 
intHaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT 
intHaruPage::TS_REPLACE 
intHaruPage::NUM_STYLE_DECIMAL 
intHaruPage::NUM_STYLE_UPPER_ROMAN 
intHaruPage::NUM_STYLE_LOWER_ROMAN 
intHaruPage::NUM_STYLE_UPPER_LETTERS 
intHaruPage::NUM_STYLE_LOWER_LETTERS 

Methods

HaruPage::arc()
HaruPage::beginText()
HaruPage::circle()
HaruPage::closePath()
HaruPage::concat()
HaruPage::createDestination()
HaruPage::createLinkAnnotation()
HaruPage::createTextAnnotation()
HaruPage::createUrlAnnotation()
HaruPage::curveTo()
HaruPage::curveTo2()
HaruPage::curveTo3()
HaruPage::drawImage()
HaruPage::ellipse()
HaruPage::endPath()
HaruPage::endText()
HaruPage::eofillStroke()
HaruPage::eofill()
HaruPage::fillStroke()
HaruPage::fill()
HaruPage::getCharSpace()
HaruPage::getCMYKFill()
HaruPage::getCMYKStroke()
HaruPage::getCurrentFontSize()
HaruPage::getCurrentFont()
HaruPage::getCurrentPos()
HaruPage::getCurrentTextPos()
HaruPage::getDash()
HaruPage::getFillingColorSpace()
HaruPage::getFlatness()
HaruPage::getGMode()
HaruPage::getGrayFill()
HaruPage::getGrayStroke()
HaruPage::getHeight()
HaruPage::getHorizontalScaling()
HaruPage::getLineCap()
HaruPage::getLineJoin()
HaruPage::getLineWidth()
HaruPage::getMiterLimit()
HaruPage::getRGBFill()
HaruPage::getRGBStroke()
HaruPage::getStrokingColorSpace()
HaruPage::getTextLeading()
HaruPage::getTextMatrix()
HaruPage::getTextRenderingMode()
HaruPage::getTextRise()
HaruPage::getTextWidth()
HaruPage::getTransMatrix()
HaruPage::getWidth()
HaruPage::getWordSpace()
HaruPage::lineTo()
HaruPage::measureText()
HaruPage::moveTextPos()
HaruPage::moveToNextLine()
HaruPage::moveTo()
HaruPage::rectangle()
HaruPage::setCharSpace()
HaruPage::setCMYKFill()
HaruPage::setCMYKStroke()
HaruPage::setDash()
HaruPage::setFlatness()
HaruPage::setFontAndSize()
HaruPage::setGrayFill()
HaruPage::setGrayStroke()
HaruPage::setHeight()
HaruPage::setHorizontalScaling()
HaruPage::setLineCap()
HaruPage::setLineJoin()
HaruPage::setLineWidth()
HaruPage::setMiterLimit()
HaruPage::setRGBFill()
HaruPage::setRGBStroke()
HaruPage::setRotate()
HaruPage::setSize()
HaruPage::setSlideShow()
HaruPage::setTextLeading()
HaruPage::setTextMatrix()
HaruPage::setTextTenderingMode()
HaruPage::setWidth()
HaruPage::setWordSpace()
HaruPage::showTextNextLine()
HaruPage::showText()
HaruPage::stroke()
HaruPage::textOut()
HaruPage::textRect()

HaruFont

(no version information, might be only in CVS)

HaruFont -- Haru PDF Font Class

Synopsis

class HaruFont

HaruImage

(no version information, might be only in CVS)

HaruImage -- Haru PDF Image Class

Synopsis

class HaruImage

HaruEncoder

(no version information, might be only in CVS)

HaruEncoder -- Haru PDF Encoder Class

Synopsis

class HaruEncoder

Class Members

Predefined Constants

Table 1.

TypeNameDescription
intHaruEncoder::TYPE_SINGLE_BYTE 
intHaruEncoder::TYPE_DOUBLE_BYTE 
intHaruEncoder::TYPE_UNINITIALIZED 
intHaruEncoder::UNKNOWN 
intHaruEncoder::WMODE_HORIZONTAL 
intHaruEncoder::WMODE_VERTICAL 
intHaruEncoder::BYTE_TYPE_SINGLE 
intHaruEncoder::BYTE_TYPE_LEAD 
intHaruEncoder::BYTE_TYPE_TRAIL 
intHaruEncoder::BYTE_TYPE_UNKNOWN 

HaruOutline

(no version information, might be only in CVS)

HaruOutline -- Haru PDF Outline Class

Synopsis

class HaruOutline

HaruAnnotation

(no version information, might be only in CVS)

HaruAnnotation -- Haru PDF Annotation Class

Synopsis

class HaruAnnotation

Class Members

Predefined Constants

Table 1.

TypeNameDescription
intHaruAnnotation::NO_HIGHLIGHT 
intHaruAnnotation::INVERT_BOX 
intHaruAnnotation::INVERT_BORDER 
intHaruAnnotation::DOWN_APPEARANCE 
intHaruAnnotation::ICON_COMMENT 
intHaruAnnotation::ICON_KEY 
intHaruAnnotation::ICON_NOTE 
intHaruAnnotation::ICON_HELP 
intHaruAnnotation::ICON_NEW_PARAGRAPH 
intHaruAnnotation::ICON_PARAGRAPH 
intHaruAnnotation::ICON_INSERT 

HaruDestination

(no version information, might be only in CVS)

HaruDestination -- Haru PDF Destination Class

Synopsis

class HaruDestination

HaruAnnotation::setBorderStyle

(no version information, might be only in CVS)

HaruAnnotation::setBorderStyle -- Set the border style of the annotation

Description

bool HaruAnnotation::setBorderStyle ( float width, int dash_on, int dash_off )

Defines the style of the border of the annotation. This function may be used with link annotations only.

Parameters

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruAnnotation::setHighlightMode

(no version information, might be only in CVS)

HaruAnnotation::setHighlightMode -- Set the highlighting mode of the annotation

Description

bool HaruAnnotation::setHighlightMode ( int mode )

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parameters

mode

The highlighting mode of the annotation. Can take only these values:

HaruAnnotation::NO_HIGHLIGHT - no highlighting.
HaruAnnotation::INVERT_BOX - invert the contents of the annotation.
HaruAnnotation::INVERT_BORDER - invert the border of the annotation.
HaruAnnotation::DOWN_APPEARANCE - dent the annotation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruAnnotation::setIcon

(no version information, might be only in CVS)

HaruAnnotation::setIcon -- Set the icon style of the annotation

Description

bool HaruAnnotation::setIcon ( int icon )

Defines the style of the annotation icon. This function may be used with text annotations only.

Parameters

icon

The style of the icon. Can take only these values:

HaruAnnotation::ICON_COMMENT
HaruAnnotation::ICON_KEY
HaruAnnotation::ICON_NOTE
HaruAnnotation::ICON_HELP
HaruAnnotation::ICON_NEW_PARAGRAPH
HaruAnnotation::ICON_PARAGRAPH
HaruAnnotation::ICON_INSERT

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruAnnotation::setOpened

(no version information, might be only in CVS)

HaruAnnotation::setOpened -- Set the initial state of the annotation

Description

bool HaruAnnotation::setOpened ( bool opened )

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parameters

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFit

(no version information, might be only in CVS)

HaruDestination::setFit -- Set the appearance of the page to fit the window

Description

bool HaruDestination::setFit ( void )

Defines the appearance of the page to fit the window.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitB

(no version information, might be only in CVS)

HaruDestination::setFitB -- Set the appearance of the page to fit the bounding box of the page within the window

Description

bool HaruDestination::setFitB ( void )

Defines the appearance of the page to fit the bounding box of the page within the window.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitBH

(no version information, might be only in CVS)

HaruDestination::setFitBH -- Set the appearance of the page to fit the width of the bounding box

Description

bool HaruDestination::setFitBH ( float top )

Defines the appearance of the page to magnifying to fit the width of the bounding box and setting the top position of the page to the value of top.

Parameters

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitBV

(no version information, might be only in CVS)

HaruDestination::setFitBV -- Set the appearance of the page to fit the height of the boudning box

Description

bool HaruDestination::setFitBV ( float left )

Defines the appearance of the page to magnifying to fit the height of the bounding box and setting the left position of the page to the value of left.

Parameters

left

The left coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitH

(no version information, might be only in CVS)

HaruDestination::setFitH -- Set the appearance of the page to fit the window width

Description

bool HaruDestination::setFitH ( float top )

Defines the appearance of the page to fit the window width and sets the top position of the page to the value of top.

Parameters

top

The top position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitR

(no version information, might be only in CVS)

HaruDestination::setFitR -- Set the appearance of the page to fit the specified rectangle

Description

bool HaruDestination::setFitR ( float left, float bottom, float right, float top )

Defines the appearance of the page to fit the rectangle by the parameters.

Parameters

left

The left coordinates of the page.

bottom

The bottom coordinates of the page.

right

The right coordinates of the page.

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setFitV

(no version information, might be only in CVS)

HaruDestination::setFitV -- Set the appearance of the page to fit the window height

Description

bool HaruDestination::setFitV ( float left )

Defines the appearance of the page to fit the window height.

Parameters

left

The left position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDestination::setXYZ

(no version information, might be only in CVS)

HaruDestination::setXYZ -- Set the appearance of the page

Description

bool HaruDestination::setXYZ ( float left, float top, float zoom )

Defines the appearance of the page using three parameters: left, top and zoom.

Parameters

left

The left position of the page.

top

The top position of the page.

zoom

The magnification factor. The value must be between 0.08 (8%) and 32 (3200%).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::addPage

(no version information, might be only in CVS)

HaruDoc::addPage -- Add new page to the document

Description

object HaruDoc::addPage ( void )

Adds new page to the document and returns new HaruPage instance.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::addPageLabel

(no version information, might be only in CVS)

HaruDoc::addPageLabel -- Set the numbering style for the specified range of pages

Description

bool HaruDoc::addPageLabel ( int first_page, int style, int first_num [, string prefix] )

Set the numbering style for the specified range of pages.

Parameters

first_page

The first page included into the labeling range.

style

The numbering style. The following values are allowed:

HaruPage::NUM_STYLE_DECIMAL - page label is displayed using decimal numerals.
HaruPage::NUM_STYLE_UPPER_ROMAN - page label is displayed using uppercase Roman numerals.
HaruPage::NUM_STYLE_LOWER_ROMAN - page label is displayed using lowercase Roman numerals.
HaruPage::NUM_STYLE_UPPER_LETTER - page label is displayed using uppercase letters (from A to Z).
HaruPage::NUM_STYLE_LOWER_LETTERS - page label is displayed using lowercase letters (from a to z).

first_num

The first page number in this range.

prefix

The prefix for the page label. Optional, empty by default.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::__construct

(no version information, might be only in CVS)

HaruDoc::__construct -- Construct new HaruDoc instance

Description

void HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::createOutline

(no version information, might be only in CVS)

HaruDoc::createOutline -- Create a HaruOutline instance

Description

object HaruDoc::createOutline ( string title [, object parent_outline [, object encoder]] )

Creates and returns new HaruOutline instance.

Parameters

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getCurrentEncoder

(no version information, might be only in CVS)

HaruDoc::getCurrentEncoder -- Get HaruEncoder currently used in the document

Description

object HaruDoc::getCurrentEncoder ( void )

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getCurrentPage

(no version information, might be only in CVS)

HaruDoc::getCurrentPage -- Return current page of the document

Description

object HaruDoc::getCurrentPage ( void )

Get current page of the document. Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getEncoder

(no version information, might be only in CVS)

HaruDoc::getEncoder -- Get HaruEncoder instance for the specified encoding

Description

object HaruDoc::getEncoder ( string encoding )

Returns HaruEncoder instance for the specified encoding.

Parameters

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getFont

(no version information, might be only in CVS)

HaruDoc::getFont -- Get HaruFont instance

Description

object HaruDoc::getFont ( string fontname [, string encoding] )

Creates and returns HaruFont instance with the specified fontname and encoding.

Parameters

fontname

The name of the font. See Builtin Fonts for the list of builtin fonts. You can also use the name of a font loaded via HaruDoc::loadTTF(), HaruDoc::loadTTC() and HaruDoc::loadType1().

encoding

The encoding to use. See Builtin Encodings for the list of supported encodings.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getInfoAttr

(no version information, might be only in CVS)

HaruDoc::getInfoAttr -- Get current value of the specified document attribute

Description

string HaruDoc::getInfoAttr ( int type )

Returns the string value of the specified document attribute.

Parameters

type

The type of the attribute. The following values are available:

HaruDoc::INFO_AUTHOR
HaruDoc::INFO_CREATOR
HaruDoc::INFO_TITLE
HaruDoc::INFO_SUBJECT
HaruDoc::INFO_KEYWORDS
HaruDoc::INFO_CREATION_DATE
HaruDoc::INFO_MOD_DATE

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getPageLayout

(no version information, might be only in CVS)

HaruDoc::getPageLayout -- Get current page layout

Description

int HaruDoc::getPageLayout ( void )

Returns the page layout currently set in the document or FALSE if page layout was not set. See HaruDoc::setPageLayout() for the list of possible values.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getPageMode

(no version information, might be only in CVS)

HaruDoc::getPageMode -- Get current page mode

Description

int HaruDoc::getPageMode ( void )

Returns the page mode currently set in the document. See HaruDoc::setPageMode() for the list of possible values.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::getStreamSize

(no version information, might be only in CVS)

HaruDoc::getStreamSize -- Get the size of the temporary stream

Description

int HaruDoc::getStreamSize ( void )

Returns the size of the data in the temporary stream of the document. The size is zero if the document was not saved to the temporary stream.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::insertPage

(no version information, might be only in CVS)

HaruDoc::insertPage -- Insert new page just before the specified page

Description

object HaruDoc::insertPage ( object page )

Creates new page and inserts just before the specified page. Returns new HaruPage instance.

Parameters

page

A valid HaruPage instance.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadJPEG

(no version information, might be only in CVS)

HaruDoc::loadJPEG -- Load JPEG image and return new HaruImage instance

Description

object HaruDoc::loadJPEG ( string filename )

Loads the specified JPEG image and returns new HaruImage instance.

Parameters

filename

A valid JPEG image file.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadPNG

(no version information, might be only in CVS)

HaruDoc::loadPNG -- Load PNG image and return HaruImage instance

Description

object HaruDoc::loadPNG ( string filename [, bool deferred] )

Loads PNG image and returns HaruImage instance. You can set deferred parameter to TRUE for deferred data loading, in this case only size and color are loaded immediately. Default value of deferred is FALSE.

Libharu might be built without libpng support, in this case each call to this function would result in exception.

Parameters

filename

The name of a PNG image file.

deferred

Do not load data immediately. Defaults to FALSE.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadRaw

(no version information, might be only in CVS)

HaruDoc::loadRaw -- Load RAW image and return HaruImage instance

Description

object HaruDoc::loadRaw ( string filename, int width, int height, int color_space )

Loads RAW image and returns new HaruImage instance.

Parameters

filename

The name of a RAW image file.

width

The width of the image.

height

The height of the image.

color_space

The color space of the image. Can be one of the following values:

HaruDoc::CS_DEVICE_GRAY
HaruDoc::CS_DEVICE_RGB
HaruDoc::CS_DEVICE_CMYK

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadTTC

(no version information, might be only in CVS)

HaruDoc::loadTTC -- Load the font with the specified index from TTC file

Description

string HaruDoc::loadTTC ( string fontfile, int index [, bool embed] )

Loads the TrueType font with the specified index from a TrueType collection file.

Parameters

fontfile

The TrueType collection file.

index

The index of the font in the collection file.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included. Defaults to FALSE.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadTTF

(no version information, might be only in CVS)

HaruDoc::loadTTF -- Load TTF font file

Description

string HaruDoc::loadTTF ( string fontfile [, bool embed] )

Loads the given TTF file and (optionally) embed its data into the document.

Parameters

fontfile

The TTF file to load.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included. Defaults to FALSE.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::loadType1

(no version information, might be only in CVS)

HaruDoc::loadType1 -- Load Type1 font

Description

string HaruDoc::loadType1 ( string afmfile [, string pfmfile] )

Loads Type1 font from the given file and registers it in the PDF document.

Parameters

afmfile

Path to an AFM file.

pfmfile

Path to a PFA/PFB file, optional. If it's not set only the glyph data of the font is embedded into the PDF document.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::output

(no version information, might be only in CVS)

HaruDoc::output -- Write the document data to the output buffer

Description

bool HaruDoc::output ( void )

Writes the document data into standard output.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

See Also

HaruDoc::save()

HaruDoc::readFromStream

(no version information, might be only in CVS)

HaruDoc::readFromStream -- Read data from the temporary stream

Description

string HaruDoc::readFromStream ( int bytes )

Returns data from the temporary stream. The bytes parameter specifies how much bytes to read, though the stream may contain less bytes than requested.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::resetError

(no version information, might be only in CVS)

HaruDoc::resetError -- Reset error state of the document handle

Description

bool HaruDoc::resetError ( void )

Once an error code is set, most of the operations, including I/O processing functions cannot be performed. In case if you want to continue after the cause of the error has been fixed, you have to invoke this function in order to reset the document error state.

Return Values

Always succeedes and returns TRUE.

HaruDoc::resetStream

(no version information, might be only in CVS)

HaruDoc::resetStream -- Rewind the temporary stream

Description

bool HaruDoc::resetStream ( void )

Rewinds the temporary stream of the document.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::save

(no version information, might be only in CVS)

HaruDoc::save -- Save the document into the specified file

Description

bool HaruDoc::save ( string file )

Saves the document into the specified file.

Parameters

file

The file to save the document to.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::saveToStream

(no version information, might be only in CVS)

HaruDoc::saveToStream -- Save the document into a temporary stream

Description

bool HaruDoc::saveToStream ( void )

Saves the document data into a temporary stream.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setCompressionMode

(no version information, might be only in CVS)

HaruDoc::setCompressionMode -- Set compression mode for the document

Description

bool HaruDoc::setCompressionMode ( int mode )

Defines compression mode for the document. In case when libharu was compiled without Zlib support this function will always throw HaruException.

Parameters

mode

The compression mode to use. The value is a combination of the following flags:

HaruDoc::COMP_NONE - all contents is not compressed.
HaruDoc::COMP_TEXT - compress the text data.
HaruDoc::COMP_IMAGE - compress the image data.
HaruDoc::COMP_METADATA - compress other data (fonts, cmaps).
HaruDoc::COMP_ALL - compress all data.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setCurrentEncoder

(no version information, might be only in CVS)

HaruDoc::setCurrentEncoder -- Set the current encoder for the document

Description

bool HaruDoc::setCurrentEncoder ( string encoding )

Defines the encoder currently used in the document.

Parameters

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setEncryptionMode

(no version information, might be only in CVS)

HaruDoc::setEncryptionMode -- Set encryption mode for the document

Description

bool HaruDoc::setEncryptionMode ( int mode [, int key_len] )

Defines encryption mode for the document. The encryption mode cannot be set before setting the password.

Parameters

mode

The encryption mode to use. Can be one of the following:

HaruDoc::ENCRYPT_R2 - use "revision2" algorithm.
HaruDoc::ENCRYPT_R3 - use "revision3" algorithm. Using this value bumps the version of PDF to 1.4.

key_len

The encryption key length in bytes. This parameter is optional and used only when mode is HaruDoc::ENCRYPT_R3. The default value is 5 (40bit).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setInfoAttr

(no version information, might be only in CVS)

HaruDoc::setInfoAttr -- Set the info attribute of the document

Description

bool HaruDoc::setInfoAttr ( int type, string info )

Defines an info attribute. Uses the current encoding of the document.

Parameters

type

The type of the attribute. Can be one of the following:

HaruDoc::INFO_AUTHOR
HaruDoc::INFO_CREATOR
HaruDoc::INFO_TITLE
HaruDoc::INFO_SUBJECT
HaruDoc::INFO_KEYWORDS

info

The value of the attribute.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setInfoDateAttr

(no version information, might be only in CVS)

HaruDoc::setInfoDateAttr -- Set the datetime info attributes of the document

Description

bool HaruDoc::setInfoDateAttr ( int type, int year, int month, int day, int hour, int min, int sec, string ind, int off_hour, int off_min )

Sets the datetime info attributes of the document.

Parameters

type

The type of the attribute. Can be one of the following:

HaruDoc::INFO_CREATION_DATE
HaruDoc::INFO_MOD_DATE

year

month

Between 1 and 12.

day

Between 1 and 31, 30, 29 or 28 (different for each month).

hour

Between 0 and 23.

min

Between 0 and 59.

sec

Between 0 and 59.

ind

The timezone relation to UTC, can be "", " ", "+", "-" and "Z".

off_hour

If ind is not " " or "", values between 0 and 23 are valid. Otherwise, this parameter is ignored.

off_min

If ind is not " " or "", values between 0 and 59 are valid. Otherwise, this parameter is ignored.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setOpenAction

(no version information, might be only in CVS)

HaruDoc::setOpenAction -- Define which page is shown when the document is opened

Description

bool HaruDoc::setOpenAction ( object destination )

Defines wich page should be shown when the document is opened.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setPageLayout

(no version information, might be only in CVS)

HaruDoc::setPageLayout -- Set how pages should be displayed

Description

bool HaruDoc::setPageLayout ( int layout )

Defines how pages should be displayed.

Parameters

layout

The following values are accepted:

HaruDoc::PAGE_LAYOUT_SINGLE - only one page is displayed.
HaruDoc::PAGE_LAYOUT_ONE_COLUMN - display the pages in one column.
HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT - display pages in two columns, first page left.
HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT - display pages in two columns, first page right.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setPageMode

(no version information, might be only in CVS)

HaruDoc::setPageMode -- Set how the document should be displayed

Description

bool HaruDoc::setPageMode ( int mode )

Defines how the document should be displayed.

Parameters

mode

The following values are accepted:

HaruDoc::PAGE_MODE_USE_NONE - display the document with neither outline nor thumbnail.
HaruDoc::PAGE_MODE_USE_OUTLINE - display the document with outline pane.
HaruDoc::PAGE_MODE_USE_THUMBS - display the document with thumbnail pane.
HaruDoc::PAGE_MODE_FULL_SCREEN - display the document with full screen mode.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setPagesConfiguration

(no version information, might be only in CVS)

HaruDoc::setPagesConfiguration -- Set the number of pages per set of pages

Description

bool HaruDoc::setPagesConfiguration ( int page_per_pages )

By default the document has one pages object as a root for all pages. All page objects are create as branches of this object. One pages object can contain only 8191, therefore the maximum number of pages per document is 8191. But you can change that fact by setting page_per_pages parameter, so that the root pages object contains 8191 more pages (not page) objects, which in turn contain 8191 pages each. So the maximum number of pages in the document becomes 8191*page_per_pages.

Parameters

page_per_pages

The numbers of pages that a pages object can contain.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setPassword

(no version information, might be only in CVS)

HaruDoc::setPassword -- Set owner and user passwords for the document

Description

bool HaruDoc::setPassword ( string owner_password, string user_password )

Defines owner and user passwords for the document. Setting the passwords makes the document contents encrypted.

Parameters

owner_password

The password of the owner, which can change permissions of the document. Empty password is not accepted. Owner's password cannot be the same as the user's password.

user_password

The password of the user. Can be empty.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::setPermission

(no version information, might be only in CVS)

HaruDoc::setPermission -- Set permissions for the document

Description

bool HaruDoc::setPermission ( int permission )

Defines permissions for the document.

Parameters

permission

The values is a combination of these flags:

HaruDoc::ENABLE_READ - user can read the document.
HaruDoc::ENABLE_PRINT - user can print the document.
HaruDoc::ENABLE_EDIT_ALL - user can edit the contents of the document other than annotations and form fields.
HaruDoc::ENABLE_COPY - user can copy the text and the graphics of the document.
HaruDoc::ENABLE_EDIT - user can add or modify the annotations and form fields of the document.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useCNSEncodings

(no version information, might be only in CVS)

HaruDoc::useCNSEncodings -- Enable Chinese simplified encodings

Description

bool HaruDoc::useCNSEncodings ( void )

Enables Chinese simplified encodings.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useCNSFonts

(no version information, might be only in CVS)

HaruDoc::useCNSFonts -- Enable builtin Chinese simplified fonts

Description

bool HaruDoc::useCNSFonts ( void )

Enableis builtin Chinese simplified fonts.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useCNTEncodings

(no version information, might be only in CVS)

HaruDoc::useCNTEncodings -- Enable Chinese traditional encodings

Description

bool HaruDoc::useCNTEncodings ( void )

Enables Chinese traditional encodings.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useCNTFonts

(no version information, might be only in CVS)

HaruDoc::useCNTFonts -- Enable builtin Chinese traditional fonts

Description

bool HaruDoc::useCNTFonts ( void )

Enables builtin Chinese traditional fonts.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useJPEncodings

(no version information, might be only in CVS)

HaruDoc::useJPEncodings -- Enable Japanese encodings

Description

bool HaruDoc::useJPEncodings ( void )

Enables Japanese encodings.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useJPFonts

(no version information, might be only in CVS)

HaruDoc::useJPFonts -- Enable builtin Japanese fonts

Description

bool HaruDoc::useJPFonts ( void )

Enables builtin Japanese fonts.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useKREncodings

(no version information, might be only in CVS)

HaruDoc::useKREncodings -- Enable Korean encodings

Description

bool HaruDoc::useKREncodings ( void )

Enables Korean encodings.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruDoc::useKRFonts

(no version information, might be only in CVS)

HaruDoc::useKRFonts -- Enable builtin Korean fonts

Description

bool HaruDoc::useKRFonts ( void )

Enables builtin Korean fonts.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruEncoder::getByteType

(no version information, might be only in CVS)

HaruEncoder::getByteType -- Get the type of the byte in the text

Description

int HaruEncoder::getByteType ( string text, int index )

Returns the type of the byte in the text on the specified position. The result is one of the following values:

HaruEncoder::BYTE_TYPE_SINGLE - single byte character.
HaruEncoder::BYTE_TYPE_LEAD - lead byte of a double-byte character.
HaruEncoder::BYTE_TYPE_TRAIL - trailing byte of a double-byte character.
HaruEncoder::BYTE_TYPE_UNKNOWN - invalid encoder or cannot detect the byte type.

Parameters

text

The text.

index

The position in the text.

Errors/Exceptions

Throws HaruException on error.

HaruEncoder::getType

(no version information, might be only in CVS)

HaruEncoder::getType -- Get the type of the encoder

Description

int HaruEncoder::getType ( void )

Returns the type of the encoder. The result is one of the followin values:

HaruEncoder::TYPE_SINGLE_BYTE - the encoder is for single byte characters.
HaruEncoder::TYPE_DOUBLE_BYTE - the encoder is for multibyte characters.
HaruEncoder::TYPE_UNINITIALIZED - the encoder is not initialized.
HaruEncoder::UNKNOWN - the encoder is invalid.

Errors/Exceptions

Throws HaruException on error.

HaruEncoder::getUnicode

(no version information, might be only in CVS)

HaruEncoder::getUnicode -- Convert the specified character to unicode

Description

int HaruEncoder::getUnicode ( int character )

Converts the specified character to unicode.

Parameters

character

The character code to convert.

Errors/Exceptions

Throws HaruException on error.

HaruEncoder::getWritingMode

(no version information, might be only in CVS)

HaruEncoder::getWritingMode -- Get the writing mode of the encoder

Description

int HaruEncoder::getWritingMode ( void )

Returns the writing mode of the encoder. The result value is on of the following:

HaruEncoder::WMODE_HORIZONTAL - horizontal writing mode.
HaruEncoder::WMODE_VERTICAL - vertical writing mode.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getAscent

(no version information, might be only in CVS)

HaruFont::getAscent -- Get the vertical ascent of the font

Description

int HaruFont::getAscent ( void )

Returns the vertical ascent of the font.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getCapHeight

(no version information, might be only in CVS)

HaruFont::getCapHeight -- Get the distance from the baseline of uppercase letters

Description

int HaruFont::getCapHeight ( void )

Returns the distance from the baseline of uppercase letters.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getDescent

(no version information, might be only in CVS)

HaruFont::getDescent -- Get the vertical descent of the font

Description

int HaruFont::getDescent ( void )

Return the vertical descent of the font.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getEncodingName

(no version information, might be only in CVS)

HaruFont::getEncodingName -- Get the name of the encoding

Description

string HaruFont::getEncodingName ( void )

Returns the name of the font encoding.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getFontName

(no version information, might be only in CVS)

HaruFont::getFontName -- Get the name of the font

Description

string HaruFont::getFontName ( void )

Returns the name of the font.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getTextWidth

(no version information, might be only in CVS)

HaruFont::getTextWidth -- Get the total width of the text, number of characters, number of words and number of spaces

Description

array HaruFont::getTextWidth ( string text )

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Parameters

text

The text to measure.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getUnicodeWidth

(no version information, might be only in CVS)

HaruFont::getUnicodeWidth -- Get the width of the character in the font

Description

int HaruFont::getUnicodeWidth ( int character )

Returns the width of the character in the font.

Parameters

character

The code of the character.

Errors/Exceptions

Throws HaruException on error.

HaruFont::getXHeight

(no version information, might be only in CVS)

HaruFont::getXHeight -- Get the distance from the baseline of lowercase letters

Description

int HaruFont::getXHeight ( void )

Returns the distance from the baseline of lowercase letters.

Errors/Exceptions

Throws HaruException on error.

HaruFont::measureText

(no version information, might be only in CVS)

HaruFont::measureText -- Calculate the number of characters which can be included within the specified width

Description

int HaruFont::measureText ( string text, float width, float font_size, float char_space, float word_space [, bool word_wrap] )

Returns the number of characters which can be included within the specified width.

Parameters

text

The text to fit the width.

width

The width of the area to put the text to.

font_size

The size of the font.

char_space

The character spacing.

word_space

The word spacing.

word_wrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area. Defaults to FALSE.

Errors/Exceptions

Throws HaruException on error.

HaruImage::getBitsPerComponent

(no version information, might be only in CVS)

HaruImage::getBitsPerComponent -- Get the number of bits used to describe each color component of the image

Description

int HaruImage::getBitsPerComponent ( void )

Returns the number of bits used to describe each color component of the image.

Errors/Exceptions

Throws HaruException on error.

HaruImage::getColorSpace

(no version information, might be only in CVS)

HaruImage::getColorSpace -- Get the name of the color space

Description

string HaruImage::getColorSpace ( void )

Returns the name of the color space of the image. The name is one of the following values:

"DeviceGray"
"DeviceRGB"
"DeviceCMYK"
"Indexed"

Errors/Exceptions

Throws HaruException on error.

HaruImage::getHeight

(no version information, might be only in CVS)

HaruImage::getHeight -- Get the height of the image

Description

int HaruImage::getHeight ( void )

Returns the height of the image.

Errors/Exceptions

Throws HaruException on error.

HaruImage::getSize

(no version information, might be only in CVS)

HaruImage::getSize -- Get size of the image

Description

array HaruImage::getSize ( void )

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Errors/Exceptions

Throws HaruException on error.

HaruImage::getWidth

(no version information, might be only in CVS)

HaruImage::getWidth -- Get the width of the image

Description

int HaruImage::getWidth ( void )

Returns the width of the image.

Errors/Exceptions

Throws HaruException on error.

HaruImage::setColorMask

(no version information, might be only in CVS)

HaruImage::setColorMask -- Set the color mask of the image

Description

bool HaruImage::setColorMask ( int rmin, int rmax, int gmin, int gmax, int bmin, int bmax )

Defines the transparent color of the image using the RGB range values. The color within the range is displayed as a transparent color. The color space of the image must be RGB.

Parameters

rmin

The lower limit of red. Must be between 0 and 255.

rmax

The upper limit of red. Must be between 0 and 255.

gmin

The lower limit of green. Must be between 0 and 255.

gmax

The upper limit of green. Must be between 0 and 255.

bmin

The lower limit of blue. Must be between 0 and 255.

bmax

The upper limit of blue. Must be between 0 and 255.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruImage::setMaskImage

(no version information, might be only in CVS)

HaruImage::setMaskImage -- Set the image mask

Description

bool HaruImage::setMaskImage ( object mask_image )

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parameters

mask_image

A valid HaruImage instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruOutline::setDestination

(no version information, might be only in CVS)

HaruOutline::setDestination -- Set the destination for the outline

Description

bool HaruOutline::setDestination ( object destination )

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruOutline::setOpened

(no version information, might be only in CVS)

HaruOutline::setOpened -- Set the initial state of the outline

Description

bool HaruOutline::setOpened ( bool opened )

Defines whether this node is opened or not when the outline is displayed for the first time.

Parameters

opened

TRUE means open, FALSE - closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::arc

(no version information, might be only in CVS)

HaruPage::arc -- Append an arc to the current path

Description

bool HaruPage::arc ( float x, float y, float ray, float ang1, float ang2 )

Appends an arc to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

ray

The ray of the arc.

ang1

The angle of the beginning.

ang2

The angle of the end. Must be greater than ang1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::beginText

(no version information, might be only in CVS)

HaruPage::beginText -- Begin a text object and set the current text position to (0,0)

Description

bool HaruPage::beginText ( void )

Begins new text object and sets the current text position to (0,0).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::circle

(no version information, might be only in CVS)

HaruPage::circle -- Append a circle to the current path

Description

bool HaruPage::circle ( float x, float y, float ray )

Appends a circle to the current path.

Parameters

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::closePath

(no version information, might be only in CVS)

HaruPage::closePath -- Append a straight line from the current point to the start point of the path

Description

bool HaruPage::closePath ( void )

Appends a straight line from the current point to the start point of the path.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::concat

(no version information, might be only in CVS)

HaruPage::concat -- Concatenate current transformation matrix of the page and the specified matrix

Description

bool HaruPage::concat ( float a, float b, float c, float d, float x, float y )

Concatenates current transformation matrix of the page and the specified matrix.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::createDestination

(no version information, might be only in CVS)

HaruPage::createDestination -- Create new HaruDestination instance

Description

object HaruPage::createDestination ( void )

Creates and returns new HaruDestination instance.

Errors/Exceptions

Throws HaruException on error.

HaruPage::createLinkAnnotation

(no version information, might be only in CVS)

HaruPage::createLinkAnnotation -- Create new HaruAnnotation instance

Description

object HaruPage::createLinkAnnotation ( array rectangle, object destination )

Creates and returns new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Errors/Exceptions

Throws HaruException on error.

HaruPage::createTextAnnotation

(no version information, might be only in CVS)

HaruPage::createTextAnnotation -- Create new HaruAnnotation instance

Description

object HaruPage::createTextAnnotation ( array rectangle, string text [, object encoder] )

Creates and returns new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Errors/Exceptions

Throws HaruException on error.

HaruPage::createURLAnnotation

(no version information, might be only in CVS)

HaruPage::createURLAnnotation -- Create and return new HaruAnnotation instance

Description

object HaruPage::createURLAnnotation ( array rectangle, string url )

Creates and returns new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Errors/Exceptions

Throws HaruException on error.

HaruPage::curveTo2

(no version information, might be only in CVS)

HaruPage::curveTo2 -- Append a Bezier curve to the current path

Description

bool HaruPage::curveTo2 ( float x2, float y2, float x3, float y3 )

Appends a Bezier curve to the current path. The current point and the point (x2, y2) are used as the control points for the Bezier curve and current point is moved to the point (x3, y3).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::curveTo3

(no version information, might be only in CVS)

HaruPage::curveTo3 -- Append a Bezier curve to the current path

Description

bool HaruPage::curveTo3 ( float x1, float y1, float x3, float y3 )

Appends a Bezier curve to the current path. The point (x1, y1) and the point (x3, y3) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::curveTo

(no version information, might be only in CVS)

HaruPage::curveTo -- Append a Bezier curve to the current path

Description

bool HaruPage::curveTo ( float x1, float y1, float x2, float y2, float x3, float y3 )

Append a Bezier curve to the current path. The point (x1, y1) and the point (x2, y2) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::drawImage

(no version information, might be only in CVS)

HaruPage::drawImage -- Show image at the page

Description

bool HaruPage::drawImage ( object image, float x, float y, float width, float height )

Show image at the page.

Parameters

image

Valid HaruImage instance.

x

The left border of the area where the image is displayed.

y

The lower border of the area where the image is displayed.

width

The width of the image area.

height

The height of the image area.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::ellipse

(no version information, might be only in CVS)

HaruPage::ellipse -- Append an ellipse to the current path

Description

bool HaruPage::ellipse ( float x, float y, float xray, float yray )

Appends an ellipse to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

xray

The ray of the ellipse in the x direction.

yray

The ray of the ellipse in the y direction.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::endPath

(no version information, might be only in CVS)

HaruPage::endPath -- End current path object without filling and painting operations

Description

bool HaruPage::endPath ( void )

Ends current path object without performing filling and painting operations.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::endText

(no version information, might be only in CVS)

HaruPage::endText -- End current text object

Description

bool HaruPage::endText ( void )

Finalizes current text object.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::eofill

(no version information, might be only in CVS)

HaruPage::eofill -- Fill current path using even-odd rule

Description

bool HaruPage::eofill ( void )

Fills current path using even-odd rule.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::eoFillStroke

(no version information, might be only in CVS)

HaruPage::eoFillStroke -- Fill current path using even-odd rule, then paint the path

Description

bool HaruPage::eoFillStroke ( [bool close_path] )

Fills current path using even-odd rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::fill

(no version information, might be only in CVS)

HaruPage::fill -- Fill current path using nonzero winding number rule

Description

bool HaruPage::fill ( void )

Fills current path using nonzero winding number rule.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::fillStroke

(no version information, might be only in CVS)

HaruPage::fillStroke -- Fill current path using nonzero winding number rule, then paint the path

Description

bool HaruPage::fillStroke ( [bool close_path] )

Fills current path using nonzero winding number rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCharSpace

(no version information, might be only in CVS)

HaruPage::getCharSpace -- Get the current value of character spacing

Description

float HaruPage::getCharSpace ( void )

Returns the current value of character spacing.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCMYKFill

(no version information, might be only in CVS)

HaruPage::getCMYKFill -- Get the current filling color

Description

array HaruPage::getCMYKFill ( void )

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCMYKStroke

(no version information, might be only in CVS)

HaruPage::getCMYKStroke -- Get the current stroking color

Description

array HaruPage::getCMYKStroke ( void )

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCurrentFont

(no version information, might be only in CVS)

HaruPage::getCurrentFont -- Get the currently used font

Description

object HaruPage::getCurrentFont ( void )

Returns the currently used font as an instance of HaruFont.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCurrentFontSize

(no version information, might be only in CVS)

HaruPage::getCurrentFontSize -- Get the current font size

Description

float HaruPage::getCurrentFontSize ( void )

Returns the current font size.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCurrentPos

(no version information, might be only in CVS)

HaruPage::getCurrentPos -- Get the current position for path painting

Description

array HaruPage::getCurrentPos ( void )

Returns the current position for path painting as an array of with two elements - "x" and "y".

Errors/Exceptions

Throws HaruException on error.

HaruPage::getCurrentTextPos

(no version information, might be only in CVS)

HaruPage::getCurrentTextPos -- Get the current position for text printing

Description

array HaruPage::getCurrentTextPos ( void )

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Errors/Exceptions

Throws HaruException on error.

HaruPage::getDash

(no version information, might be only in CVS)

HaruPage::getDash -- Get the current dash pattern

Description

array HaruPage::getDash ( void )

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set. See HaruPage::setDash() for more information on dash patterns.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getFillingColorSpace

(no version information, might be only in CVS)

HaruPage::getFillingColorSpace -- Get the current filling color space

Description

int HaruPage::getFillingColorSpace ( void )

Returns the current filling color space. The result value is one of the following:

HaruDoc::CS_DEVICE_GRAY
HaruDoc::CS_DEVICE_RGB
HaruDoc::CS_DEVICE_CMYK
HaruDoc::CS_CAL_GRAY
HaruDoc::CS_CAL_RGB
HaruDoc::CS_LAB
HaruDoc::CS_ICC_BASED
HaruDoc::CS_SEPARATION
HaruDoc::CS_DEVICE_N
HaruDoc::CS_INDEXED
HaruDoc::CS_PATTERN

Errors/Exceptions

Throws HaruException on error.

HaruPage::getFlatness

(no version information, might be only in CVS)

HaruPage::getFlatness -- Get the flatness of the page

Description

float HaruPage::getFlatness ( void )

Returns the flatness of the page.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getGMode

(no version information, might be only in CVS)

HaruPage::getGMode -- Get the current graphics mode

Description

int HaruPage::getGMode ( void )

Returns the current graphics mode. The result value is one of the following:

HaruPage::GMODE_PAGE_DESCRIPTION
HaruPage::GMODE_TEXT_OBJECT
HaruPage::GMODE_PATH_OBJECT
HaruPage::GMODE_CLIPPING_PATH
HaruPage::GMODE_SHADING
HaruPage::GMODE_INLINE_IMAGE
HaruPage::GMODE_EXTERNAL_OBJECT

Errors/Exceptions

Throws HaruException on error.

HaruPage::getGrayFill

(no version information, might be only in CVS)

HaruPage::getGrayFill -- Get the current filling color

Description

float HaruPage::getGrayFill ( void )

Returns the current filling color.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getGrayStroke

(no version information, might be only in CVS)

HaruPage::getGrayStroke -- Get the current stroking color

Description

float HaruPage::getGrayStroke ( void )

Returns the current stroking color.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getHeight

(no version information, might be only in CVS)

HaruPage::getHeight -- Get the height of the page

Description

float HaruPage::getHeight ( void )

Returns the height of the page.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getHorizontalScaling

(no version information, might be only in CVS)

HaruPage::getHorizontalScaling -- Get the current value of horizontal scaling

Description

float HaruPage::getHorizontalScaling ( void )

Returns the current value of horizontal scaling.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getLineCap

(no version information, might be only in CVS)

HaruPage::getLineCap -- Get the current line cap style

Description

int HaruPage::getLineCap ( void )

Returns the current line cap style. The result value is one of the following:

HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getLineJoin

(no version information, might be only in CVS)

HaruPage::getLineJoin -- Get the current line join style

Description

int HaruPage::getLineJoin ( void )

Returns the current line join style. The result value is one of the following:

HaruPage::MITER_JOIN
HaruPage::ROUND_JOIN
HaruPage::BEVEL_JOIN

Errors/Exceptions

Throws HaruException on error.

HaruPage::getLineWidth

(no version information, might be only in CVS)

HaruPage::getLineWidth -- Get the current line width

Description

float HaruPage::getLineWidth ( void )

Returns the current line width.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getMiterLimit

(no version information, might be only in CVS)

HaruPage::getMiterLimit -- Get the value of miter limit

Description

float HaruPage::getMiterLimit ( void )

Returns the value of miter limit.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getRGBFill

(no version information, might be only in CVS)

HaruPage::getRGBFill -- Get the current filling color

Description

array HaruPage::getRGBFill ( void )

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Errors/Exceptions

Throws HaruException on error.

HaruPage::getRGBStroke

(no version information, might be only in CVS)

HaruPage::getRGBStroke -- Get the current stroking color

Description

array HaruPage::getRGBStroke ( void )

Returns the current stroking color.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getStrokingColorSpace

(no version information, might be only in CVS)

HaruPage::getStrokingColorSpace -- Get the current stroking color space

Description

int HaruPage::getStrokingColorSpace ( void )

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace().

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTextLeading

(no version information, might be only in CVS)

HaruPage::getTextLeading -- Get the current value of line spacing

Description

float HaruPage::getTextLeading ( void )

Returns the current value of line spacing.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTextMatrix

(no version information, might be only in CVS)

HaruPage::getTextMatrix -- Get the current text transformation matrix of the page

Description

array HaruPage::getTextMatrix ( void )

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTextRenderingMode

(no version information, might be only in CVS)

HaruPage::getTextRenderingMode -- Get the current text rendering mode

Description

int HaruPage::getTextRenderingMode ( void )

Returns the current text rendering mode. The result value is one of the following:

HaruPage::FILL
HaruPage::STROKE
HaruPage::FILL_THEN_STROKE
HaruPage::INVISIBLE
HaruPage::FILL_CLIPPING
HaruPage::STROKE_CLIPPING
HaruPage::FILL_STROKE_CLIPPING
HaruPage::CLIPPING

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTextRise

(no version information, might be only in CVS)

HaruPage::getTextRise -- Get the current value of text rising

Description

float HaruPage::getTextRise ( void )

Returns the current value of text rising.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTextWidth

(no version information, might be only in CVS)

HaruPage::getTextWidth -- Get the width of the text using current fontsize, character spacing and word spacing

Description

float HaruPage::getTextWidth ( string text )

Returns the width of the text using current fontsize, character spacing and word spacing.

Parameters

text

The text to measure.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getTransMatrix

(no version information, might be only in CVS)

HaruPage::getTransMatrix -- Get the current transformation matrix of the page

Description

array HaruPage::getTransMatrix ( void )

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws HaruException on error.

HaruPage::getWidth

(no version information, might be only in CVS)

HaruPage::getWidth -- Get the width of the page

Description

float HaruPage::getWidth ( void )

Returns the width of the page.

Errors/Exceptions

Throws HaruException on error.

HaruPage::getWordSpace

(no version information, might be only in CVS)

HaruPage::getWordSpace -- Get the current value of word spacing

Description

float HaruPage::getWordSpace ( void )

Returns the current value of word spacing.

Errors/Exceptions

Throws HaruException on error.

HaruPage::lineTo

(no version information, might be only in CVS)

HaruPage::lineTo -- Draw a line from the current point to the specified point

Description

bool HaruPage::lineTo ( float x, float y )

Draws a line from the current point to the specified point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::measureText

(no version information, might be only in CVS)

HaruPage::measureText -- Calculate the number of characters which can be included within the specified width

Description

int HaruPage::measureText ( string text, float width [, bool wordwrap] )

Returns the number of characters which can be included within the specified width.

Parameters

text

The text to measure.

width

The width of the area to put the text to.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area. Defaults to FALSE.

Errors/Exceptions

Throws HaruException on error.

HaruPage::moveTextPos

(no version information, might be only in CVS)

HaruPage::moveTextPos -- Move text position to the specified offset

Description

bool HaruPage::moveTextPos ( float x, float y [, bool set_leading] )

Moves text position to the specified offset. If the start position of the current line is (x1, y1), the start of the next line is (x1 + x, y1 + y). If optional parameter set_leading is TRUE, the function sets the text leading to -y. The default value of set_leading is FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::moveTo

(no version information, might be only in CVS)

HaruPage::moveTo -- Set starting point for new drawing path

Description

bool HaruPage::moveTo ( float x, float y )

Defines starting point for new drawing path.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::moveToNextLine

(no version information, might be only in CVS)

HaruPage::moveToNextLine -- Move text position to the start of the next line

Description

bool HaruPage::moveToNextLine ( void )

Moves text position to the start of the next line.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::rectangle

(no version information, might be only in CVS)

HaruPage::rectangle -- Append a rectangle to the current path

Description

bool HaruPage::rectangle ( float x, float y, float width, float height )

Appends a rectangle to the current drawing path.

Parameters

x

The left border of the rectangle.

y

The lower border of the rectangle.

width

The width of the rectangle.

height

The height of the rectangle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setCharSpace

(no version information, might be only in CVS)

HaruPage::setCharSpace -- Set character spacing for the page

Description

bool HaruPage::setCharSpace ( float char_space )

Defines character spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setCMYKFill

(no version information, might be only in CVS)

HaruPage::setCMYKFill -- Set filling color for the page

Description

bool HaruPage::setCMYKFill ( float c, float m, float y, float k )

Defines filling color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setCMYKStroke

(no version information, might be only in CVS)

HaruPage::setCMYKStroke -- Set stroking color for the page

Description

bool HaruPage::setCMYKStroke ( float c, float m, float y, float k )

Defines stroking color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setDash

(no version information, might be only in CVS)

HaruPage::setDash -- Set the dash pattern for the page

Description

bool HaruPage::setDash ( array pattern, int phase )

Defines the dash pattern for the page.

Parameters

pattern

An array (8 elements max) which contains a pattern of dashes and gaps used for lines on the page.

phase

The phase on which the pattern begins.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setFlatness

(no version information, might be only in CVS)

HaruPage::setFlatness -- Set flatness for the page

Description

bool HaruPage::setFlatness ( float flatness )

Defines flatness for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setFontAndSize

(no version information, might be only in CVS)

HaruPage::setFontAndSize -- Set font and fontsize for the page

Description

bool HaruPage::setFontAndSize ( object font, float size )

Defines current font and its size for the page.

Parameters

font

A valid HaruFont instance.

size

The size of the font.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setGrayFill

(no version information, might be only in CVS)

HaruPage::setGrayFill -- Set filling color for the page

Description

bool HaruPage::setGrayFill ( float value )

Defines filling color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setGrayStroke

(no version information, might be only in CVS)

HaruPage::setGrayStroke -- Sets stroking color for the page

Description

bool HaruPage::setGrayStroke ( float value )

Defines stroking color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setHeight

(no version information, might be only in CVS)

HaruPage::setHeight -- Set height of the page

Description

bool HaruPage::setHeight ( float height )

Defines height of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setHorizontalScaling

(no version information, might be only in CVS)

HaruPage::setHorizontalScaling -- Set horizontal scaling for the page

Description

bool HaruPage::setHorizontalScaling ( float scaling )

Defines horizontal scaling for text showing on the page. The initial value is 100.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setLineCap

(no version information, might be only in CVS)

HaruPage::setLineCap -- Set the shape to be used at the ends of lines

Description

bool HaruPage::setLineCap ( int cap )

Defines the shape to be used at the ends of lines.

Parameters

cap

Must be one of the following values:

HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setLineJoin

(no version information, might be only in CVS)

HaruPage::setLineJoin -- Set line join style for the page

Description

bool HaruPage::setLineJoin ( int join )

Defines line join style for the page.

Parameters

join

Must be one of the following values:

HaruPage::MITER_JOIN
HaruPage::ROUND_JOIN
HaruPage::BEVEL_JOIN

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setLineWidth

(no version information, might be only in CVS)

HaruPage::setLineWidth -- Set line width for the page

Description

bool HaruPage::setLineWidth ( float width )

Defines line width for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setMiterLimit

(no version information, might be only in CVS)

HaruPage::setMiterLimit -- Set the current value of the miter limit of the page

Description

bool HaruPage::setMiterLimit ( float limit )

Defines the current value of the miter limit of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setRGBFill

(no version information, might be only in CVS)

HaruPage::setRGBFill -- Set filling color for the page

Description

bool HaruPage::setRGBFill ( float r, float g, float b )

Defines filling color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setRGBStroke

(no version information, might be only in CVS)

HaruPage::setRGBStroke -- Set stroking color for the page

Description

bool HaruPage::setRGBStroke ( float r, float g, float b )

Defines stroking color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setRotate

(no version information, might be only in CVS)

HaruPage::setRotate -- Set rotation angle of the page

Description

bool HaruPage::setRotate ( int angle )

Defines rotation angle of the page.

Parameters

angle

Must be a multiple of 90 degrees.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setSize

(no version information, might be only in CVS)

HaruPage::setSize -- Set size and direction of the page

Description

bool HaruPage::setSize ( int size, int direction )

Changes size and direction of the page to a predefined format.

Parameters

size

Must be one of the following values:

HaruPage::SIZE_LETTER
HaruPage::SIZE_LEGAL
HaruPage::SIZE_A3
HaruPage::SIZE_A4
HaruPage::SIZE_A5
HaruPage::SIZE_B4
HaruPage::SIZE_B5
HaruPage::SIZE_EXECUTIVE
HaruPage::SIZE_US4x6
HaruPage::SIZE_US4x8
HaruPage::SIZE_US5x7
HaruPage::SIZE_COMM10

direction

Must be one of the following values:

HaruPage::PORTRAIT
HaruPage::LANDSCAPE

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setSlideShow

(no version information, might be only in CVS)

HaruPage::setSlideShow -- Set transition style for the page

Description

bool HaruPage::setSlideShow ( int type, float disp_time, float trans_time )

Defines transition style for the page.

Parameters

type

Must be one of the following values:

HaruPage::TS_WIPE_RIGHT
HaruPage::TS_WIPE_LEFT
HaruPage::TS_WIPE_UP
HaruPage::TS_WIPE_DOWN
HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT
HaruPage::TS_BARN_DOORS_HORIZONTAL_IN
HaruPage::TS_BARN_DOORS_VERTICAL_OUT
HaruPage::TS_BARN_DOORS_VERTICAL_IN
HaruPage::TS_BOX_OUT
HaruPage::TS_BOX_IN
HaruPage::TS_BLINDS_HORIZONTAL
HaruPage::TS_BLINDS_VERTICAL
HaruPage::TS_DISSOLVE
HaruPage::TS_GLITTER_RIGHT
HaruPage::TS_GLITTER_DOWN
HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT
HaruPage::TS_REPLACE

disp_time

The display duration of the page in seconds.

trans_time

The duration of the transition effect in seconds.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setTextLeading

(no version information, might be only in CVS)

HaruPage::setTextLeading -- Set text leading (line spacing) for the page

Description

bool HaruPage::setTextLeading ( float text_leading )

Defines line spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setTextMatrix

(no version information, might be only in CVS)

HaruPage::setTextMatrix -- Set the current text transformation matrix of the page

Description

bool HaruPage::setTextMatrix ( float a, float b, float c, float d, float x, float y )

Defines the text transformation matrix of the page.

Parameters

a

b

c

d

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setTextRenderingMode

(no version information, might be only in CVS)

HaruPage::setTextRenderingMode -- Set text rendering mode for the page

Description

bool HaruPage::setTextRenderingMode ( int mode )

Defines text rendering mode for the page.

Parameters

mode

Must be one of the following values:

HaruPage::FILL
HaruPage::STROKE
HaruPage::FILL_THEN_STROKE
HaruPage::INVISIBLE
HaruPage::FILL_CLIPPING
HaruPage::STROKE_CLIPPING
HaruPage::FILL_STROKE_CLIPPING
HaruPage::CLIPPING

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setTextRise

(no version information, might be only in CVS)

HaruPage::setTextRise -- Set the current value of text rising

Description

bool HaruPage::setTextRise ( float rise )

Defines the current value of text rising.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setWidth

(no version information, might be only in CVS)

HaruPage::setWidth -- Set width of the page

Description

bool HaruPage::setWidth ( float width )

Defines width of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::setWordSpace

(no version information, might be only in CVS)

HaruPage::setWordSpace -- Set word spacing for the page

Description

bool HaruPage::setWordSpace ( float word_space )

Defines word spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::showText

(no version information, might be only in CVS)

HaruPage::showText -- Print text at the current position of the page

Description

bool HaruPage::showText ( string text )

Prints out the text at the current position of the page.

Parameters

text

The text to show.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::showTextNextLine

(no version information, might be only in CVS)

HaruPage::showTextNextLine -- Move the current position to the start of the next line and print the text

Description

bool HaruPage::showTextNextLine ( string text [, float word_space [, float char_space]] )

Moves the current position to the start of the next line and print out the text.

Parameters

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::stroke

(no version information, might be only in CVS)

HaruPage::stroke -- Paint current path

Description

bool HaruPage::stroke ( [bool close_path] )

Paints the current path.

Parameters

close_path

Closes the current path if set to TRUE. Defaults to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::textOut

(no version information, might be only in CVS)

HaruPage::textOut -- Print the text on the specified position

Description

bool HaruPage::textOut ( float x, float y, string text )

Prints the text on the specified position.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

HaruPage::textRect

(no version information, might be only in CVS)

HaruPage::textRect -- Print the text inside the specified region

Description

bool HaruPage::textRect ( float left, float top, float right, float bottom, string text [, int align] )

Prints the text inside the specified region.

Parameters

left

Left border of the text area.

top

Top border of the text area.

right

Right border of the text area.

bottom

Lower border of the text area.

text

The text to print.

align

Text alignment. Must be one of the following values:

HaruPage::TALING_LEFT
HaruPage::TALING_RIGHT
HaruPage::TALING_CENTER
HaruPage::TALING_JUSTIFY

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws HaruException on error.

LIV. hash Functions

Introduction

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.


Requirements

The Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2. It may be explicitly disabled by using the --disable-hash switch to configure. Earlier versions of PHP may incorporate the Hash extension by installing the PECL module.


Resource Types

This extension defines a Hashing Context resource returned by hash_init().


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

HASH_HMAC (integer)

Optional flag for hash_init(). Indicates that the HMAC digest-keying algorithm should be applied to the current hashing context.

Table of Contents
hash_algos -- Return a list of registered hashing algorithms
hash_file -- Generate a hash value using the contents of a given file
hash_final -- Finalize an incremental hash and return resulting digest
hash_hmac_file -- Generate a keyed hash value using the HMAC method and the contents of a given file
hash_hmac -- Generate a keyed hash value using the HMAC method
hash_init -- Initialize an incremental hashing context
hash_update_file -- Pump data into an active hashing context from a file
hash_update_stream -- Pump data into an active hashing context from an open stream
hash_update -- Pump data into an active hashing context
hash -- Generate a hash value (message digest)

hash_algos

(no version information, might be only in CVS)

hash_algos -- Return a list of registered hashing algorithms

Description

array hash_algos ( void )

Return Values

Returns a numerically indexed array containing the list of supported hashing algorithms.

Examples

Example 1. hash_algos() example

As of PHP 5.1.2, hash_algos() will return the following list of algorithm names.

<?php
print_r(hash_algos());
?>

The above example will output:

Array
(
    [0] => md4
    [1] => md5
    [2] => sha1
    [3] => sha256
    [4] => sha384
    [5] => sha512
    [6] => ripemd128
    [7] => ripemd160
    [8] => whirlpool
    [9] => tiger128,3
    [10] => tiger160,3
    [11] => tiger192,3
    [12] => tiger128,4
    [13] => tiger160,4
    [14] => tiger192,4
    [15] => snefru
    [16] => gost
    [17] => adler32
    [18] => crc32
    [19] => crc32b
    [20] => haval128,3
    [21] => haval160,3
    [22] => haval192,3
    [23] => haval224,3
    [24] => haval256,3
    [25] => haval128,4
    [26] => haval160,4
    [27] => haval192,4
    [28] => haval224,4
    [29] => haval256,4
    [30] => haval128,5
    [31] => haval160,5
    [32] => haval192,5
    [33] => haval224,5
    [34] => haval256,5
)

hash_file

(no version information, might be only in CVS)

hash_file -- Generate a hash value using the contents of a given file

Description

string hash_file ( string algo, string filename [, bool raw_output] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

filename

URL describing location of file to be hashed; Supports fopen wrappers.

raw_output

When set to TRUE, outputs raw binary data. Default value (FALSE) outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example 1. Using 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('md5', 'example.txt');
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

hash_final

(no version information, might be only in CVS)

hash_final -- Finalize an incremental hash and return resulting digest

Description

string hash_final ( resource context [, bool raw_output] )

Parameters

context

Hashing context returned by hash_init().

raw_output

When set to TRUE, outputs raw binary data. Default value (FALSE) outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example 1. hash_final() example

<?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

hash_hmac_file

(no version information, might be only in CVS)

hash_hmac_file -- Generate a keyed hash value using the HMAC method and the contents of a given file

Description

string hash_hmac_file ( string algo, string filename, string key [, bool raw_output] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

filename

URL describing location of file to be hashed; Supports fopen wrappers.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. Default value (FALSE) outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example 1. hash_hmac_file() example

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_hmac_file('md5', 'example.txt', 'secret');
?>

The above example will output:

7eb2b5c37443418fc77c136dd20e859c

hash_hmac

(no version information, might be only in CVS)

hash_hmac -- Generate a keyed hash value using the HMAC method

Description

string hash_hmac ( string algo, string data, string key [, bool raw_output] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. Default value (FALSE) outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example 1. hash_hmac() example

<?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

The above example will output:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

hash_init

(no version information, might be only in CVS)

hash_init -- Initialize an incremental hashing context

Description

resource hash_init ( string algo [, int options, string key] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

options

Optional settings for hash generation, currently supports only one option: HASH_HMAC. When specified, the key must be specified.

key

When HASH_HMAC is specified for options, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

Return Values

Returns a Hashing Context resource for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Examples

Example 1. Incremental hashing example

<?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

hash_update_file

(no version information, might be only in CVS)

hash_update_file -- Pump data into an active hashing context from a file

Description

bool hash_update_file ( resource context, string filename [, resource context] )

Parameters

context

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

context

Stream context as returned by stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

hash_update_stream

(no version information, might be only in CVS)

hash_update_stream -- Pump data into an active hashing context from an open stream

Description

int hash_update_stream ( resource context, resource handle [, int length] )

Parameters

context

Hashing context returned by hash_init().

handle

Open file handle as returned by any stream creation function.

length

Maximum number of characters to copy from handle into the hashing context.

Return Values

Actual number of bytes added to the hashing context from handle.

Examples

Example 1. hash_update_stream() example

<?php
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('md5');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

hash_update

(no version information, might be only in CVS)

hash_update -- Pump data into an active hashing context

Description

bool hash_update ( resource context, string data )

Parameters

context

Hashing context returned by hash_init().

data

Message to be included in the hash digest.

Return Values

Returns TRUE.

hash

(no version information, might be only in CVS)

hash -- Generate a hash value (message digest)

Description

string hash ( string algo, string data [, bool raw_output] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

raw_output

When set to TRUE, outputs raw binary data. Default value (FALSE) outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example 1. A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

The above example will output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

LV. HTTP

Introduction

This HTTP extension aims to provide a convenient and powerful set of functionality for one of PHPs major applications.

It eases handling of HTTP URLs, dates, redirects, headers and messages, provides means for negotiation of clients preferred language and charset, as well as a convenient way to send any arbitrary data with caching and resuming capabilities.

It provides powerful request functionality, if built with CURL support. Parallel requests are available for PHP 5 and greater.

Additionally to the API reference in this manual you can find information about how to install and configure as well as which global constants are predefined in the following sections:

Installation
Configuration
Global Constants
Resource Types


Classes

The classes below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The HttpResponse class requires at least PHP v5.1. Any other class is available as of PHP v5.0.

Note: Be aware though, that some methods are not available with PHP v5.0.

HttpMessage
HttpQueryString
HttpDeflateStream
HttpInflateStream
HttpRequest
HttpRequestPool
HttpResponse

Table of Contents
Installation -- Installing the HTTP extension
Configuration -- http module configuration directives
Resources -- Resources created by the HTTP extension
Constants -- predefined http module constants
Request Options -- options usable with the HttpRequest class and request functions
HttpMessage -- HTTP Message Class
HttpMessage::__construct -- HttpMessage constructor
HttpMessage::factory -- Create HttpMessage from string
HttpMessage::fromEnv -- Create HttpMessage from environment
HttpMessage::fromString -- Create HttpMessage from string
HttpMessage::toString -- Get string representation
HttpMessage::toMessageTypeObject -- Create HTTP object regarding message type
HttpMessage::guessContentType -- Guess content type
HttpMessage::detach -- Detach HttpMessage
HttpMessage::prepend -- Prepend message(s)
HttpMessage::reverse -- Reverse message chain
HttpMessage::send -- Send message
HttpMessage::getParentMessage -- Get parent message
HttpMessage::getType -- Get message type
HttpMessage::setType -- Set message type
HttpMessage::getHttpVersion -- Get HTTP version
HttpMessage::setHttpVersion -- Set HTTP version
HttpMessage::getHeaders -- Get message headers
HttpMessage::getHeader -- Get header
HttpMessage::addHeaders -- Add headers
HttpMessage::setHeaders -- Set headers
HttpMessage::getBody -- Get message body
HttpMessage::setBody -- Set message body
HttpMessage::getRequestMethod -- Get request method
HttpMessage::setRequestMethod -- Set request method
HttpMessage::getRequestUrl -- Get request URL
HttpMessage::setRequestUrl -- Set request URL
HttpMessage::getResponseCode -- Get response code
HttpMessage::setResponseCode -- Set response code
HttpMessage::getResponseStatus -- Get response status
HttpMessage::setResponseStatus -- Set response status
HttpQueryString -- HTTP Query String Class
HttpQueryString::__construct -- HttpQueryString constructor
HttpQueryString::singleton -- HttpQueryString singleton
HttpQueryString::get -- Get (part of) query string
HttpQueryString::mod -- Modifiy query string copy
HttpQueryString::set -- Set query string params
HttpQueryString::toArray -- Get query string as array
HttpQueryString::toString -- Get query string
HttpQueryString::xlate -- Change query strings charset
HttpDeflateStream -- HTTP Deflate Stream Class
HttpDeflateStream::factory -- HttpDeflateStream class factory
HttpDeflateStream::__construct -- HttpDeflateStream class constructor
HttpDeflateStream::update -- Update deflate stream
HttpDeflateStream::flush -- Flush deflate stream
HttpDeflateStream::finish -- Finalize deflate stream
HttpInflateStream -- HTTP Inflate Stream
HttpInflateStream::factory -- HttpInflateStream class factory
HttpInflateStream::__construct -- HttpInflateStream class constructor
HttpInflateStream::update -- Update inflate stream
HttpInflateStream::flush -- Flush inflate stream
HttpInflateStream::finish -- Finalize inflate stream
HttpRequest -- HTTP Request Class
HttpRequest::addCookies -- Add cookies
HttpRequest::addHeaders -- Add headers
HttpRequest::addPostFields -- Add post fields
HttpRequest::addPostFile -- Add post file
HttpRequest::addPutData -- Add put data
HttpRequest::addQueryData -- Add query data
HttpRequest::addRawPostData -- Add raw post data
HttpRequest::addSslOptions -- Add ssl options
HttpRequest::clearHistory -- Clear history
HttpRequest::__construct -- HttpRequest constructor
HttpRequest::enableCookies -- Enable cookies
HttpRequest::getContentType -- Get content type
HttpRequest::getCookies -- Get cookies
HttpRequest::getHeaders -- Get headers
HttpRequest::getHistory -- Get history
HttpRequest::getMethod -- Get method
HttpRequest::getOptions -- Get options
HttpRequest::getPostFields -- Get post fields
HttpRequest::getPostFiles -- Get post files
HttpRequest::getPutData -- Get put data
HttpRequest::getPutFile -- Get put file
HttpRequest::getQueryData -- Get query data
HttpRequest::getRawPostData -- Get raw post data
HttpRequest::getRawRequestMessage -- Get raw request message
HttpRequest::getRawResponseMessage -- Get raw response message
HttpRequest::getRequestMessage -- Get request message
HttpRequest::getResponseBody -- Get response body
HttpRequest::getResponseCode -- Get response code
HttpRequest::getResponseCookies -- Get response cookie(s)
HttpRequest::getResponseData -- Get response data
HttpRequest::getResponseHeader -- Get response header(s)
HttpRequest::getResponseInfo -- Get response info
HttpRequest::getResponseMessage -- Get response message
HttpRequest::getResponseStatus -- Get response status
HttpRequest::getSslOptions -- Get ssl options
HttpRequest::getUrl -- Get url
HttpRequest::resetCookies -- Reset cookies
HttpRequest::send -- Send request
HttpRequest::setContentType -- Set content type
HttpRequest::setCookies -- Set cookies
HttpRequest::setHeaders -- Set headers
HttpRequest::setMethod -- Set method
HttpRequest::setOptions -- Set options
HttpRequest::setPostFields -- Set post fields
HttpRequest::setPostFiles -- Set post files
HttpRequest::setPutData -- Set put data
HttpRequest::setPutFile -- Set put file
HttpRequest::setQueryData -- Set query data
HttpRequest::setRawPostData -- Set raw post data
HttpRequest::setSslOptions -- Set ssl options
HttpRequest::setUrl -- Set URL
HttpRequestPool -- HTTP Request Pool Class
HttpRequestPool::attach -- Attach HttpRequest
HttpRequestPool::__construct -- HttpRequestPool constructor
HttpRequestPool::__destruct -- HttpRequestPool destructor
HttpRequestPool::detach -- Detach HttpRequest
HttpRequestPool::getAttachedRequests -- Get attached requests
HttpRequestPool::getFinishedRequests -- Get finished requests
HttpRequestPool::reset -- Reset request pool
HttpRequestPool::send -- Send all requests
HttpRequestPool::socketPerform -- Perform socket actions
HttpRequestPool::socketSelect -- Perform socket select
HttpResponse -- HTTP Response Class
HttpResponse::capture -- Capture script output
HttpResponse::getBufferSize -- Get buffer size
HttpResponse::getCacheControl -- Get cache control
HttpResponse::getCache -- Get cache
HttpResponse::getContentDisposition -- Get content disposition
HttpResponse::getContentType -- Get content type
HttpResponse::getData -- Get data
HttpResponse::getETag -- Get ETag
HttpResponse::getFile -- Get file
HttpResponse::getGzip -- Get gzip
HttpResponse::getHeader -- Get header
HttpResponse::getLastModified -- Get last modified
HttpResponse::getStream -- Get Stream
HttpResponse::getThrottleDelay -- Get throttle delay
HttpResponse::getRequestBody -- Get request body
HttpResponse::getRequestBodyStream -- Get request body stream
HttpResponse::getRequestHeaders -- Get request headers
HttpResponse::guessContentType -- Guess content type
HttpResponse::redirect -- Redirect
HttpResponse::send -- Send response
HttpResponse::setBufferSize -- Set buffer size
HttpResponse::setCacheControl -- Set cache control
HttpResponse::setCache -- Set cache
HttpResponse::setContentDisposition -- Set content disposition
HttpResponse::setContentType -- Set content type
HttpResponse::setData -- Set data
HttpResponse::setETag -- Set ETag
HttpResponse::setFile -- Set file
HttpResponse::setGzip -- Set gzip
HttpResponse::setHeader -- Set header
HttpResponse::setLastModified -- Set last modified
HttpResponse::setStream -- Set stream
HttpResponse::setThrottleDelay -- Set throttle delay
HttpResponse::status -- Send HTTP response status
http_cache_etag -- Caching by ETag
http_cache_last_modified -- Caching by last modification
http_chunked_decode -- Decode chunked-encoded data
http_deflate -- Deflate data
http_inflate -- Inflate data
http_get_request_body_stream -- Get request body as stream
http_get_request_body -- Get request body as string
http_get_request_headers -- Get request headers as array
http_date -- Compose HTTP RFC compliant date
http_support -- Check built-in HTTP support
http_match_etag -- Match ETag
http_match_modified -- Match last modification
http_match_request_header -- Match any header
http_build_cookie -- Build cookie string
http_negotiate_charset -- Negotiate clients preferred character set
http_negotiate_content_type -- Negotiate clients preferred content type
http_negotiate_language -- Negotiate clients preferred language
ob_deflatehandler -- Deflate output handler
ob_etaghandler -- ETag output handler
ob_inflatehandler -- Inflate output handler
http_parse_cookie -- Parse HTTP cookie
http_parse_headers -- Parse HTTP headers
http_parse_message -- Parse HTTP messages
http_parse_params -- Parse parameter list
http_persistent_handles_count -- Stat persistent handles
http_persistent_handles_ident -- Get/set ident of persistent handles
http_persistent_handles_clean -- Clean up persistent handles
http_get -- Perform GET request
http_head -- Perform HEAD request
http_post_data -- Perform POST request with pre-encoded data
http_post_fields -- Perform POST request with data to be encoded
http_put_data -- Perform PUT request with data
http_put_file -- Perform PUT request with file
http_put_stream -- Perform PUT request with stream
http_request_method_exists -- Check whether request method exists
http_request_method_name -- Get request method name
http_request_method_register -- Register request method
http_request_method_unregister -- Unregister request method
http_request -- Perform custom request
http_request_body_encode -- Encode request body
http_redirect -- Issue HTTP redirect
http_send_content_disposition -- Send Content-Disposition
http_send_content_type -- Send Content-Type
http_send_data -- Send arbitrary data
http_send_file -- Send file
http_send_last_modified -- Send Last-Modified
http_send_status -- Send HTTP response status
http_send_stream -- Send stream
http_throttle -- HTTP throttling
http_build_str -- Build query string
http_build_url -- Build an URL

Installation

(no version information, might be only in CVS)

Installation -- Installing the HTTP extension

Installation

This PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/pecl_http.

Note: The official name of this extension is pecl_http.

The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/

Installation requirements on Windows

In order to be able to load this extension on Windows, you additionally need to load the following PHP extensions: hash, iconv and SPL.

Installation requirements on other platforms

The extension must be built with libcurl support to enable request functionality (--with-http-curl-requests). A library version equal or greater to v7.12.3 is required.

To enable support for sending and receiving compressed responses, the extension must be built with zlib support (--with-http-zlib-compression). A library version equal or greater than v1.2.2 is required.

Content type quessing can be enabled by building this extension with libmagic support (--with-http-magic-mime).

Configuration

(no version information, might be only in CVS)

Configuration -- http module configuration directives

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. HTTP Configuration Options

NameDefaultChangeableDescription
http.etag.mode"MD5"PHP_INI_ALL The hashing algorithm used to generate the ETag. MD5, SHA1, and CRC32 are always available. If the hash xtension is enabled, any hashing algorithms this extension provides are available, too.
http.log.cache""PHP_INI_ALL The path (or stream wrapper url) to a log file in which to write successful cache hits.
http.log.redirect""PHP_INI_ALL The path (or stream wrapper url) to a log file in which to write redirects.
http.log.not_found""PHP_INI_ALL The path (or stream wrapper url) to a log file in which to write "file not found" errors.
http.log.allowed_methods""PHP_INI_ALL The path (or stream wrapper url) to a log file in which to write "allowed methods" violations.
http.log.composite""PHP_INI_ALL The path (or stream wrapper url) to a log file in which to write all events.
http.request.methods.allowed""PHP_INI_ALL Allowed request methods. If a client issues a request with a request method other than listed here, PHP exits with a status of "405 Method not allowed". See the INI setting http.force_exit for what "exits" means.
http.request.methods.custom""PHP_INI_PERDIR|PHP_INI_SYSTEM Custom request methods. If you want to use any non-standard request methods, you can register them with this INI setting or http_request_method_register().
http.request.datashare.cookie"0"PHP_INI_SYSTEM Whether the global HttpRequestDataShare should by default share cookie information.
http.request.datashare.dns"1"PHP_INI_SYSTEM Whether the global HttpRequestDataShare should by default share name lookup information.
http.request.datashare.ssl"0"PHP_INI_SYSTEM Whether the global HttpRequestDataShare should by default share SSL session information. This is not yet implemented in libcurl.
http.request.datashare.connect"0"PHP_INI_SYSTEM Whether the global HttpRequestDataShare should by default share connect information. This is not yet implemented in libcurl.
http.persistent.handles.limit"-1"PHP_INI_SYSTEM The maximum amount of persistent handles to keep alive.
http.persistent.handles.ident"GLOBAL"PHP_INI_ALL The ident of persistent handles.
http.send.inflate.start_auto"0"PHP_INI_PERDIR|PHP_INI_SYSTEM Whether to automatically start the inflate output handler.
http.send.inflate.start_flags"0"PHP_INI_ALL Initialization settings for the inflate output handler.
http.send.deflate.start_auto"0"PHP_INI_PERDIR|PHP_INI_SYSTEM Whether to automatically start the deflate output handler.
http.send.deflate.start_flags"0"PHP_INI_ALL Initialization settings for the deflate output handler. See deflate constants.
http.send.not_found_404"1"PHP_INI_ALL Whether to automatically exit with a status of "404 Not found", if http_send_file() was not able to find the specified file. See the INI setting http.force_exit for what "exits" means.
http.only_exceptions"0"PHP_INI_ALL Whether all notices/warnings/errors should be thrown as exceptions.
http.force_exit"1"PHP_INI_ALL Each occasion where "exits with a status of..." is mentioned, usually causes the halt of the scripting engine. Disable this option if you alternatively want to start a discarding (dev/null) output handler and continue script execution.

Resources

(no version information, might be only in CVS)

Resources -- Resources created by the HTTP extension

Resource Types

This extension defines a stream resource returned by http_get_request_body_stream() and (thereafter) HttpResponse::getStream().

Constants

(no version information, might be only in CVS)

Constants -- predefined http module constants

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Constants usable with http_support()

HTTP_SUPPORT (integer)

querying for this constant will always return TRUE

HTTP_SUPPORT_REQUESTS (integer)

whether support to issue HTTP requests is given, ie. libcurl support was compiled in

HTTP_SUPPORT_MAGICMIME (integer)

whether support to guess the Content-Type of HTTP messages is given, ie. libmagic support was compiled in

HTTP_SUPPORT_ENCODINGS (integer)

whether support for zlib encodings is given, ie. libz support was compiled in

HTTP_SUPPORT_SSLREQUESTS (integer)

whether support to issue HTTP requests over SSL is givem, ie. linked libcurl was built with SSL support

Constants usable with http_parse_params()

HTTP_PARAMS_ALLOW_COMMA (integer)

allow commans additionally to semicolons as separator

HTTP_PARAMS_ALLOW_FAILURE (integer)

continue parsing after an error occurred

HTTP_PARAMS_RAISE_ERROR (integer)

raise PHP warnings on parse errors

HTTP_PARAMS_DEFAULT (integer)

all three values above, bitwise or'ed

Constants usable with http_parse_cookie() and its return value

HTTP_COOKIE_PARSE_RAW (integer)

don't urldecode values

HTTP_COOKIE_SECURE (integer)

whether "secure" was found in the cookie's parameters list

HTTP_COOKIE_HTTPONLY (integer)

whether "httpOnly" was found in the cookie's parameter list

Constants usable with http_deflate() and HttpDeflateStream

HTTP_DEFLATE_LEVEL_DEF (integer)

HTTP_DEFLATE_LEVEL_MIN (integer)

HTTP_DEFLATE_LEVEL_MAX (integer)

HTTP_DEFLATE_TYPE_ZLIB (integer)

HTTP_DEFLATE_TYPE_GZIP (integer)

HTTP_DEFLATE_TYPE_RAW (integer)

HTTP_DEFLATE_STRATEGY_DEF (integer)

HTTP_DEFLATE_STRATEGY_FILT (integer)

HTTP_DEFLATE_STRATEGY_HUFF (integer)

HTTP_DEFLATE_STRATEGY_RLE (integer)

HTTP_DEFLATE_STRATEGY_FIXED (integer)

Constants usable with HttpDeflateStream and HttpInflateStream

HTTP_ENCODING_STREAM_FLUSH_NONE (integer)

don't flush

HTTP_ENCODING_STREAM_FLUSH_SYNC (integer)

synchronized flush only

HTTP_ENCODING_STREAM_FLUSH_FULL (integer)

full data flush

Constants used for error reporting and Exceptions

HTTP_E_RUNTIME (integer)

runtime error

HTTP_E_INVALID_PARAM (integer)

an invalid parameter was passed

HTTP_E_HEADER (integer)

header() or similar operation failed

HTTP_E_MALFORMED_HEADERS (integer)

HTTP header parse error

HTTP_E_REQUEST_METHOD (integer)

unknown/invalid request method

HTTP_E_MESSAGE_TYPE (integer)

with operation incompatible message type

HTTP_E_ENCODING (integer)

encoding/decoding error

HTTP_E_REQUEST (integer)

request failure

HTTP_E_REQUEST_POOL (integer)

request pool failure

HTTP_E_SOCKET (integer)

socket exception

HTTP_E_RESPONSE (integer)

response failure

HTTP_E_URL (integer)

invalid URL

HTTP_E_QUERYSTRING (integer)

querystring operation failure

Constants usable with HttpMessage

HTTP_MSG_NONE (integer)

the message is of no specific type

HTTP_MSG_REQUEST (integer)

request style message

HTTP_MSG_RESPONSE (integer)

response style message

Constants usable with HttpQueryString

HTTP_QUERYSTRING_TYPE_BOOL (integer)

HTTP_QUERYSTRING_TYPE_INT (integer)

HTTP_QUERYSTRING_TYPE_FLOAT (integer)

HTTP_QUERYSTRING_TYPE_STRING (integer)

HTTP_QUERYSTRING_TYPE_ARRAY (integer)

HTTP_QUERYSTRING_TYPE_OBJECT (integer)

Constants used for the httpauthtype request option

HTTP_AUTH_BASIC (integer)

use "basic" authentication

HTTP_AUTH_DIGEST (integer)

use "digest" authentication

HTTP_AUTH_NTLM (integer)

use "NTLM" authentication

HTTP_AUTH_GSSNEG (integer)

use "GSS-NEGOTIATE" authentication

HTTP_AUTH_ANY (integer)

try any authentication scheme

Constants used for the HTTP protocol version request option

HTTP_VERSION_ANY (integer)

no specific HTTP protocol version

HTTP_VERSION_1_0 (integer)

HTTP version 1.0

HTTP_VERSION_1_1 (integer)

HTTP version 1.1

Constants used for the SSL protocol type and version request option

HTTP_SSL_VERSION_ANY (integer)

no specific SSL protocol version

HTTP_SSL_VERSION_TLSv1 (integer)

use TLSv1 only

HTTP_SSL_VERSION_SSLv3 (integer)

use SSLv3 only

HTTP_SSL_VERSION_SSLv2 (integer)

use SSLv2 only

Constants used for the proxytype request option

HTTP_PROXY_SOCKS4 (integer)

the proxy is a SOCKS4 type proxy

HTTP_PROXY_SOCKS5 (integer)

the proxy is a SOCKS5 type proxy

HTTP_PROXY_HTTP (integer)

standard HTTP proxy

Constants used for the ipresolve request option

HTTP_IPRESOLVE_V4 (integer)

use IPv4 only for name lookups

HTTP_IPRESOLVE_V6 (integer)

use IPv6 only for name lookups

HTTP_IPRESOLVE_ANY (integer)

use any IP mechanism only for name lookups

Predefined HTTP request method constants

HTTP_METH_GET (integer)

HTTP_METH_HEAD (integer)

HTTP_METH_POST (integer)

HTTP_METH_PUT (integer)

HTTP_METH_DELETE (integer)

HTTP_METH_OPTIONS (integer)

HTTP_METH_TRACE (integer)

HTTP_METH_CONNECT (integer)

HTTP_METH_PROPFIND (integer)

HTTP_METH_PROPPATCH (integer)

HTTP_METH_MKCOL (integer)

HTTP_METH_COPY (integer)

HTTP_METH_MOVE (integer)

HTTP_METH_LOCK (integer)

HTTP_METH_UNLOCK (integer)

HTTP_METH_VERSION_CONTROL (integer)

HTTP_METH_REPORT (integer)

HTTP_METH_CHECKOUT (integer)

HTTP_METH_CHECKIN (integer)

HTTP_METH_UNCHECKOUT (integer)

HTTP_METH_MKWORKSPACE (integer)

HTTP_METH_UPDATE (integer)

HTTP_METH_LABEL (integer)

HTTP_METH_MERGE (integer)

HTTP_METH_BASELINE_CONTROL (integer)

HTTP_METH_MKACTIVITY (integer)

HTTP_METH_ACL (integer)

Constants usable with http_redirect()

HTTP_REDIRECT (integer)

guess applicable redirect method

HTTP_REDIRECT_PERM (integer)

permanent redirect (301 Moved permanently)

HTTP_REDIRECT_FOUND (integer)

standard redirect (302 Found)

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

HTTP_REDIRECT_POST (integer)

redirect applicable to POST requests (303 See other)

HTTP_REDIRECT_PROXY (integer)

proxy redirect (305 Use proxy)

HTTP_REDIRECT_TEMP (integer)

temporary redirect (307 Temporary Redirect)

Constants usable with http_build_url()

HTTP_URL_REPLACE (integer)

replace every part of the first URL when there's one of the second URL

HTTP_URL_JOIN_PATH (integer)

join relative paths

HTTP_URL_JOIN_QUERY (integer)

join query strings

HTTP_URL_STRIP_USER (integer)

strip any user authentication information

HTTP_URL_STRIP_PASS (integer)

strip any password authentication information

HTTP_URL_STRIP_AUTH (integer)

strip any authentication information

HTTP_URL_STRIP_PORT (integer)

strip explicit port numbers

HTTP_URL_STRIP_PATH (integer)

strip complete path

HTTP_URL_STRIP_QUERY (integer)

strip query string

HTTP_URL_STRIP_FRAGMENT (integer)

strip any fragments (#identifier)

HTTP_URL_STRIP_ALL (integer)

strip anything but scheme and host

Request Options

(no version information, might be only in CVS)

Request Options -- options usable with the HttpRequest class and request functions

Overview

Options related to time outs

timeout (integer)

seconds the whole request may take to complete

connecttimeout (integer)

seconds the connect, including name resolving, may take

dns_cache_timeout (integer)

seconds after an dns cache entry times out

Options related to urls

url (string)

the request url

port (integer)

use another port as specified in the url

redirect (integer)

whether and how many redirects to follow; defaults to 0

unrestrictedauth (bool)

whether to continue sending credentials on redirects to a different host

referer (string)

the refererring url to send

Options related to cookies

encodecookies (bool)

whether custom cookies should be urlencode()d prior sending

cookies (array)

list of cookies as associative array like array("cookie" => "value")

cookiestore (string)

path to a file where cookies are/will be stored

cookiesession (bool)

don't load session cookies from cookiestore if TRUE

Options related to headers

useragent (string)

the user agent to send; defaults to PECL::HTTP/x.y.z (PHP/x.y.z); omitted if explicitly set to an empty string

lastmodified (int)

timestamp for If-(Un)Modified-Since header

etag (string)

quoted etag for If-(None-)Match header

headers (array)

list of custom headers as associative array like array("header" => "value")

Options related to authentication

httpauth (string)

http credentials in "user:pass" format

httpauthtype (int)

HTTP authentication type constant

(array)

Options related to proxies

proxyhost (string)

proxy host in "host[:port]" format

proxyport (int)

use another proxy port as specified in proxyhost

proxytype (int)

HTTP proxy type constant

proxyauth (string)

proxy credentials in "user:pass" format

proxyauthtype (int)

HTTP authentication type constant

Options related to the transfer

compress (bool)

whether to request and accept a gzip/deflate content encoded response

resume (int)

start the download at the specified byte offset if server support is given (indicated by a 206 response code)

range (array)

array of arrays, each containing two integers, specifying the ranges to download if server support is given (indicated by a 206 response code); only recognized if the resume option is empty

Options imposing limits

maxfilesize (integer)

maximum file size that should be downloaded; has no effect, if the size of the requested entity is unknown (eg. dynamic pages with chunked transfer encoding etc.)

low_speed_limit (int)

the lowest transfer speed a successful request may have

low_speed_time (int)

the time in which low_speed_limit must be transferred for a successful request

max_send_speed (int)

maximum send speed in bytes per second

max_recv_speed (int)

maximum receive speed in bytes per second

Callback options

onprogress (callback)

progress callback

Network options

interface (string)

outgoing network interface (ifname, ip or hostname)

portrange (array)

2 integers specifying outgoing portrange to try

SSL options

ssl (array)

Note: SSL options are set through an array with the single "ssl" request option name.

cert (string)

path to certificate

certtype (string)

type of certificate

certpasswd (string)

password for certificate

key (string)

path to key

keytype (string)

type of key

keypasswd (string)

pasword for key

engine (string)

ssl engine to use

version (int)

ssl version to use

verifypeer (bool)

whether to verify the peer

verifyhost (bool)

whether to verify the host

cipher_list (string)

list of allowed ciphers

cainfo (string)

capath (string)

random_file (string)

egdsocket (string)

HttpMessage

(no version information, might be only in CVS)

HttpMessage -- HTTP Message Class

Synopsis

class HttpMessage implements Iterator, Countable, Serializable

Class Members

Properties

Table 1. Instance Properties

ModifiersTypeNameDescription
protectedinttypemessage type
protectedstringbodymessage body
protectedfloathttpVersionHTTP protocol version
protectedarrayheadersmessage headers
protectedstringrequestMethodrequest method name
protectedrequestUrlstringrequest URL
protectedintresponseCoderesponse code
protectedstringresponseStatusresponse status message
protectedHttpMessageparentMessagereference to parent message

Note: None of these default properties can be accessed by reference, array key/index notation nor be used in increment or decrement operations.

Predefined Constants

Table 2.

TypeNameDescription
intTYPE_NONEmessage has is of no specific type
intTYPE_REQUESTmessage is a request style HTTP message
intTYPE_RESPONSEmessage is a response style HTTP message

HttpMessage::__construct

(no version information, might be only in CVS)

HttpMessage::__construct -- HttpMessage constructor

Description

publicvoid HttpMessage::__construct ( [string message] )

Instantiate a new HttpMessage object.

The constructed object will actually represent the last message of the passed string. If there were prior messages, those can be accessed by HttpMessage::getParentMessage().

Parameters

message

a single or several consecutive HTTP messages

Errors/Exceptions

Throws HttpMalformedHeaderException.

HttpMessage::factory

(no version information, might be only in CVS)

HttpMessage::factory -- Create HttpMessage from string

Description

static publicHttpMessage HttpMessage::factory ( [string raw_message [, string class_name = 'HttpMessage']] )

Create an HttpMessage object from a string.

Parameters

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

Errors/Exceptions

Throws HttpMalformedHeadersException.

See Also

HttpMessage::fromEnv().

HttpMessage::fromEnv

(no version information, might be only in CVS)

HttpMessage::fromEnv -- Create HttpMessage from environment

Description

static publicHttpMessage HttpMessage::fromEnv ( int message_type [, string class_name = 'HttpMessage'] )

Create an HttpMessage object from script environment.

Parameters

message_type

The message type. See HttpMessage type constants.

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

See Also

HttpMessage::factory().

HttpMessage::fromString

(no version information, might be only in CVS)

HttpMessage::fromString -- Create HttpMessage from string

Description

static publicHttpMessage HttpMessage::fromString ( [string raw_message [, string class_name = 'HttpMessage']] )

Create an HttpMessage object from a string.

This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.

Parameters

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

Errors/Exceptions

Throws HttpMalformedHeadersException.

See Also

HttpMessage::factory().

HttpMessage::toString

(no version information, might be only in CVS)

HttpMessage::toString -- Get string representation

Description

publicstring HttpMessage::toString ( [bool include_parent = FALSE] )

Get the string representation of the Message.

Parameters

include_parent

specifies whether the returned string should also contain any parent messages

Return Values

Returns the message as string.

HttpMessage::toMessageTypeObject

(no version information, might be only in CVS)

HttpMessage::toMessageTypeObject -- Create HTTP object regarding message type

Description

publicHttpRequest|HttpResponse HttpMessage::toMessageTypeObject ( void )

Creates an object regarding to the type of the message.

Parameters

Return Values

Returns either an HttpRequest or HttpResponse object on success, or NULL on failure.

Errors/Exceptions

Throws HttpRuntimeException, HttpMessageTypeException, HttpHeaderException.

HttpMessage::guessContentType

(no version information, might be only in CVS)

HttpMessage::guessContentType -- Guess content type

Description

publicstring HttpMessage::guessContentType ( string magic_file [, int magic_mode = MAGIC_MIME] )

Attempts to guess the content type of the message body through libmagic.

Parameters

magic_file

the magic.mime database to use

magic_mode

flags for libmagic

Return Values

Returns the guessed content type on success, or FALSE on failure.

Errors/Exceptions

Throws HttpRuntimeException, HttpInvalidParamException.

HttpMessage::detach

(no version information, might be only in CVS)

HttpMessage::detach -- Detach HttpMessage

Description

publicHttpMessage HttpMessage::detach ( void )

Returns a clone of an HttpMessage object detached from any parent messages.

Parameters

Return Values

Returns detached HttpMessage object copy.

HttpMessage::prepend

(no version information, might be only in CVS)

HttpMessage::prepend -- Prepend message(s)

Description

publicvoid HttpMessage::prepend ( HttpMessage message [, bool top = TRUE] )

Prepends message(s) to the HTTP message.

Parameters

message

HttpMessage object to prepend

top

whether to prepend to the top most or right this message

Errors/Exceptions

Throws HttpInvalidParamException if the message is located within the same message chain.

HttpMessage::reverse

(no version information, might be only in CVS)

HttpMessage::reverse -- Reverse message chain

Description

publicHttpMessage HttpMessage::reverse ( void )

Reorders the message chain in reverse order.

Return Values

Returns the most parent HttpMessage object.

HttpMessage::send

(no version information, might be only in CVS)

HttpMessage::send -- Send message

Description

publicbool HttpMessage::send ( void )

Send the Message according to its type as Response or Request.

This provides limited functionality compared to HttpRequest and HttpResponse.

Return Values

Returns TRUE on success or FALSE on failure.

HttpMessage::getParentMessage

(no version information, might be only in CVS)

HttpMessage::getParentMessage -- Get parent message

Description

publicHttpMessage HttpMessage::getParentMessage ( void )

Get parent Message.

Return Values

Returns the parent HttpMessage object.

Errors/Exceptions

Throws HttpRuntimeException.

HttpMessage::getType

(no version information, might be only in CVS)

HttpMessage::getType -- Get message type

Description

publicint HttpMessage::getType ( void )

Get Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Return Values

Returns the HttpMessage::TYPE.

HttpMessage::setType

(no version information, might be only in CVS)

HttpMessage::setType -- Set message type

Description

publicvoid HttpMessage::setType ( int type )

Set Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Parameters

type

the HttpMessage::TYPE

HttpMessage::getHttpVersion

(no version information, might be only in CVS)

HttpMessage::getHttpVersion -- Get HTTP version

Description

publicstring HttpMessage::getHttpVersion ( void )

Get the HTTP Protocol Version of the Message.

Return Values

Returns the HTTP protocol version as string.

HttpMessage::setHttpVersion

(no version information, might be only in CVS)

HttpMessage::setHttpVersion -- Set HTTP version

Description

publicbool HttpMessage::setHttpVersion ( string version )

Set the HTTP Protocol version of the Message.

Parameters

version

the HTTP protocol version

Return Values

Returns TRUE on success, or FALSE if supplied version is out of range (1.0/1.1).

HttpMessage::getHeaders

(no version information, might be only in CVS)

HttpMessage::getHeaders -- Get message headers

Description

publicarray HttpMessage::getHeaders ( void )

Get message headers.

Return Values

Returns an associative array containing the messages HTTP headers.

HttpMessage::getHeader

(no version information, might be only in CVS)

HttpMessage::getHeader -- Get header

Description

publicstring HttpMessage::getHeader ( string header )

Get message header.

Parameters

header

header name

Return Values

Returns the header value on success or NULL if the header does not exist.

HttpMessage::addHeaders

(no version information, might be only in CVS)

HttpMessage::addHeaders -- Add headers

Description

publicvoid HttpMessage::addHeaders ( array headers [, bool append = FALSE] )

Add headers. If append is true, headers with the same name will be separated, else overwritten.

Parameters

headers

associative array containing the additional HTTP headers to add to the messages existing headers

append

if true, and a header with the same name of one to add exists already, this respective header will be converted to an array containing both header values, otherwise it will be overwritten with the new header value

Return Values

Returns TRUE on success or FALSE on failure.

HttpMessage::setHeaders

(no version information, might be only in CVS)

HttpMessage::setHeaders -- Set headers

Description

publicvoid HttpMessage::setHeaders ( array headers )

Sets new headers.

Parameters

headers

associative array containing the new HTTP headers, which will replace all previous HTTP headers of the message

HttpMessage::getBody

(no version information, might be only in CVS)

HttpMessage::getBody -- Get message body

Description

publicstring HttpMessage::getBody ( void )

Get the body of the parsed HttpMessage.

Return Values

Returns the message body as string.

HttpMessage::setBody

(no version information, might be only in CVS)

HttpMessage::setBody -- Set message body

Description

publicvoid HttpMessage::setBody ( string body )

Set the body of the HttpMessage.

Note: Don't forget to update any headers accordingly.

Parameters

body

the new body of the message

HttpMessage::getRequestMethod

(no version information, might be only in CVS)

HttpMessage::getRequestMethod -- Get request method

Description

publicstring HttpMessage::getRequestMethod ( void )

Get the Request Method of the Message.

Return Values

Returns the request method name on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST.

HttpMessage::setRequestMethod

(no version information, might be only in CVS)

HttpMessage::setRequestMethod -- Set request method

Description

publicbool HttpMessage::setRequestMethod ( string method )

Set the Request Method of the HTTP Message.

Parameters

method

the request method name

Return Values

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST or an invalid request method was supplied.

HttpMessage::getRequestUrl

(no version information, might be only in CVS)

HttpMessage::getRequestUrl -- Get request URL

Description

publicstring HttpMessage::getRequestUrl ( void )

Get the Request URL of the Message.

Parameters

Return Values

Returns the request URL as string on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST.

HttpMessage::setRequestUrl

(no version information, might be only in CVS)

HttpMessage::setRequestUrl -- Set request URL

Description

publicbool HttpMessage::setRequestUrl ( string url )

Set the Request URL of the HTTP Message.

Parameters

url

the request URL

Return Values

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST or supplied URL was empty.

HttpMessage::getResponseCode

(no version information, might be only in CVS)

HttpMessage::getResponseCode -- Get response code

Description

publicint HttpMessage::getResponseCode ( void )

Get the Response Code of the Message.

Return Values

Returns the HTTP response code if the message is of type HttpMessage::TYPE_RESPONSE, else FALSE.

HttpMessage::setResponseCode

(no version information, might be only in CVS)

HttpMessage::setResponseCode -- Set response code

Description

publicbool HttpMessage::setResponseCode ( int code )

Set the response code of an HTTP Response Message.

Parameters

code

HTTP response code

Return Values

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_RESPONSE or the response code is out of range (100-510).

HttpMessage::getResponseStatus

(no version information, might be only in CVS)

HttpMessage::getResponseStatus -- Get response status

Description

publicstring HttpMessage::getResponseStatus ( void )

Get the Response Status of the message (i.e. the string following the response code).

Return Values

Returns the HTTP response status string if the message is of type HttpMessage::TYPE_RESPONSE, else FALSE.

HttpMessage::setResponseStatus

(no version information, might be only in CVS)

HttpMessage::setResponseStatus -- Set response status

Description

publicbool HttpMessage::setResponseStatus ( string status )

Set the Response Status of the HTTP message (i.e. the string following the response code).

Parameters

status

the response status text

Return Values

Returns TRUE on success or FALSE if the message is not of type HttpMessage::TYPE_RESPONSE.

HttpQueryString

(no version information, might be only in CVS)

HttpQueryString -- HTTP Query String Class

Synopsis

class HttpQueryString implements Serializable, ArrayAccess

Class Members

Properties

Table 1. Instance Properties

ModifiersTypeNameDescription
privatearrayqueryArrayquery parameters
privatestringqueryStringserialized query parameters

Table 2. Static Properties

ModifiersTypeNameDescription
privatearrayinstanceholds singletons

Predefined Constants

Table 3.

TypeNameDescription
intTYPE_BOOLretrieve query param as bool
intTYPE_INTretrieve query param as int
intTYPE_FLOATretrieve query param as float
intTYPE_STRINGretrieve query param as string
intTYPE_ARRAYretrieve query param as array
intTYPE_OBJECTretrieve query param as object

HttpQueryString::__construct

(no version information, might be only in CVS)

HttpQueryString::__construct -- HttpQueryString constructor

Description

final publicvoid HttpQueryString::__construct ( [bool global = TRUE [, mixed add]] )

Creates a new HttpQueryString object instance.

Operates on and modifies $_GET and $_SERVER['QUERY_STRING'] if global is TRUE.

Parameters

global

whether to operate on $_GET and $_SERVER['QUERY_STRING']

add

additional/initial query string parameters

Errors/Exceptions

Throws HttpRuntimeException.

HttpQueryString::singleton

(no version information, might be only in CVS)

HttpQueryString::singleton -- HttpQueryString singleton

Description

static publicHttpQueryString HttpQueryString::singleton ( [bool global = TRUE] )

Get a single instance (differentiates between the global setting).

Parameters

global

whether to operate on $_GET and $_SERVER['QUERY_STRING']

Return Values

Returns always the same HttpQueryString instance regarding the global setting.

Errors/Exceptions

Throws HttpRuntimeException.

HttpQueryString::get

(no version information, might be only in CVS)

HttpQueryString::get -- Get (part of) query string

Description

publicmixed HttpQueryString::get ( [string key [, mixed type = 0 [, mixed defval = NULL [, bool delete = FALSE]]]] )

Get (part of) the query string.

The type parameter is either one of the HttpQueryString::TYPE_* constants or a type abbreviation like "b" for bool, "i" for int, "f" for float, "s" for string, "a" for array and "o" for a stdClass object.

Parameters

key

key of the query string param to retrieve

type

which variable type to enforce

defval

default value if key does not exist

delete

whether to remove the key/value pair from the query string

Return Values

Returns the value of the query string param or the whole query string if no key was specified on success or defval if key does not exist.

HttpQueryString::mod

(no version information, might be only in CVS)

HttpQueryString::mod -- Modifiy query string copy

Description

publicHttpQueryString HttpQueryString::mod ( mixed params )

Copies the query string object and sets provided params at the clone.

Parameters

params

query string params to add

Return Values

Returns a new HttpQueryString object

HttpQueryString::set

(no version information, might be only in CVS)

HttpQueryString::set -- Set query string params

Description

publicstring HttpQueryString::set ( mixed params )

Set query string entry/entries. NULL values will unset the variable.

Parameters

params

query string params to add

Return Values

Returns the current query string.

HttpQueryString::toArray

(no version information, might be only in CVS)

HttpQueryString::toArray -- Get query string as array

Description

publicarray HttpQueryString::toArray ( void )

Get the query string represented as associative array.

Return Values

Returns the array representation of the query string.

HttpQueryString::toString

(no version information, might be only in CVS)

HttpQueryString::toString -- Get query string

Description

publicstring HttpQueryString::toString ( void )

Get the query string.

Parameters

Return Values

Returns the string representation of the query string.

HttpQueryString::xlate

(no version information, might be only in CVS)

HttpQueryString::xlate -- Change query strings charset

Description

publicbool HttpQueryString::xlate ( string ie, string oe )

Converts the query string from the source encoding ie to the target encoding oe.

Warning

Don't use any character set that can contain NUL bytes like UTF-16.

Note: This method requires ext/iconv to be enabled and loaded.

Parameters

ie

input encoding

oe

output encoding

Return Values

Returns TRUE on success or FALSE on failure.

HttpDeflateStream

(no version information, might be only in CVS)

HttpDeflateStream -- HTTP Deflate Stream Class

Synopsis

class HttpDeflateStream

Class Members

Predefined Constants

Table 1.

TypeNameDescription
intTYPE_GZIPgzip encoding
intTYPE_ZLIBzlib AKA deflate encoding
intTYPE_RAWraw deflate encoding
intLEVEL_DEFdefault compression level
intLEVEL_MINminimum compression level
intLEVEL_MAXmaximum compression level
intSTRATEGY_DEFdefault strategy
intSTRATEGY_FILTfiltered strategy
intSTRATEGY_HUFFHuffman strategy
intSTRATEGY_RLERLE strategy
intSTRATEGY_FIXEDfixed strategy
intFLUSH_NONEno forced flush
intFLUSH_SYNCsynching flush
intFLUSH_FULLfull flush

Examples

Example 1. A HttpDeflateStream example

<?php
$stream = new HttpDeflateStream(
    HttpDeflateStream::TYPE_GZIP |
    HttpDeflateStream::LEVEL_MAX |
    HttpDeflateStream::FLUSH_SYNC);

echo $stream->update($data);
echo $stream->finish();
?>

HttpDeflateStream::factory

(no version information, might be only in CVS)

HttpDeflateStream::factory -- HttpDeflateStream class factory

Description

publicHttpDeflateStream HttpDeflateStream::factory ( [int flags = 0 [, string class_name = 'HttpDeflateStream']] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parameters

flags

initialization flags

class_name

name of a subclass of HttpDeflateStream

HttpDeflateStream::__construct

(no version information, might be only in CVS)

HttpDeflateStream::__construct -- HttpDeflateStream class constructor

Description

publicvoid HttpDeflateStream::__construct ( [int flags = 0] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parameters

flags

initialization flags

HttpDeflateStream::update

(no version information, might be only in CVS)

HttpDeflateStream::update -- Update deflate stream

Description

publicstring HttpDeflateStream::update ( string data )

Passes more data through the deflate stream.

Parameters

data

data to deflate

Return Values

Returns deflated data on success or FALSE on failure.

HttpDeflateStream::flush

(no version information, might be only in CVS)

HttpDeflateStream::flush -- Flush deflate stream

Description

publicstring HttpDeflateStream::flush ( [string data] )

Flushes the deflate stream.

Parameters

data

more data to deflate

Return Values

Returns some deflated data as string on success or FALSE on failure.

HttpDeflateStream::finish

(no version information, might be only in CVS)

HttpDeflateStream::finish -- Finalize deflate stream

Description

publicstring HttpDeflateStream::finish ( [string data] )

Finalizes the deflate stream. The deflate stream can be reused after finalizing.

Parameters

data

data to deflate

Return Values

Returns the final part of deflated data.

HttpInflateStream

(no version information, might be only in CVS)

HttpInflateStream -- HTTP Inflate Stream

Synopsis

class HttpInflateStream

Class Members

Constants

Table 1.

TypeNameDescription
intFLUSH_NONEno forced flush
intFLUSH_SYNCsynching flush
intFLUSH_FULLfull flush

Note: Flushing usually has no effect on inflate streams.

Examples

Example 1. A HttpInflateStream example

<?php
$stream = new HttpInflateStream;
echo $stream->update($data);
echo $stream->finish();
?>

HttpInflateStream::factory

(no version information, might be only in CVS)

HttpInflateStream::factory -- HttpInflateStream class factory

Description

publicHttpInflateStream HttpInflateStream::factory ( [int flags = 0 [, string class_name = 'HttpInflateStream']] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parameters

flags

initialization flags

class_name

name of a subclass of HttpInflateStream

HttpInflateStream::__construct

(no version information, might be only in CVS)

HttpInflateStream::__construct -- HttpInflateStream class constructor

Description

publicvoid HttpInflateStream::__construct ( [int flags = 0] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parameters

flags

initialization flags

HttpInflateStream::update

(no version information, might be only in CVS)

HttpInflateStream::update -- Update inflate stream

Description

publicstring HttpInflateStream::update ( string data )

Passes more data through the inflate stream.

Parameters

data

data to inflate

Return Values

Returns inflated data on success or FALSE on failure.

HttpInflateStream::flush

(no version information, might be only in CVS)

HttpInflateStream::flush -- Flush inflate stream

Description

publicstring HttpInflateStream::flush ( [string data] )

Flushes the inflate stream.

Note: Flushing usually has no effect on inflate streams.

Parameters

data

more data to inflate

Return Values

Returns some inflated data as string on success or FALSE on failure.

HttpInflateStream::finish

(no version information, might be only in CVS)

HttpInflateStream::finish -- Finalize inflate stream

Description

publicstring HttpInflateStream::finish ( [string data] )

Finalizes the inflate stream. The inflate stream can be reused after finalizing.

Parameters

data

data to inflate

Return Values

Returns the final part of inflated data.

HttpRequest

(no version information, might be only in CVS)

HttpRequest -- HTTP Request Class

Synopsis

class HttpRequest

Class Members

Properties

Table 1. Instance Properties

ModifiersTypeNameDescription
protectedarrayoptionsrequest options to configure the request; see request options
protectedarraypostFieldsform data: array("fieldname" => "fieldvalue")
protectedarraypostFilesfiles to upload: array(array("name" => "image", "file" => "/home/u/images/u.png", "type" => "image/png"))
protectedarrayresponseInfoinformation (statistical) about the request/response; see Request/response information
protectedHttpMessageresponseMessagethe response message
protectedintegerresponseCodethe numerical response code
protectedstringresponseStatusthe literal response status text
protectedintegermethodthe request method to use
protectedstringurlthe request url
protectedstringcontentTypethe content type to use for raw post requests
protectedstringrawPostDataraw post data
protectedstringqueryDataquery parameters
protectedstringputFilethe file to upload with a PUT request
protectedstringputDataraw data to upload with a PUT request
protectedHttpMessagehistorythe whole request/response history if history logging is enabled
publicbooleanrecordHistorywhether to enable history logging

Predefined Constants

Table 2.

TypeNameDescription
integerMETH_GETGET request method
integerMETH_HEADHEAD request method
integerMETH_POSTPOST request method
integerMETH_PUTPUT request method
integerMETH_DELETEDELETE request method
integerMETH_OPTIONSOPTIONS request method
integerMETH_TRACETRACE request method
integerMETH_CONNECTCONNECT request method
integerMETH_PROPFINDPROPFIND request method
integerMETH_PROPPATCHPROPPATCH request method
integerMETH_MKCOLMKCOL request method
integerMETH_COPYCOPY request method
integerMETH_MOVEMOVE request method
integerMETH_LOCKLOCK request method
integerMETH_UNLOCKUNLOCK request method
integerMETH_VERSION_CONTROLVERSION-CONTROL request method
integerMETH_REPORTREPORT request method
integerMETH_CHECKOUTCHECKOUT request method
integerMETH_CHECKINCHECKIN request method
integerMETH_UNCHECKOUTUNCHECKOUT request method
integerMETH_MKWORKSPACEMKWORKSPACE request method
integerMETH_UPDATEUPDATE request method
integerMETH_LABELLABEL request method
integerMETH_MERGEMERGE request method
integerMETH_BASELINE_CONTROLBASELINE-CONTROL request method
integerMETH_MKACTIVITYMKACTIVITY request method
integerMETH_ACLACL request method
integerVERSION_1_0HTTP protocol version 1.0
integerVERSION_1_1HTTP protocol version 1.1
integerVERSION_ANYany HTTP protocol version
integerAUTH_BASICbasic authentication
integerAUTH_DIGESTdigest authentication
integerAUTH_NTLMNTLM authentication
integerAUTH_GSSNEGGSS negotiate authentication
integerAUTH_ANYany authentication
integerPROXY_SOCKS4SOCKS v4 proxy
integerPROXY_SOCKS5SOCKS v5 proxy
integerPROXY_HTTPHTTP proxy
integerSSL_VERSION_TLSv1use TLS v1
integerSSL_VERSION_SSLv2use SSL v2
integerSSL_VERSION_SSLv3use SSL v3
integerSSL_VERSION_ANYuse any SSL/TLS method
integerIPRESOLVE_V4resolve via IPv4 only
integerIPRESOLVE_V6resolve via IPv6 only
integerIPRESOLVE_ANYuse any resolving methods

HttpRequest::addCookies

(no version information, might be only in CVS)

HttpRequest::addCookies -- Add cookies

Description

publicbool HttpRequest::addCookies ( array cookies )

Add custom cookies.

Note: The request option encodecookies controls whether the cookie values should be urlencode()d.

Note: Affects any request method.

Parameters

cookies

an associative array containing any cookie name/value pairs to add

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A HttpRequest::addCookies() example

<?php
$r = new HttpRequest;
$r->addCookies(
    array(
        "cookie_name" => "cookie value",
    )
);
?>

See Also

HttpRequest::setCookies()

HttpRequest::addHeaders

(no version information, might be only in CVS)

HttpRequest::addHeaders -- Add headers

Description

publicbool HttpRequest::addHeaders ( array headers )

Add request header name/value pairs.

Parameters

headers

an associative array as parameter containing additional header name/value pairs

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::addPostFields

(no version information, might be only in CVS)

HttpRequest::addPostFields -- Add post fields

Description

publicbool HttpRequest::addPostFields ( array post_data )

Adds POST data entries, leaving previously set unchanged, unless a post entry with the same name already exists.

Affects only POST and custom requests.

Parameters

post_data

an associative array as parameter containing the post fields

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::addPostFile

(no version information, might be only in CVS)

HttpRequest::addPostFile -- Add post file

Description

publicbool HttpRequest::addPostFile ( string name, string file [, string content_type = 'application/x-octetstream'] )

Add a file to the POST request, leaving previously set files unchanged.

Affects only POST and custom requests. Cannot be used with raw post data.

Parameters

name

the form element name

file

the path to the file

content_type

the content type of the file

Return Values

Returns TRUE on success, or FALSE if the content type seems not to contain a primary and a secondary content type part.

HttpRequest::addPutData

(no version information, might be only in CVS)

HttpRequest::addPutData -- Add put data

Description

publicbool HttpRequest::addPutData ( string put_data )

Add PUT data, leaving previously set PUT data unchanged.

Affects only PUT requests.

Parameters

put_data

the data to concatenate

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::addQueryData

(no version information, might be only in CVS)

HttpRequest::addQueryData -- Add query data

Description

publicbool HttpRequest::addQueryData ( array query_params )

Add parameters to the query parameter list, leaving previously set unchanged.

Affects any request type.

Parameters

query_params

an associative array as parameter containing the query fields to add

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::addRawPostData

(no version information, might be only in CVS)

HttpRequest::addRawPostData -- Add raw post data

Description

publicbool HttpRequest::addRawPostData ( string raw_post_data )

Add raw post data, leaving previously set raw post data unchanged.

Affects only POST and custom requests.

Parameters

raw_post_data

the raw post data to concatenate

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::addSslOptions

(no version information, might be only in CVS)

HttpRequest::addSslOptions -- Add ssl options

Description

publicbool HttpRequest::addSslOptions ( array options )

Set additional SSL options.

Parameters

options

an associative array as parameter containing additional SSL specific options

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::clearHistory

(no version information, might be only in CVS)

HttpRequest::clearHistory -- Clear history

Description

publicvoid HttpRequest::clearHistory ( void )

Clears all history messages.

Note: History is only logged if recordHistory was enabled.

HttpRequest::__construct

(no version information, might be only in CVS)

HttpRequest::__construct -- HttpRequest constructor

Description

publicvoid HttpRequest::__construct ( [string url [, int request_method = HTTP_METH_GET [, array options]]] )

Instantiate a new HttpRequest object.

Parameters

url

the target request url

request_method

the request method to use

options

an associative array with request options

Errors/Exceptions

Throws HttpException.

HttpRequest::enableCookies

(no version information, might be only in CVS)

HttpRequest::enableCookies -- Enable cookies

Description

publicbool HttpRequest::enableCookies ( void )

Enable automatic sending of received cookies.

Note: Note that cuutomly set cookies will be sent anyway.

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::getContentType

(no version information, might be only in CVS)

HttpRequest::getContentType -- Get content type

Description

publicstring HttpRequest::getContentType ( void )

Get the previously set content type.

Return Values

Returns the previously set content type as string.

HttpRequest::getCookies

(no version information, might be only in CVS)

HttpRequest::getCookies -- Get cookies

Description

publicarray HttpRequest::getCookies ( void )

Get previously set cookies.

Return Values

Returns an associative array containing any previously set cookies.

HttpRequest::getHeaders

(no version information, might be only in CVS)

HttpRequest::getHeaders -- Get headers

Description

publicarray HttpRequest::getHeaders ( void )

Get previously set request headers.

Return Values

Returns an associative array containing all currently set headers.

HttpRequest::getHistory

(no version information, might be only in CVS)

HttpRequest::getHistory -- Get history

Description

publicHttpMessage HttpRequest::getHistory ( void )

Get all sent requests and received responses as an HttpMessage object.

If you want to record history, set the instance variable HttpRequest::recordHistory to TRUE.

The returned object references the last received response, use HttpMessage::getParentMessage()() to access the data of previously sent requests and received responses.

Return Values

Returns an HttpMessage object representing the complete request/response history.

Errors/Exceptions

Throws HttpRuntimeException.

HttpRequest::getMethod

(no version information, might be only in CVS)

HttpRequest::getMethod -- Get method

Description

publicint HttpRequest::getMethod ( void )

Get the previously set request method.

Return Values

Returns the currently set request method.

HttpRequest::getOptions

(no version information, might be only in CVS)

HttpRequest::getOptions -- Get options

Description

publicarray HttpRequest::getOptions ( void )

Get currently set options.

Return Values

Returns an associative array containing currently set options.

HttpRequest::getPostFields

(no version information, might be only in CVS)

HttpRequest::getPostFields -- Get post fields

Description

publicarray HttpRequest::getPostFields ( void )

Get previously set POST data.

Parameters

Return Values

Returns the currently set post fields as associative array.

HttpRequest::getPostFiles

(no version information, might be only in CVS)

HttpRequest::getPostFiles -- Get post files

Description

publicarray HttpRequest::getPostFiles ( void )

Get all previously added POST files.

Return Values

Returns an array containing currently set post files.

HttpRequest::getPutData

(no version information, might be only in CVS)

HttpRequest::getPutData -- Get put data

Description

publicstring HttpRequest::getPutData ( void )

Get previously set PUT data.

Return Values

Returns a string containing the currently set PUT data.

HttpRequest::getPutFile

(no version information, might be only in CVS)

HttpRequest::getPutFile -- Get put file

Description

publicstring HttpRequest::getPutFile ( void )

Get previously set put file.

Return Values

Returns a string containing the path to the currently set put file.

HttpRequest::getQueryData

(no version information, might be only in CVS)

HttpRequest::getQueryData -- Get query data

Description

publicstring HttpRequest::getQueryData ( void )

Get the current query data in form of an urlencoded query string.

Return Values

Returns a string containing the urlencoded query.

HttpRequest::getRawPostData

(no version information, might be only in CVS)

HttpRequest::getRawPostData -- Get raw post data

Description

publicstring HttpRequest::getRawPostData ( void )

Get previously set raw post data.

Parameters

Return Values

Returns a string containing the currently set raw post data.

HttpRequest::getRawRequestMessage

(no version information, might be only in CVS)

HttpRequest::getRawRequestMessage -- Get raw request message

Description

publicstring HttpRequest::getRawRequestMessage ( void )

Get sent HTTP message.

Parameters

Return Values

Returns an HttpMessage in a form of a string.

HttpRequest::getRawResponseMessage

(no version information, might be only in CVS)

HttpRequest::getRawResponseMessage -- Get raw response message

Description

publicstring HttpRequest::getRawResponseMessage ( void )

Get the entire HTTP response.

Parameters

Return Values

Returns the complete web server response, including the headers in a form of a string.

HttpRequest::getRequestMessage

(no version information, might be only in CVS)

HttpRequest::getRequestMessage -- Get request message

Description

publicHttpMessage HttpRequest::getRequestMessage ( void )

Get sent HTTP message.

If redirects were allowed and several responses were received, the data references the last received response. Use HttpMessage::getParentMessage() to access the data of previously sent requests within this request cycle.

Note: Note that the internal request message is immutable, that means that the request message received through HttpRequest::getRequestMessage() will always look the same for the same request, regardless of any changes you may have made to the returned object.

Return Values

Returns an HttpMessage object representing the sent request.

Errors/Exceptions

Throws HttpMalformedHeadersException, HttpEncodingException.

HttpRequest::getResponseBody

(no version information, might be only in CVS)

HttpRequest::getResponseBody -- Get response body

Description

publicstring HttpRequest::getResponseBody ( void )

Get the response body after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parameters

Return Values

Returns a string containing the response body.

HttpRequest::getResponseCode

(no version information, might be only in CVS)

HttpRequest::getResponseCode -- Get response code

Description

publicint HttpRequest::getResponseCode ( void )

Get the response code after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Return Values

Returns an int representing the response code.

HttpRequest::getResponseCookies

(no version information, might be only in CVS)

HttpRequest::getResponseCookies -- Get response cookie(s)

Description

publicarray HttpRequest::getResponseCookies ( [int flags [, array allowed_extras]] )

Get response cookie(s) after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parameters

flags

http_parse_cookie() flags

allowed_extras

allowed keys treated as extra information instead of cookie names

Return Values

Returns an array of stdClass objects like http_parse_cookie() would return.

HttpRequest::getResponseData

(no version information, might be only in CVS)

HttpRequest::getResponseData -- Get response data

Description

publicarray HttpRequest::getResponseData ( void )

* Get all response data after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Return Values

Returns an associative array with the key "headers" containing an associative array holding all response headers, as well as the key "body" containing a string with the response body.

HttpRequest::getResponseHeader

(no version information, might be only in CVS)

HttpRequest::getResponseHeader -- Get response header(s)

Description

publicmixed HttpRequest::getResponseHeader ( [string name] )

Get response header(s) after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parameters

name

header to read; if empty, all response headers will be returned

Return Values

Returns either a string with the value of the header matching name if requested, FALSE on failure, or an associative array containing all response headers.

HttpRequest::getResponseInfo

(no version information, might be only in CVS)

HttpRequest::getResponseInfo -- Get response info

Description

publicmixed HttpRequest::getResponseInfo ( [string name] )

Get response info after the request has been sent.

See http_get() for a full list of returned info.

If redirects were allowed and several responses were received, the data references the last received response.

Parameters

name

the info to read; if empty or omitted, an associative array containing all available info will be returned

Return Values

Returns either a scalar containing the value of the info matching name if requested, FALSE on failure, or an associative array containing all available info.

HttpRequest::getResponseMessage

(no version information, might be only in CVS)

HttpRequest::getResponseMessage -- Get response message

Description

publicHttpMessage HttpRequest::getResponseMessage ( void )

Get the full response as HttpMessage object after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response. Use HttpMessage::getParentMessage() to access the data of previously received responses within this request cycle.

Return Values

Returns an HttpMessage object of the response.

Errors/Exceptions

Throws HttpException, HttpRuntimeException.

HttpRequest::getResponseStatus

(no version information, might be only in CVS)

HttpRequest::getResponseStatus -- Get response status

Description

publicstring HttpRequest::getResponseStatus ( void )

Get the response status (i.e. the string after the response code) after the message has been sent.

Return Values

Returns a string containing the response status text.

HttpRequest::getSslOptions

(no version information, might be only in CVS)

HttpRequest::getSslOptions -- Get ssl options

Description

publicarray HttpRequest::getSslOptions ( void )

Get previously set SSL options.

Return Values

Returns an associative array containing any previously set SSL options.

HttpRequest::getUrl

(no version information, might be only in CVS)

HttpRequest::getUrl -- Get url

Description

publicstring HttpRequest::getUrl ( void )

Get the previously set request URL.

Return Values

Returns the currently set request url as string.

HttpRequest::resetCookies

(no version information, might be only in CVS)

HttpRequest::resetCookies -- Reset cookies

Description

publicbool HttpRequest::resetCookies ( [bool session_only = FALSE] )

Reset all automatically received/sent cookies.

Note: Note that customly set cookies are not affected.

Parameters

session_only

whether only session cookies should be reset (needs libcurl >= v7.15.4, else libcurl >= v7.14.1)

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::send

(no version information, might be only in CVS)

HttpRequest::send -- Send request

Description

publicHttpMessage HttpRequest::send ( void )

Send the HTTP request.

Note: While an exception may be thrown, the transfer could have succeeded at least partially, so you might want to check the return values of various HttpRequest::getResponse*() methods.

Return Values

Returns the received response as HttpMessage object.

Errors/Exceptions

Throws HttpRuntimeException, HttpRequestException, HttpMalformedHeaderException, HttpEncodingException.

Examples

Example 1. GET example

<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
    $r->send();
    if ($r->getResponseCode() == 200) {
        file_put_contents('local.rss', $r->getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?>

Example 2. POST example

<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
    echo $r->send()->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
?>

HttpRequest::setContentType

(no version information, might be only in CVS)

HttpRequest::setContentType -- Set content type

Description

publicbool HttpRequest::setContentType ( string content_type )

Set the content type the post request should have.

Parameters

content_type

the content type of the request (primary/secondary)

Return Values

Returns TRUE on success, or FALSE if the content type does not seem to contain a primary and a secondary part.

HttpRequest::setCookies

(no version information, might be only in CVS)

HttpRequest::setCookies -- Set cookies

Description

publicbool HttpRequest::setCookies ( [array cookies] )

Set custom cookies.

Parameters

cookies

an associative array as parameter containing cookie name/value pairs; if empty or omitted, all previously set cookies will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setHeaders

(no version information, might be only in CVS)

HttpRequest::setHeaders -- Set headers

Description

publicbool HttpRequest::setHeaders ( [array headers] )

Set request header name/value pairs.

Parameters

headers

an associative array as parameter containing header name/value pairs; if empty or omitted, all previously set headers will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setMethod

(no version information, might be only in CVS)

HttpRequest::setMethod -- Set method

Description

publicbool HttpRequest::setMethod ( int request_method )

Set the request method.

Parameters

request_method

the request method to use

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setOptions

(no version information, might be only in CVS)

HttpRequest::setOptions -- Set options

Description

publicbool HttpRequest::setOptions ( [array options] )

Set the request options to use.

See the full list of request options.

Parameters

options

an associative array, which values will overwrite the currently set request options; if empty or omitted, the options of the HttpRequest object will be reset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setPostFields

(no version information, might be only in CVS)

HttpRequest::setPostFields -- Set post fields

Description

publicbool HttpRequest::setPostFields ( array post_data )

Set the POST data entries, overwriting previously set POST data.

Affects only POST and custom requests.

Parameters

post_data

an associative array containing the post fields; if empty, the post data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setPostFiles

(no version information, might be only in CVS)

HttpRequest::setPostFiles -- Set post files

Description

publicbool HttpRequest::setPostFiles ( array post_files )

Set files to post, overwriting previously set post files.

Affects only POST and requests. Cannot be used with raw post data.

Parameters

post_files

an array containing the files to post; if empty, the post files will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setPutData

(no version information, might be only in CVS)

HttpRequest::setPutData -- Set put data

Description

publicbool HttpRequest::setPutData ( [string put_data] )

Set PUT data to send, overwriting previously set PUT data.

Affects only PUT requests.

Only either PUT data or PUT file can be used for each request. PUT data has higher precedence and will be used even if a PUT file is set.

Parameters

put_data

the data to upload

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setPutFile

(no version information, might be only in CVS)

HttpRequest::setPutFile -- Set put file

Description

publicbool HttpRequest::setPutFile ( [string file] )

Set file to put. Affects only PUT requests.

Parameters

file

the path to the file to send; if empty or omitted the put file will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setQueryData

(no version information, might be only in CVS)

HttpRequest::setQueryData -- Set query data

Description

publicbool HttpRequest::setQueryData ( mixed query_data )

Set the URL query parameters to use, overwriting previously set query parameters.

Affects any request types.

Parameters

query_data

a string or associative array parameter containing the pre-encoded query string or to be encoded query fields; if empty, the query data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setRawPostData

(no version information, might be only in CVS)

HttpRequest::setRawPostData -- Set raw post data

Description

publicbool HttpRequest::setRawPostData ( [string raw_post_data] )

Set raw post data to send, overwriting previously set raw post data. Don't forget to specify a content type. Affects only POST and custom requests.

Only either post fields or raw post data can be used for each request. Raw post data has higher precedence and will be used even if post fields are set.

Parameters

raw_post_data

raw post data

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setSslOptions

(no version information, might be only in CVS)

HttpRequest::setSslOptions -- Set ssl options

Description

publicbool HttpRequest::setSslOptions ( [array options] )

Set SSL options.

Parameters

options

an associative array containing any SSL specific options; if empty or omitted, the SSL options will be reset

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequest::setUrl

(no version information, might be only in CVS)

HttpRequest::setUrl -- Set URL

Description

publicbool HttpRequest::setUrl ( string url )

Set the request URL.

Parameters

url

the request url

Return Values

Returns TRUE on success or FALSE on failure.

HttpRequestPool

(no version information, might be only in CVS)

HttpRequestPool -- HTTP Request Pool Class

Synopsis

class HttpRequest implements Iterator, Countable

HttpRequestPool::attach

(no version information, might be only in CVS)

HttpRequestPool::attach -- Attach HttpRequest

Description

publicbool HttpRequestPool::attach ( HttpRequest request )

Attach an HttpRequest object to this HttpRequestPool.

Warning

Set all options prior attaching!

Parameters

request

an HttpRequest object not already attached to any HttpRequestPool object

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws HttpInvalidParamException, HttpRequestException, HttpRequestPoolException, HttpEncodingException.

HttpRequestPool::__construct

(no version information, might be only in CVS)

HttpRequestPool::__construct -- HttpRequestPool constructor

Description

void HttpRequestPool::__construct ( [HttpRequest request] )

Instantiate a new HttpRequestPool object. An HttpRequestPool is able to send several HttpRequests in parallel.

Accepts virtually infinite optional parameters each referencing an HttpRequest object.

Parameters

request

HttpRequest object to attach

Errors/Exceptions

Throws HttpRequestPoolException (HttpRequestException, HttpInvalidParamException).

Examples

Example 1. A HttpRequestPool example

<?php
try {
    $pool = new HttpRequestPool(
        new HttpRequest('http://www.google.com/', HttpRequest::METH_HEAD),
        new HttpRequest('http://www.php.net/', HttpRequest::METH_HEAD)
    );
    $pool->send();
    foreach($pool as $request) {
        printf("%s is %s (%d)\n",
            $request->getUrl(),
            $request->getResponseCode() ? 'alive' : 'not alive',
            $request->getResponseCode()
        );
    }
} catch (HttpException $e) {
    echo $e;
}
?>

HttpRequestPool::__destruct

(no version information, might be only in CVS)

HttpRequestPool::__destruct -- HttpRequestPool destructor

Description

void HttpRequestPool::__destruct ( void )

Clean up HttpRequestPool object.

HttpRequestPool::detach

(no version information, might be only in CVS)

HttpRequestPool::detach -- Detach HttpRequest

Description

bool HttpRequestPool::detach ( HttpRequest request )

Detach an HttpRequest object from this HttpRequestPool.

Parameters

request

an HttpRequest object attached to this HttpRequestPool object

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws HttpInvalidParamException, HttpRequestPoolException.

HttpRequestPool::getAttachedRequests

(no version information, might be only in CVS)

HttpRequestPool::getAttachedRequests -- Get attached requests

Description

array HttpRequestPool::getAttachedRequests ( void )

Get attached HttpRequest objects.

Parameters

Return Values

Returns an array containing all currently attached HttpRequest objects.

HttpRequestPool::getFinishedRequests

(no version information, might be only in CVS)

HttpRequestPool::getFinishedRequests -- Get finished requests

Description

array HttpRequestPool::getFinishedRequests ( void )

Get attached HttpRequest objects that already have finished their work.

Parameters

Return Values

Returns an array containing all attached HttpRequest objects that already have finished their work.

HttpRequestPool::reset

(no version information, might be only in CVS)

HttpRequestPool::reset -- Reset request pool

Description

void HttpRequestPool::reset ( void )

Detach all attached HttpRequest objects.

HttpRequestPool::send

(no version information, might be only in CVS)

HttpRequestPool::send -- Send all requests

Description

bool HttpRequestPool::send ( void )

Send all attached HttpRequest objects in parallel.

Parameters

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws HttpRequestPoolException (HttpSocketException, HttpRequestException, HttpMalformedHeaderException).

HttpRequestPool::socketPerform

(no version information, might be only in CVS)

HttpRequestPool::socketPerform -- Perform socket actions

Description

protectedbool HttpRequestPool::socketPerform ( void )

Returns TRUE until each request has finished its transaction.

Return Values

Returns TRUE until each request has finished its transaction.

Examples

Example 1. A HttpRequestPool::socketPerform() example

<?php
class MyPool extends HttpRequestPool
{
    public function send()
    {
        while ($this->socketPerform()) {
            if (!$this->socketSelect()) {
                throw new HttpSocketExcpetion;
            }
        }
    }

    protected final function socketPerform()
    {
        $result = parent::socketPerform();
        foreach ($this->getFinishedRequests() as $r) {
            $this->detach($r);
            // handle response of finished request
        }
        return $result;
    }
}
?>

HttpRequestPool::socketSelect

(no version information, might be only in CVS)

HttpRequestPool::socketSelect -- Perform socket select

Description

protectedbool HttpRequestPool::socketSelect ( void )

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse

(no version information, might be only in CVS)

HttpResponse -- HTTP Response Class

Synopsis

static class HttpResponse

Class Members

Properties

Table 1. Static Properties

ModifiersTypeNameDescription
protectedbooleancachewhether caching the response should be attempted
protectedbooleangzipwhether the sent entity should be gzip'ed on the fly
protectedstringeTagthe generated or custom ETag
protectedintegerlastModifiedthe generated or custom timestamp of last modification
protectedstringcacheControlCache-Control setting
protectedstringcontentTypethe Content-Type of the sent entity
protectedstringcontentDispositionthe Content-Disposition of the sent entity
protectedintegerbufferSizethe chunk buffer size used for throttling
protecteddoublethrottleDelaythe seconds to delay when throttling

Predefined Constants

Table 2.

TypeNameDescription
integerREDIRECTguess applicable redirect method
integerREDIRECT_PERMpermanent redirect (301 Moved permanently)
integerREDIRECT_FOUNDstandard redirect (302 Found)
integerREDIRECT_POSTredirect applicable to POST requests (303 See other)
integerREDIRECT_PROXYproxy redirect (305 Use proxy)
integerREDIRECT_TEMPtemporary redirect (307 Temporary Redirect)

HttpResponse::capture

(no version information, might be only in CVS)

HttpResponse::capture -- Capture script output

Description

staticvoid HttpResponse::capture ( void )

Capture script output.

Examples

Example 1. A HttpResponse::capture() example

<?php
HttpResponse::setCache(true);
HttpResponse::capture();
// script follows
?>

HttpResponse::getBufferSize

(no version information, might be only in CVS)

HttpResponse::getBufferSize -- Get buffer size

Description

staticint HttpResponse::getBufferSize ( void )

Get current buffer size.

Return Values

Returns an int representing the current buffer size in bytes.

HttpResponse::getCacheControl

(no version information, might be only in CVS)

HttpResponse::getCacheControl -- Get cache control

Description

staticstring HttpResponse::getCacheControl ( void )

Get current Cache-Control header setting.

Return Values

Returns the current cache control setting as a string like sent in a header.

HttpResponse::getCache

(no version information, might be only in CVS)

HttpResponse::getCache -- Get cache

Description

staticbool HttpResponse::getCache ( void )

Get current caching setting.

Return Values

Returns TRUE if caching should be attempted, else FALSE.

HttpResponse::getContentDisposition

(no version information, might be only in CVS)

HttpResponse::getContentDisposition -- Get content disposition

Description

staticstring HttpResponse::getContentDisposition ( void )

Get current Content-Disposition setting.

Return Values

Returns the current content disposition as string like sent in a header.

HttpResponse::getContentType

(no version information, might be only in CVS)

HttpResponse::getContentType -- Get content type

Description

staticstring HttpResponse::getContentType ( void )

Get current Content-Type header setting.

Return Values

Returns the currently set content type as string.

HttpResponse::getData

(no version information, might be only in CVS)

HttpResponse::getData -- Get data

Description

staticstring HttpResponse::getData ( void )

Get the previously set data to be sent.

Return Values

Returns a string containing the previously set data to send.

HttpResponse::getETag

(no version information, might be only in CVS)

HttpResponse::getETag -- Get ETag

Description

staticstring HttpResponse::getETag ( void )

Get calculated or previously set custom ETag.

Return Values

Returns the calculated or previously set ETag as unquoted string.

HttpResponse::getFile

(no version information, might be only in CVS)

HttpResponse::getFile -- Get file

Description

staticstring HttpResponse::getFile ( void )

Get the previously set file to be sent.

Return Values

Returns the previously set path to the file to send as string.

HttpResponse::getGzip

(no version information, might be only in CVS)

HttpResponse::getGzip -- Get gzip

Description

staticbool HttpResponse::getGzip ( void )

Get current gzip'ing setting.

Return Values

Returns TRUE if GZip compression is enabled, else FALSE.

HttpResponse::getHeader

(no version information, might be only in CVS)

HttpResponse::getHeader -- Get header

Description

staticmixed HttpResponse::getHeader ( [string name] )

Get header(s) about to be sent.

Note: This may not work as expected with the following SAPI(s): Apache2 w/PHP < 5.1.3.

Parameters

name

specifies the name of the header to read; if empty or omitted, an associative array with all headers will be returned

Return Values

Returns either a string containing the value of the header matching name, FALSE on failure, or an associative array with all headers.

HttpResponse::getLastModified

(no version information, might be only in CVS)

HttpResponse::getLastModified -- Get last modified

Description

staticint HttpResponse::getLastModified ( void )

Get calculated or previously set custom Last-Modified date.

Return Values

Returns the calculated or previously set Unix timestamp.

HttpResponse::getStream

(no version information, might be only in CVS)

HttpResponse::getStream -- Get Stream

Description

staticresource HttpResponse::getStream ( void )

Get the previously set resource to be sent.

Parameters

Return Values

Returns the previously set resource.

HttpResponse::getThrottleDelay

(no version information, might be only in CVS)

HttpResponse::getThrottleDelay -- Get throttle delay

Description

staticdouble HttpResponse::getThrottleDelay ( void )

Get the current throttle delay.

Return Values

Returns a double representing the throttle delay in seconds.

HttpResponse::getRequestBody

(no version information, might be only in CVS)

HttpResponse::getRequestBody -- Get request body

Description

staticstring HttpResponse::getRequestBody ( void )

This function is an alias of: http_get_request_body().

HttpResponse::getRequestBodyStream

(no version information, might be only in CVS)

HttpResponse::getRequestBodyStream -- Get request body stream

Description

staticresource HttpResponse::getRequestBodyStream ( void )

This function is an alias of: http_get_request_body_stream().

HttpResponse::getRequestHeaders

(no version information, might be only in CVS)

HttpResponse::getRequestHeaders -- Get request headers

Description

staticarray HttpResponse::getRequestHeaders ( void )

This function is an alias of: http_get_request_headers().

HttpResponse::guessContentType

(no version information, might be only in CVS)

HttpResponse::guessContentType -- Guess content type

Description

staticstring HttpResponse::guessContentType ( string magic_file [, int magic_mode=MAGIC_MIME] )

Attempts to guess the content type of supplied payload through libmagic.

If the attempt is successful, the guessed Content-Type will automatically be set as response Content-Type.

Parameters

magic_file

specifies the magic.mime database to use

magic_mode

flags for libmagic

Return Values

Returns the guessed content type on success, or FALSE on failure.

Errors/Exceptions

Throws HttpRuntimeException, HttpInvalidParamException.

HttpResponse::redirect

(no version information, might be only in CVS)

HttpResponse::redirect -- Redirect

Description

staticvoid HttpResponse::redirect ( [string url [, array params [, bool session = FALSE [, int status]]]] )

This function is an alias of: http_redirect().

HttpResponse::send

(no version information, might be only in CVS)

HttpResponse::send -- Send response

Description

staticbool HttpResponse::send ( [bool clean_ob = TRUE] )

Finally send the entity.

A successful caching attempt will exit PHP, and write a log entry if the INI setting http.log.cache is set. See the INI setting http.force_exit for what "exits" means.

Parameters

clean_ob

whether to destroy all previously started output handlers and their buffers

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A HttpResponse::send() example

<?php
HttpResponse::setCache(true);
HttpResponse::setContentType('application/pdf');
HttpResponse::setContentDisposition("$user.pdf", false);
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>

HttpResponse::setBufferSize

(no version information, might be only in CVS)

HttpResponse::setBufferSize -- Set buffer size

Description

staticbool HttpResponse::setBufferSize ( int bytes )

Sets the send buffer size of the throttling mechanism.

Note: Provides a basic throttling mechanism, which will yield the current process respectively thread until the entity has been completely sent.

Note: This may not work as expected with the following SAPI(s): FastCGI.

Parameters

bytes

the chunk size in bytes

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setCacheControl

(no version information, might be only in CVS)

HttpResponse::setCacheControl -- Set cache control

Description

staticbool HttpResponse::setCacheControl ( string control [, int max_age = 0 [, bool must_revalidate = TRUE]] )

Define a custom Cache-Control header, usually being private or public;

Parameters

control

the primary cache control setting

max_age

the max-age in seconds, suggesting how long the cache entry is valid on the client side

must_revalidate

whether the cached entity should be revalidated by the client for every request

Return Values

Returns TRUE on success, or FALSE if control does not match one of public, private or no-cache.

HttpResponse::setCache

(no version information, might be only in CVS)

HttpResponse::setCache -- Set cache

Description

staticbool HttpResponse::setCache ( bool cache )

Whether it should be attempted to cache the entity.

This will result in necessary caching headers and checks of clients If-Modified-Since and If-None-Match headers. If one of those headers matches a 304 Not Modified status code will be issued.

Note: If you're using sessions, be sure that you set session.cache_limiter to something more appropriate than "no-cache"!

Parameters

cache

whether caching should be attempted

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setContentDisposition

(no version information, might be only in CVS)

HttpResponse::setContentDisposition -- Set content disposition

Description

staticbool HttpResponse::setContentDisposition ( string filename [, bool inline = FALSE] )

Set the Content-Disposition. The Content-Disposition header is very useful if the data actually sent came from a file or something similar, that should be "saved" by the client/user (i.e. by browsers "Save as..." popup window).

Parameters

filename

the file name the "Save as..." dialog should display

inline

if set to true and the user agent knows how to handle the content type, it will probably not cause the popup window to be shown

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setContentType

(no version information, might be only in CVS)

HttpResponse::setContentType -- Set content type

Description

staticbool HttpResponse::setContentType ( string content_type )

Set the Content-Type of the sent entity.

Parameters

content_type

the content type of the sent entity (primary/secondary)

Return Values

Returns TRUE on success, or FALSE if the content type does not seem to contain a primary and secondary content type part.

HttpResponse::setData

(no version information, might be only in CVS)

HttpResponse::setData -- Set data

Description

staticbool HttpResponse::setData ( mixed data )

Set the data to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

data

data to send

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setETag

(no version information, might be only in CVS)

HttpResponse::setETag -- Set ETag

Description

staticbool HttpResponse::setETag ( string etag )

Set a custom ETag. Use this only if you know what you're doing.

Parameters

etag

unquoted string as parameter containing the ETag

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setFile

(no version information, might be only in CVS)

HttpResponse::setFile -- Set file

Description

staticbool HttpResponse::setFile ( string file )

Set the file to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

file

the path to the file to send

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setGzip

(no version information, might be only in CVS)

HttpResponse::setGzip -- Set gzip

Description

staticbool HttpResponse::setGzip ( bool gzip )

Enable on-thy-fly gzip'ing of the sent entity.

Parameters

gzip

whether GZip compression should be enabled

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setHeader

(no version information, might be only in CVS)

HttpResponse::setHeader -- Set header

Description

staticbool HttpResponse::setHeader ( string name [, mixed value [, bool replace = TRUE]] )

Send an HTTP header.

Parameters

name

the name of the header

value

the value of the header; if not set, no header with this name will be sent

replace

whether an existing header should be replaced

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setLastModified

(no version information, might be only in CVS)

HttpResponse::setLastModified -- Set last modified

Description

staticbool HttpResponse::setLastModified ( int timestamp )

Set a custom Last-Modified date.

Parameters

timestamp

Unix timestamp representing the last modification time of the sent entity

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setStream

(no version information, might be only in CVS)

HttpResponse::setStream -- Set stream

Description

staticbool HttpResponse::setStream ( resource stream )

Set the resource to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

stream

already opened stream from which the data to send will be read

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::setThrottleDelay

(no version information, might be only in CVS)

HttpResponse::setThrottleDelay -- Set throttle delay

Description

staticbool HttpResponse::setThrottleDelay ( float seconds )

Sets the throttle delay.

Note: Provides a basic throttling mechanism, which will yield the current process respectively thread until the entity has been completely sent.

Note: This may not work as expected with the following SAPI(s): FastCGI.

Parameters

seconds

seconds to sleep after each chunk sent

Return Values

Returns TRUE on success or FALSE on failure.

HttpResponse::status

(no version information, might be only in CVS)

HttpResponse::status -- Send HTTP response status

Description

staticbool HttpResponse::status ( int status )

This function is an alias of: http_send_status().

http_cache_etag

(PECL)

http_cache_etag -- Caching by ETag

Description

bool http_cache_etag ( [string etag] )

Attempts to cache the sent entity by its ETag, either supplied or generated by the hash algorithm specified by the INI setting http.etag.mode.

If the clients If-None-Match header matches the supplied/calculated ETag, the body is considered cached on the clients side and a 304 Not Modified status code is issued.

A log entry is written to the cache log if the INI setting http.log.cache is set and the cache attempt was successful.

Note: This function may be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

If this function is used outside the http_send_*() API, it facilitates the ob_etaghandler().

Parameters

etag

custom ETag

Return Values

Returns FALSE or exits on success with 304 Not Modified if the entity is cached. See the INI setting http.force_exit for what "exits" means.

Examples

Example 1. A http_cache_etag() example

<?php
http_cache_etag();
http_send_data("data");
?>

See Also

http_cache_last_modified()
ob_etaghandler()
http_match_etag()
the HttpResponse class if you are using PHP-5.1 and above

http_cache_last_modified

(PECL)

http_cache_last_modified -- Caching by last modification

Description

bool http_cache_last_modified ( [int timestamp_or_expires] )

Attempts to cache the sent entity by its last modification date.

If the supplied argument is greater than 0, it is handled as timestamp and will be sent as date of last modification. If it is 0 or omitted, the current time will be sent as Last-Modified date. If it's negative, it is handled as expiration time in seconds, which means that if the requested last modification date is not between the calculated timespan, the Last-Modified header is updated and the actual body will be sent.

A log entry will be written to the cache log if the INI setting http.log.cache is set and the cache attempt was successful.

Note: This function may be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

timestamp_or_expires

Unix timestamp

Return Values

Returns FALSE or exits on success with 304 Not Modified if the entity is cached. See the INI setting http.force_exit for what "exits" means.

Examples

Example 1. A http_cache_last_modified() example

Caching for 5 seconds.

<?php
http_cache_last_modified(-5);
printf("%s\n", http_date());
?>

See Also

http_cache_etag()
the HttpResponse class if you are using PHP-5.1 and above

http_chunked_decode

(PECL)

http_chunked_decode -- Decode chunked-encoded data

Description

string http_chunked_decode ( string encoded )

Decodes a string which is HTTP-chunked encoded.

Parameters

encoded

chunked encoded string

Return Values

Returns the decoded string on success or FALSE on failure.

Examples

Example 1. A http_chunked_decode() example

<?php
$string = "".
    "05\r\n".
    "this \r\n".
    "07\r\n".
    "string \r\n".
    "12\r\n".
    "is chunked encoded\r\n".
    "01\n\r\n".
    "00";
echo http_chunked_decode($string);
?>

The above example will output:

this string is chunked encoded

http_deflate

(no version information, might be only in CVS)

http_deflate -- Deflate data

Description

string http_deflate ( string data [, int flags = 0] )

Compress data with gzip, zlib AKA deflate or raw deflate encoding.

See the deflate constants table for possible values for the flags parameter.

Parameters

data

String containing the data that should be encoded

flags

deflate options

Return Values

Returns the encoded string on success, or NULL on failure.

http_inflate

(no version information, might be only in CVS)

http_inflate -- Inflate data

Description

string http_inflate ( string data )

Decompress data compressed with either gzip, deflate AKA zlib or raw deflate encoding.

Parameters

data

string containing the compressed data

Return Values

Returns the decoded string on success, or NULL on failure.

http_get_request_body_stream

(no version information, might be only in CVS)

http_get_request_body_stream -- Get request body as stream

Description

resource http_get_request_body_stream ( void )

Create a stream to read the raw request body (e.g. POST or PUT data).

This function can only be used once if the request method was another than POST.

Parameters

Return Values

Returns the raw request body as stream on success or NULL on failure.

See Also

http_get_request_body()
http_get_request_headers()
the HttpResponse class if you are using PHP-5.1 and above

http_get_request_body

(PECL)

http_get_request_body -- Get request body as string

Description

string http_get_request_body ( void )

Get the raw request body (e.g. POST or PUT data).

This function can not be used after http_get_request_body_stream() if the request method was another than POST.

Parameters

Return Values

Returns the raw request body as string on success or NULL on failure.

See Also

http_get_request_body_stream()
http_get_request_headers()
the HttpResponse class if you are using PHP-5.1 and above

http_get_request_headers

(PECL)

http_get_request_headers -- Get request headers as array

Description

array http_get_request_headers ( void )

Get a list of incoming HTTP headers.

Parameters

Return Values

Returns an associative array of incoming request headers.

See Also

http_get_request_body()
http_get_request_body_stream()
the HttpResponse class if you are using PHP-5.1 and above

http_date

(PECL)

http_date -- Compose HTTP RFC compliant date

Description

string http_date ( [int timestamp] )

Compose a valid HTTP date regarding RFC 1123 looking like: Wed, 22 Dec 2004 11:34:47 GMT.

Parameters

timestamp

Unix timestamp; current time if omitted

Return Values

Returns the HTTP date as string.

See Also

date()

http_support

(no version information, might be only in CVS)

http_support -- Check built-in HTTP support

Description

int http_support ( [int feature = 0] )

Check for features that require external libraries.

See the feature support constants table for possible values for the feature argument.

Parameters

feature

feature to probe for

Return Values

Returns integer, whether requested feature is supported, or a bitmask with all supported features if feature was omitted.

Examples

Example 1. A http_support() example

<?php
if (!http_support(HTTP_SUPPORT_REQUESTS) {
    die("Need HTTP request support!\n");
}
?>

http_match_etag

(PECL)

http_match_etag -- Match ETag

Description

bool http_match_etag ( string etag [, bool for_range = FALSE] )

Matches the given ETag against the clients If-Match resp. If-None-Match HTTP headers.

Parameters

etag

the ETag to match

for_range

if set to TRUE, the header usually used to validate HTTP ranges will be checked

Return Values

Returns TRUE if ETag matches or the header contained the asterisk ("*"), else FALSE.

http_match_modified

(PECL)

http_match_modified -- Match last modification

Description

bool http_match_modified ( [int timestamp [, bool for_range = FALSE]] )

Matches the given Unix timestamp against the clients If-Modified-Since resp. If-Unmodified-Since HTTP headers.

Parameters

timestamp

Unix timestamp; current time, if omitted

for_range

if set to TRUE, the header usually used to validate HTTP ranges will be checked

Return Values

Returns TRUE if timestamp represents an earlier date than the header, else FALSE.

http_match_request_header

(PECL)

http_match_request_header -- Match any header

Description

bool http_match_request_header ( string header, string value [, bool match_case = FALSE] )

Match an incoming HTTP header.

Parameters

header

the header name (case-insensitive)

value

the header value that should be compared

match_case

whether the value should be compared case sensitively

Return Values

Returns TRUE if header value matches, else FALSE.

See Also

http_match_etag()
http_match_last_modified()

http_build_cookie

(no version information, might be only in CVS)

http_build_cookie -- Build cookie string

Description

string http_build_cookie ( array cookie )

Build a cookie string from an array/object like returned by http_parse_cookie().

Parameters

cookie

a cookie list like returned from http_parse_cookie()

Return Values

Returns the cookie(s) as string.

http_negotiate_charset

(PECL)

http_negotiate_charset -- Negotiate clients preferred character set

Description

string http_negotiate_charset ( array supported [, array &result] )

This function negotiates the clients preferred charset based on its Accept-Charset HTTP header. The qualifier is recognized and charsets without qualifier are rated highest.

Parameters

supported

array containing the supported charsets as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated charset or the default charset (i.e. first array entry) if none match.

Examples

Example 1. Using http_negotiate_charset()

<?php
$charsets = array(
		'iso-8859-1', // default
		'iso-8859-2',
		'iso-8859-15',
		'utf-8'
);

$pref = http_negotiate_charset($charsets, $result);

if (strcmp($pref, 'iso-8859-1')) {
		iconv_set_encoding('internal_encoding', 'iso-8859-1');
		iconv_set_encoding('output_encoding', $pref);
		ob_start('ob_iconv_handler');
}

print_r($result);
?>

http_negotiate_content_type

(no version information, might be only in CVS)

http_negotiate_content_type -- Negotiate clients preferred content type

Description

string http_negotiate_content_type ( array supported [, array &result] )

This function negotiates the clients preferred content type based on its Accept HTTP header. The qualifier is recognized and content types without qualifier are rated highest.

Parameters

supported

array containing the supported content types as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated content type or the default content type (i.e. first array entry) if none match.

Examples

Example 1. Using http_negotiate_content_type()

<?php
$content_types = array('application/xhtml+xml', 'text/html');
http_send_content_type(http_negotiate_content_type($content_types));
?>

http_negotiate_language

(PECL)

http_negotiate_language -- Negotiate clients preferred language

Description

string http_negotiate_language ( array supported [, array &result] )

This function negotiates the clients preferred language based on its Accept-Language HTTP header. The qualifier is recognized and languages without qualifier are rated highest. The qualifier will be decreased by 10% for partial matches (i.e. matching primary language).

Parameters

supported

array containing the supported languages as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated language or the default language (i.e. first array entry) if none match.

Examples

Example 1. Using http_negotiate_language()

<?php
$langs = array(
		'en-US',// default
		'fr',
		'fr-FR',
		'de',
		'de-DE',
		'de-AT',
		'de-CH',
);

include './langs/'. http_negotiate_language($langs, $result) .'.php';

print_r($result);
?>

ob_deflatehandler

(no version information, might be only in CVS)

ob_deflatehandler -- Deflate output handler

Description

string ob_deflatehandler ( string data, int mode )

For use with ob_start().

Note: This output handler can only be used once.

The deflate output buffer handler can only be used once.

It conflicts with ob_gzhandler() and zlib.output_compression as well and should not be used after mbstring extension's mb_output_handler() and session extension's URL-Rewriter (AKA session.use_trans_sid).

ob_etaghandler

(PECL)

ob_etaghandler -- ETag output handler

Description

string ob_etaghandler ( string data, int mode )

For use with ob_start().

Output buffer handler generating an ETag with the hash algorithm specified with the INI setting http.etag.mode.

This output handler is used by http_cache_etag().

ob_inflatehandler

(no version information, might be only in CVS)

ob_inflatehandler -- Inflate output handler

Description

string ob_inflatehandler ( string data, int mode )

For use with ob_start().

Same restrictions as with ob_deflatehandler() apply.

http_parse_cookie

(no version information, might be only in CVS)

http_parse_cookie -- Parse HTTP cookie

Description

object http_parse_cookie ( string cookie [, int flags [, array allowed_extras]] )

Parses HTTP cookies like sent in a response into a struct.

Parameters

cookie

string containing the value of a Set-Cookie response header

flags

parse flags (HTTP_COOKIE_PARSE_RAW)

allowed_extras

array containing recognized extra keys; by default all unknown keys will be treated as cookie names

Return Values

Returns a stdClass object on success or FALSE on failure.

Examples

Example 1. Using http_parse_cookie()

<?php
print_r(http_parse_cookie("foo=bar; bar=baz; path=/; domain=example.com; comment=; secure", 0, array("comment")));
?>

The above example will output:

stdClass Object
(
  [cookies] => Array
  (
    [foo] => bar
    [bar] => baz
  )

  [extras] => Array
  (
    [comment] =>
  )

  [flags] => 16
  [expires] => 0
  [path] => /
  [domain] => example.com
)

http_parse_headers

(PECL)

http_parse_headers -- Parse HTTP headers

Description

array http_parse_headers ( string header )

Parses HTTP headers into an associative array.

Parameters

header

string containing HTTP headers

Return Values

Returns an array on success, or FALSE on failure.

Examples

Example 1. Using http_parse_headers()

<?php
$headers = "content-type: text/html; charset=UTF-8\r\n".
  "Server: Funky/1.0\r\n".
  "Set-Cookie: foo=bar\r\n".
  "Set-Cookie: baz=quux\r\n".
  "Folded: works\r\n\ttoo\r\n";
print_r(http_parse_headers($headers));
?>

The above example will output:

Array
(
  [Content-Type] => text/html; chatset=UTF-8
  [Server] => Funky/1.0
  [Set-Cookie] => Array
  (
    [0] => foo=bar
    [1] => baz=quux
  )
  [Folded] => works
    too
)

http_parse_message

(PECL)

http_parse_message -- Parse HTTP messages

Description

object http_parse_message ( string message )

Parses the HTTP message into a simple recursive object.

Parameters

message

string containing a single HTTP message or several consecutive HTTP messages

Return Values

Returns a hierarchical object structure of the parsed messages.

Examples

Example 1. Using http_parse_message()

<?php
define ('URL', 'http://www.example.com/');
print_r(http_parse_message(http_get(URL, array('redirect' => 3))));
?>

The above example will output something similar to:

stdClass object
(
  [type] => 2
  [httpVersion] => 1.1
  [responseCode] => 200
  [headers] => Array 
  (
    [Content-Length] => 3
    [Server] => Apache
  )
  [body] => Hi!
  [parentMessage] => stdClass object
  (
    [type] => 2
    [httpVersion] => 1.1
    [responseCode] => 302
    [headers] => Array 
    (
      [Content-Length] => 0
      [Location] => ...
    )
    [body] => 
    [parentMessage] => ...
  )
)

http_parse_params

(no version information, might be only in CVS)

http_parse_params -- Parse parameter list

Description

object http_parse_params ( string param [, int flags = HTTP_PARAMS_DEFAULT] )

Parse parameter list.

See the params parsing constants table for possible values of the flags argument.

Parameters

param

Parameters

flags

Parse flags

Return Values

Returns parameter list as stdClass object.

Examples

Example 1. A http_parse_params() example

<?php
var_dump(http_parse_params("text/html; charset=\"utf8\""));
?>

The above example will output:

object(stdClass)#1 (1) {
  ["params"]=>
  array(2) {
    [0]=>
    string(9) "text/html"
    [1]=>
    array(1) {
      ["charset"]=>
      string(4) "utf8"
    }
  }
}

http_persistent_handles_count

(no version information, might be only in CVS)

http_persistent_handles_count -- Stat persistent handles

Description

object http_persistent_handles_count ( void )

List statistics about persistent handles usage.

Parameters

Return Values

Returns persistent handles statistics as stdClass object on success or FALSE on failure.

Examples

Example 1. A http_persistent_handles_count() example

<?php
print_r(http_persistent_handles_count());
?>

The above example will output:

stdClass Object
(
    [http_request] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 0
                    [free] => 1
                )

        )

    [http_request_datashare] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 1
                    [free] => 0
                )

        )

    [http_request_pool] => Array
        (
        )

)

http_persistent_handles_ident

(no version information, might be only in CVS)

http_persistent_handles_ident -- Get/set ident of persistent handles

Description

string http_persistent_handles_ident ( string ident )

Query or define the ident of persistent handles.

Parameters

ident

the identification string

Return Values

Returns the prior ident as string on success or FALSE on failure.

Examples

Example 1. A http_persistent_handles_ident() example

<?php
echo http_persistent_handles_ident("CUSTOM"), "\n";
echo http_persistent_handles_ident("MyApp1"), "\n";
http_get("http://www.example.com/");
print_r(http_persistent_handles_count());
?>

The above example will output:

GLOBAL
CUSTOM
stdClass Object
(
    [http_request] => Array
        (
            [MyApp1] => Array
                (
                    [used] => 0
                    [free] => 1
                )

        )

    [http_request_datashare] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 1
                    [free] => 0
                )

        )

    [http_request_pool] => Array
        (
        )

)

http_persistent_handles_clean

(no version information, might be only in CVS)

http_persistent_handles_clean -- Clean up persistent handles

Description

string http_persistent_handles_clean ( [string ident] )

Clean up (close) persistent handles, optionally identified with ident.

Parameters

clean

the identification string

Return Values

No value is returned.

http_get

(PECL)

http_get -- Perform GET request

Description

string http_get ( string url [, array options [, array &info]] )

Performs an HTTP GET request on the supplied url.

See the full list of request options.

Parameters

url

URL

options

request options

info

Will be filled with request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Examples

Example 1. A http_get() example

<?php
$response = http_get("http://www.example.com/", array("timeout"=>1), $info);
print_r($info);
?>

The above example will output:

array (
  'effective_url' => 'http://www.example.com/',
  'response_code' => 302,
  'connect_code' => 0,
  'filetime' => -1,
  'total_time' => 0.212348,
  'namelookup_time' => 0.038296,
  'connect_time' => 0.104144,
  'pretransfer_time' => 0.104307,
  'starttransfer_time' => 0.212077,
  'redirect_time' => 0,
  'redirect_count' => 0,
  'size_upload' => 0,
  'size_download' => 218,
  'speed_download' => 1026,
  'speed_upload' => 0,
  'header_size' => 307,
  'request_size' => 103,
  'ssl_verifyresult' => 0,
  'ssl_engines' =>
  array (
    0 => 'dynamic',
    1 => 'cswift',
    2 => 'chil',
    3 => 'atalla',
    4 => 'nuron',
    5 => 'ubsec',
    6 => 'aep',
    7 => 'sureware',
    8 => '4758cca',
  ),
  'content_length_download' => 218,
  'content_length_upload' => 0,
  'content_type' => 'text/html',
  'httpauth_avail' => 0,
  'proxyauth_avail' => 0,
  'num_connects' => 1,
  'os_errno' => 0,
  'error' => '',
)

http_head

(PECL)

http_head -- Perform HEAD request

Description

string http_head ( [string url [, array options [, array &info]]] )

Performs an HTTP HEAD request on the supplied url.

See the full list of request options.

Parameters

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_post_data

(PECL)

http_post_data -- Perform POST request with pre-encoded data

Description

string http_post_data ( string url [, string data [, array options [, array &info]]] )

Performs an HTTP POST request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

String containing the pre-encoded post data

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_post_fields

(PECL)

http_post_fields -- Perform POST request with data to be encoded

Description

string http_post_fields ( string url [, array data [, array files [, array options [, array &info]]]] )

Performs an HTTP POST request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

Associative array of POST values

files

Array of files to post

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Examples

Example 1. A http_post_fields() example

<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

http_put_data

(no version information, might be only in CVS)

http_put_data -- Perform PUT request with data

Description

string http_put_data ( string url [, string data [, array options [, array &info]]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

PUT request body

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_put_file

(PECL)

http_put_file -- Perform PUT request with file

Description

string http_put_file ( string url [, string file [, array options [, array &info]]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

file

The file to put

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_put_stream

(PECL)

http_put_stream -- Perform PUT request with stream

Description

string http_put_stream ( string url [, resource stream [, array options [, array &info]]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

stream

The stream to read the PUT request body from

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_request_method_exists

(PECL)

http_request_method_exists -- Check whether request method exists

Description

int http_request_method_exists ( mixed method )

Check if a request method is registered (or available by default).

Parameters

method

request method name or ID

Return Values

Returns TRUE if the request method is known, else FALSE.

http_request_method_name

(PECL)

http_request_method_name -- Get request method name

Description

string http_request_method_name ( int method )

Get the literal string representation of a standard or registered request method.

Parameters

method

request method ID

Return Values

Returns the request method name as string on success, or FALSE on failure.

http_request_method_register

(PECL)

http_request_method_register -- Register request method

Description

int http_request_method_register ( string method )

Register a custom request method.

Parameters

method

the request method name to register

Return Values

Returns the ID of the request method on success, or FALSE on failure.

http_request_method_unregister

(PECL)

http_request_method_unregister -- Unregister request method

Description

bool http_request_method_unregister ( mixed method )

Unregister a previously registered custom request method.

Parameters

method

The request method name or ID

Return Values

Returns TRUE on success or FALSE on failure.

http_request

(no version information, might be only in CVS)

http_request -- Perform custom request

Description

string http_request ( int method [, string url [, string body [, array options [, array &info]]]] )

Performs a custom HTTP request on the supplied url.

See the full list of request options.

Parameters

method

Request method

url

URL

body

Request body

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

http_request_body_encode

(no version information, might be only in CVS)

http_request_body_encode -- Encode request body

Description

string http_request_body_encode ( array fields, array files )

Generate x-www-form-urlencoded resp. form-data encoded request body.

Parameters

fields

POST fields

files

POST files

Return Values

Returns encoded string on success, or FALSE on failure

http_redirect

(PECL)

http_redirect -- Issue HTTP redirect

Description

void http_redirect ( [string url [, array params [, bool session = FALSE [, int status]]]] )

Redirect to the given url.

The supplied url will be expanded with http_build_url(), the params array will be treated with http_build_str() and the session identification will be appended if session is true. The HTTP response code will be set according to status. You can use one of the redirect constants for convenience. Please see RFC 2616 for which redirect response code to use in which situation. By default PHP will decide which response status fits best.

To be RFC compliant, "Redirecting to <a>URL</a>." will be displayed, if the client doesn't redirect immediately, and the request method was another one than HEAD.

A log entry will be written to the redirect log, if the INI setting http.log.redirect is set and the redirect attempt was successful.

Parameters

url

the URL to redirect to

params

associative array of query parameters

session

whether to append session information

status

custom response status code

Return Values

Returns FALSE or exits on success with the specified redirection status code. See the INI setting http.force_exit for what "exits" means.

Examples

Example 1. A http_redirect() example

<?php
http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);
?>

The above example will output:

HTTP/1.1 301 Moved Permanently
X-Powered-By: PHP/5.2.2
Content-Type: text/html
Location: http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc

Redirecting to <a href="http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc">http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc</a>.

See Also

the HttpResponse class if you are using PHP-5.1 and above

http_send_content_disposition

(PECL)

http_send_content_disposition -- Send Content-Disposition

Description

bool http_send_content_disposition ( string filename [, bool inline = FALSE] )

Send the Content-Disposition. The Content-Disposition header is very useful if the data actually sent came from a file or something similar, that should be "saved" by the client/user (i.e. by browsers "Save as..." popup window).

Note: This function is supposed to be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

filename

the file name the "Save as..." dialog should display

inline

if set to TRUE and the user agent knows how to handle the content type, it will probably not cause the popup window to be shown

Return Values

Returns TRUE on success or FALSE on failure.

See Also

http_send_data()
http_send_file()
http_send_stream()
the HttpResponse class if you are using PHP-5.1 and above

http_send_content_type

(PECL)

http_send_content_type -- Send Content-Type

Description

bool http_send_content_type ( [string content_type = 'application/x-octetstream'] )

Send the Content-Type of the sent entity.

Note: This function is supposed to be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

content_type

the desired content type (primary/secondary)

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Raises an E_WARNING when the content_type doesn't seem to contain a primary and a secondary part.

See Also

http_send_data()
http_send_file()
http_send_stream()
the HttpResponse class if you are using PHP-5.1 and above

http_send_data

(PECL)

http_send_data -- Send arbitrary data

Description

bool http_send_data ( string data )

Sends raw data with support for (multiple) range requests.

Parameters

data

data to send

Return Values

Returns TRUE on success or FALSE on failure.

http_send_file

(PECL)

http_send_file -- Send file

Description

bool http_send_file ( string file )

Sends a file with support for (multiple) range requests.

This functions behaviour and further action is dependent on the following INI settings: http.send.not_found_404 and http.log.not_found.

If the INI setting http.send.not_found_404 is enabled and the INI setting http.log.not_found points to a writable file, a log message is written when the file was not found.

Parameters

file

the file to send

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A http_send_file() example

<?php
http_send_content_disposition("document.pdf", true);
http_send_content_type("application/pdf");
http_throttle(0.1, 2048);
http_send_file("../report.pdf");
?>

The above example will output:

HTTP/1.1 206 Partial Content
X-Powered-By: PHP/5.2.2
Accept-Ranges: bytes
Content-Length: 12345
Content-Range: bytes 0-12344
Content-Type: application/pdf
Content-Disposition: inline; filename="document.pdf"

%PDF...

http_send_last_modified

(PECL)

http_send_last_modified -- Send Last-Modified

Description

bool http_send_last_modified ( [int timestamp] )

Send a Last-Modified header with a valid HTTP date.

Note: This function is supposed to be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

timestamp

a Unix timestamp, converted to a valid HTTP date; if omitted, the current time will be sent

Return Values

Returns TRUE on success or FALSE on failure.

See Also

the HttpResponse class if you are using PHP-5.1 and above

http_send_status

(PECL)

http_send_status -- Send HTTP response status

Description

bool http_send_status ( int status )

Send HTTP status code.

Parameters

status

HTTP status code (100-599)

Return Values

Returns TRUE on success or FALSE on failure.

See Also

the HttpResponse class if you are using PHP-5.1 and above

http_send_stream

(PECL)

http_send_stream -- Send stream

Description

bool http_send_stream ( resource stream )

Sends an already opened stream with support for (multiple) range requests.

Parameters

stream

stream to read from (must be seekable)

Return Values

Returns TRUE on success or FALSE on failure.

http_throttle

(PECL)

http_throttle -- HTTP throttling

Description

void http_throttle ( [float sec [, int bytes = 40960]] )

Sets the throttle delay and send buffer size.

Note: This function is supposed to be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Note: Provides a basic throttling mechanism, which will yield the current process respectively thread until the entity has been completely sent.

Note: This may not work as expected with the following SAPI(s): FastCGI.

Parameters

sec

seconds to sleep after each chunk sent

bytes

the chunk size in bytes

Examples

Example 1. A http_throttle() example

Send file with approximately 20 kbyte/s.

<?php
// ~ 20 kbyte/s
# http_throttle(1, 20000);
# http_throttle(0.5, 10000);
http_throttle(0.1, 2000);
http_send_file('document.pdf');
?>
?>

See Also

http_send_data()
http_send_file()
http_send_stream()
the HttpResponse class if you are using PHP-5.1 and above

http_build_str

(no version information, might be only in CVS)

http_build_str -- Build query string

Description

string http_build_str ( array query [, string prefix [, string arg_separator]] )

Opponent to parse_str().

Parameters

query

associative array of query string parameters

prefix

top level prefix

arg_separator

argument separator to use (by default the INI setting arg_separator.output will be used, or "&" if neither is set

Return Values

Returns the built query as string on success or FALSE on failure.

http_build_url

(no version information, might be only in CVS)

http_build_url -- Build an URL

Description

string http_build_url ( [mixed url [, mixed parts [, int flags = HTTP_URL_REPLACE [, array &new_url]]]] )

Build an URL.

The parts of the second URL will be merged into the first according to the flags argument.

Parameters

url

(part(s) of) an URL in form of a string or associative array like parse_url() returns

parts

same as the first argument

flags

a bitmask of binary or'ed HTTP_URL constants; HTTP_URL_REPLACE is the default

new_url

if set, it will be filled with the parts of the composed url like parse_url() would return

Return Values

Returns the new URL as string on success or FALSE on failure.

Examples

Example 1. A http_build_url() example

<?php
echo http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
	array(
		"scheme" => "ftp",
		"host" => "ftp.example.com",
		"path" => "files/current/",
		"query" => "a=c"
	),
	HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);
?>

The above example will output:

ftp://ftp.example.com/pub/files/current/?a=b&a=c

LVI. Hyperwave Functions

Introduction

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: A unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Requirements

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.


Installation

This PECL extension is not bundled with PHP.

In order to use these functions you must compile PHP with Hyperwave support by using the --with-hyperwave[=DIR] configure option.

Windows users will enable php_hyperwave.dll inside of php.ini in order to use these functions. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Hyperwave configuration options

NameDefaultChangeableChangelog
hyperwave.allow_persistent"0"PHP_INI_SYSTEMAvailable since PHP 4.3.2.
hyperwave.default_port"418"PHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.


Resource Types

This extension has no resource types defined.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

HW_ATTR_LANG (integer)

HW_ATTR_NR (integer)

HW_ATTR_NONE (integer)


Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

Table of Contents
hw_Array2Objrec -- Convert attributes from object array to object record
hw_changeobject --  Changes attributes of an object (obsolete)
hw_Children -- Object ids of children
hw_ChildrenObj -- Object records of children
hw_Close -- Closes the Hyperwave connection
hw_Connect -- Opens a connection
hw_connection_info --  Prints information about the connection to Hyperwave server
hw_cp -- Copies objects
hw_Deleteobject -- Deletes object
hw_DocByAnchor -- Object id object belonging to anchor
hw_DocByAnchorObj -- Object record object belonging to anchor
hw_Document_Attributes -- Object record of hw_document
hw_Document_BodyTag -- Body tag of hw_document
hw_Document_Content -- Returns content of hw_document
hw_Document_SetContent -- Sets/replaces content of hw_document
hw_Document_Size -- Size of hw_document
hw_dummy --  Hyperwave dummy function
hw_EditText -- Retrieve text document
hw_Error -- Error number
hw_ErrorMsg -- Returns error message
hw_Free_Document -- Frees hw_document
hw_GetAnchors -- Object ids of anchors of document
hw_GetAnchorsObj -- Object records of anchors of document
hw_GetAndLock -- Return object record and lock object
hw_GetChildColl -- Object ids of child collections
hw_GetChildCollObj -- Object records of child collections
hw_GetChildDocColl -- Object ids of child documents of collection
hw_GetChildDocCollObj -- Object records of child documents of collection
hw_GetObject -- Object record
hw_GetObjectByQuery -- Search object
hw_GetObjectByQueryColl -- Search object in collection
hw_GetObjectByQueryCollObj -- Search object in collection
hw_GetObjectByQueryObj -- Search object
hw_GetParents -- Object ids of parents
hw_GetParentsObj -- Object records of parents
hw_getrellink --  Get link from source to dest relative to rootid
hw_GetRemote -- Gets a remote document
hw_getremotechildren -- Gets children of remote document
hw_GetSrcByDestObj -- Returns anchors pointing at object
hw_GetText -- Retrieve text document
hw_getusername -- Name of currently logged in user
hw_Identify -- Identifies as user
hw_InCollections -- Check if object ids in collections
hw_Info -- Info about connection
hw_InsColl -- Insert collection
hw_InsDoc -- Insert document
hw_insertanchors --  Inserts only anchors into text
hw_InsertDocument -- Upload any document
hw_InsertObject -- Inserts an object record
hw_mapid -- Maps global id on virtual local id
hw_Modifyobject -- Modifies object record
hw_mv -- Moves objects
hw_New_Document -- Create new document
hw_objrec2array -- Convert attributes from object record to object array
hw_Output_Document -- Prints hw_document
hw_pConnect -- Make a persistent database connection
hw_PipeDocument -- Retrieve any document
hw_Root -- Root object id
hw_setlinkroot --  Set the id to which links are calculated
hw_stat --  Returns status string
hw_Unlock -- Unlock object
hw_Who -- List of currently logged in users

hw_Array2Objrec

(PHP 3 >= 3.0.4, PHP 4, PECL)

hw_Array2Objrec -- Convert attributes from object array to object record

Description

string hw_array2objrec ( array object_array )

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

hw_changeobject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_changeobject --  Changes attributes of an object (obsolete)

Description

bool hw_changeobject ( int link, int objid, array attributes )

Warning

This function is currently not documented; only the argument list is available.

hw_Children

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Children -- Object ids of children

Description

array hw_children ( int connection, int objectID )

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_ChildrenObj -- Object records of children

Description

array hw_childrenobj ( int connection, int objectID )

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Close -- Closes the Hyperwave connection

Description

bool hw_close ( int connection )

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Connect -- Opens a connection

Description

int hw_connect ( string host, int port [, string username, string password] )

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_connection_info

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link )

Warning

This function is currently not documented; only the argument list is available.

hw_cp

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_cp -- Copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination_id )

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Deleteobject -- Deletes object

Description

bool hw_deleteobject ( int connection, int object_to_delete )

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_DocByAnchor -- Object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID )

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_DocByAnchorObj -- Object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID )

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Attributes -- Object record of hw_document

Description

string hw_document_attributes ( int hw_document )

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_BodyTag -- Body tag of hw_document

Description

string hw_document_bodytag ( int hw_document [, string prefix] )

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Content -- Returns content of hw_document

Description

string hw_document_content ( int hw_document )

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4, PECL)

hw_Document_SetContent -- Sets/replaces content of hw_document

Description

bool hw_document_setcontent ( int hw_document, string content )

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Size -- Size of hw_document

Description

int hw_document_size ( int hw_document )

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_dummy

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid )

Warning

This function is currently not documented; only the argument list is available.

hw_EditText

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_EditText -- Retrieve text document

Description

bool hw_edittext ( int connection, int hw_document )

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().

hw_Error

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Error -- Error number

Description

int hw_error ( int connection )

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_ErrorMsg

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_ErrorMsg -- Returns error message

Description

string hw_errormsg ( int connection )

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_Free_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Free_Document -- Frees hw_document

Description

bool hw_free_document ( int hw_document )

Frees the memory occupied by the Hyperwave document.

hw_GetAnchors

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAnchors -- Object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID )

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAnchorsObj -- Object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID )

Returns an array of object records with anchors of the document with object ID objectID.

hw_GetAndLock

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAndLock -- Return object record and lock object

Description

string hw_getandlock ( int connection, int objectID )

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

hw_GetChildColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildColl -- Object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID )

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildCollObj -- Object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID )

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetChildDocColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildDocColl -- Object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID )

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildDocCollObj -- Object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID )

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetObject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObject -- Object record

Description

mixed hw_getobject ( int connection, mixed objectID [, string query] )

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

hw_GetObjectByQuery

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQuery -- Search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits )

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryColl -- Search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits )

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryCollObj -- Search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits )

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetObjectByQueryObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryObj -- Search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits )

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetParents

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetParents -- Object ids of parents

Description

array hw_getparents ( int connection, int objectID )

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetParentsObj -- Object records of parents

Description

array hw_getparentsobj ( int connection, int objectID )

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_getrellink

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid )

Warning

This function is currently not documented; only the argument list is available.

hw_GetRemote

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID )

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremotechildren().

hw_getremotechildren

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getremotechildren -- Gets children of remote document

Description

mixed hw_getremotechildren ( int connection, string object_record )

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formatted by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactly such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremote().

hw_GetSrcByDestObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID )

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetText

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetText -- Retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix] )

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().

hw_getusername

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getusername -- Name of currently logged in user

Description

string hw_getusername ( int connection )

Returns the username of the connection.

hw_Identify

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Identify -- Identifies as user

Description

string hw_identify ( int link, string username, string password )

Identifies as user with username and password. Identification is only valid for the current session. I do not think this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

hw_InCollections

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InCollections -- Check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections )

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Info -- Info about connection

Description

string hw_info ( int connection )

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsColl -- Insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array )

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsDoc -- Insert document

Description

int hw_insdoc ( resource connection, int parentID, string object_record [, string text] )

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_insertanchors

(PHP 4 >= 4.0.4, PECL)

hw_insertanchors --  Inserts only anchors into text

Description

bool hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes] )

Warning

This function is currently not documented; only the argument list is available.

hw_InsertDocument

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsertDocument -- Upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document )

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsertObject -- Inserts an object record

Description

int hw_insertobject ( int connection, string object_rec, string parameter )

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.

See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().

hw_mapid

(PHP 3 >= 3.0.13, PHP 4, PECL)

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server_id, int object_id )

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3 >= 3.0.7, PHP 4, PECL)

hw_Modifyobject -- Modifies object record

Description

bool hw_modifyobject ( int connection, int object_to_change, array remove, array add [, int mode] )

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Example 1. modifying an attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Example 2. adding a completely new attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Note: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Example 3. modifying Title attribute

<?php
       $remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
or

Example 4. modifying Title attribute

<?php
       $remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Example 5. removing attribute

<?php
       $remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Note: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Note: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Note: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Note: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Note: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Returns TRUE on success or FALSE on failure.

hw_mv

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_mv -- Moves objects

Description

int hw_mv ( int connection, array object_id_array, int source_id, int destination_id )

Moves the objects with object ids as specified in the second parameter from the collection with id source_id to the collection with the id destination_id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value returned is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

hw_New_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_New_Document -- Create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size )

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_objrec2array

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_objrec2array -- Convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format] )

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

See also hw_array2objrec().

hw_Output_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Output_Document -- Prints hw_document

Description

bool hw_output_document ( int hw_document )

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_pConnect -- Make a persistent database connection

Description

int hw_pconnect ( string host, int port [, string username, string password] )

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_PipeDocument -- Retrieve any document

Description

int hw_pipedocument ( int connection, int objectID [, array url_prefixes] )

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transferred via a special data connection which does not block the control connection.

See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().

hw_Root

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Root -- Root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_setlinkroot

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_setlinkroot --  Set the id to which links are calculated

Description

int hw_setlinkroot ( int link, int rootid )

Warning

This function is currently not documented; only the argument list is available.

hw_stat

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_stat --  Returns status string

Description

string hw_stat ( int link )

Warning

This function is currently not documented; only the argument list is available.

hw_Unlock

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Unlock -- Unlock object

Description

bool hw_unlock ( int connection, int objectID )

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Who -- List of currently logged in users

Description

array hw_who ( int connection )

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

LVII. Hyperwave API Functions

Introduction

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.2.0.


Requirements

Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.


Installation

After installing the Hyperwave SDK, configure PHP with --with-hwapi[=DIR].


Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Hyperwave API configuration options

NameDefaultChangeableChangelog
hwapi.allow_persistent"0"PHP_INI_SYSTEM 
For further details and definitions of the PHP_INI_* constants, see the Appendix I.


Resource Types

This extension has no resource types defined.


Predefined Constants

This extension has no constants defined.


Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API

  • HW_API_Object

  • HW_API_Attribute

  • HW_API_Error

  • HW_API_Content

  • HW_API_Reason

Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing several parameters they are all put into an associated array and passed as one parameter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.

  • objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".

  • parentIdentifier The name or id of an object which is considered to be a parent.

  • object An instance of class HW_API_Object.

  • parameters An instance of class HW_API_Object.

  • version The version of an object.

  • mode An integer value determine the way an operation is executed.

  • attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.

  • objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api->children() or hw_api->find().

Note: Methods returning boolean can return TRUE, FALSE or HW_API_Error object.

Table of Contents
hw_api_attribute->key -- Returns key of the attribute
hw_api_attribute->langdepvalue -- Returns value for a given language
hw_api_attribute->value -- Returns value of the attribute
hw_api_attribute->values -- Returns all values of the attribute
hw_api_attribute -- Creates instance of class hw_api_attribute
hw_api->checkin -- Checks in an object
hw_api->checkout -- Checks out an object
hw_api->children -- Returns children of an object
hw_api_content->mimetype -- Returns mimetype
hw_api_content->read -- Read content
hw_api->content -- Returns content of an object
hw_api->copy -- Copies physically
hw_api->dbstat -- Returns statistics about database server
hw_api->dcstat -- Returns statistics about document cache server
hw_api->dstanchors -- Returns a list of all destination anchors
hw_api->dstofsrcanchor -- Returns destination of a source anchor
hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
hw_api->hwstat -- Returns statistics about Hyperwave server
hw_api->identify -- Log into Hyperwave Server
hw_api->info -- Returns information about server configuration
hw_api->insert -- Inserts a new object
hw_api->insertanchor -- Inserts a new object of type anchor
hw_api->insertcollection -- Inserts a new object of type collection
hw_api->insertdocument -- Inserts a new object of type document
hw_api->link -- Creates a link to an object
hw_api->lock -- Locks an object
hw_api->move -- Moves object between collections
hw_api_content -- Create new instance of class hw_api_content
hw_api_object->assign -- Clones object
hw_api_object->attreditable -- Checks whether an attribute is editable
hw_api_object->count -- Returns number of attributes
hw_api_object->insert -- Inserts new attribute
hw_api_object -- Creates a new instance of class hw_api_object
hw_api_object->remove -- Removes attribute
hw_api_object->title -- Returns the title attribute
hw_api_object->value -- Returns value of attribute
hw_api->object -- Retrieve attribute information
hw_api->objectbyanchor -- Returns the object an anchor belongs to
hw_api->parents -- Returns parents of an object
hw_api_reason->description -- Returns description of reason
hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
hw_api->replace -- Replaces an object
hw_api->setcommittedversion -- Commits version other than last version
hw_api->srcanchors -- Returns a list of all source anchors
hw_api->srcsofdst -- Returns source of a destination object
hw_api->unlock -- Unlocks a locked object
hw_api->user -- Returns the own user object
hw_api->userlist -- Returns a list of all logged in users

hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

class hw_api_attribute {

string key ( void )

}

Returns the name of the attribute.

Return Values

Returns the name of the attribute as a string.

hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

class hw_api_attribute {

string langdepvalue ( string language )

}

Returns the value in the given language of the attribute.

Parameters

language

Return Values

Returns the value of the attribute as a string.

hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

class hw_api_attribute {

string value ( void )

}

Gets the value of the attribute.

Return Values

Returns the value, as a string.

hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

class hw_api_attribute {

array values ( void )

}

Gets all values of the attribute.

Return Values

Returns an array of attribute values.

hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

HW_API_Attribute hw_api_attribute ( [string name [, string value]] )

Creates a new instance of hw_api_attribute with the given name and value.

Parameters

name

The attribute name.

value

The attribute value.

Return Values

Returns an instance of hw_api_attribute.

hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

class hw_api {

bool checkin ( array parameter )

}

This function checks in an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks in and commits the object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.

HW_API_CHECKIN_FORCE_VERSION_CONTROL

Checks in an object even if it is not under version control.

HW_API_CHECKIN_REVERT_IF_NOT_CHANGED

Check if the new version is different from the last version. Unless this is the case the object will be checked in.

HW_API_CHECKIN_KEEP_TIME_MODIFIED

Keeps the time modified from the most recent object.

HW_API_CHECKIN_NO_AUTO_COMMIT

The object is not automatically committed on check-in.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

class hw_api {

bool checkout ( array parameter )

}

This function checks out an object or a whole hierarchy of objects.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

hw_api->checkin

hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

class hw_api {

array children ( array parameter )

}

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See Also

hw_api->parents

hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

class hw_api_content {

string mimetype ( void )

}

Returns the mimetype of the content.

Return Values

Returns the mimetype as a string.

hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

class hw_api_content {

string read ( string buffer, int len )

}

Reads len bytes from the content into the given buffer.

Parameters

buffer

len

Number of bytes to read.

Return Values

hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

class hw_api {

HW_API_Content content ( array parameter )

}

This function returns the content of a document as an object of type hw_api_content.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN.

HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable.

HW_API_CONTENT_REACHABLELINKS tells this method to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

Return Values

Returns an instance of hw_api_content.

hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

class hw_api {

hw_api_content copy ( array parameter )

}

This function will make a physical copy including the content if it exists and returns the new object or an error object.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

Return Values

Returns the copied object.

hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

class hw_api {

hw_api_object dbstat ( array parameter )

}

Returns statistics about database server.

Parameters

parameter

Return Values

hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

class hw_api {

hw_api_object dcstat ( array parameter )

}

Returns statistics about document cache server.

Parameters

parameter

Return Values

hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

class hw_api {

array dstanchors ( array parameter )

}

Retrieves all destination anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

hw_api->dstofsrcanchor

(no version information, might be only in CVS)

hw_api->dstofsrcanchor -- Returns destination of a source anchor

Description

class hw_api {

hw_api_object dstofsrcanchor ( array parameter )

}

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

class hw_api_error {

int count ( void )

}

Returns the number of error reasons.

Return Values

Returns the number of errors, as an integer.

hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

class hw_api_error {

HW_API_Reason reason ( void )

}

Returns the first error reason.

Return Values

hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

class hw_api {

array find ( array parameter )

}

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index.

Parameters

parameter

The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', 'numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

Return Values

hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

class hw_api {

hw_api_object ftstat ( array parameter )

}

Returns statistics about fulltext server.

Parameters

parameter

Return Values

hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

HW_API hwapi_hgcsp ( string hostname [, int port] )

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP.

Parameters

hostname

The host name.

port

If you do not pass a port number, 418 is used.

Return Values

Returns an instance of HW_API.

hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

class hw_api {

hw_api_object hwstat ( array parameter )

}

Returns statistics about Hyperwave server.

Parameters

parameter

Return Values

hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

class hw_api {

bool identify ( array parameter )

}

Logs into the Hyperwave Server.

Parameters

parameter

The parameter array must contain the elements 'username' and 'password'.

Return Values

Returns an object of typeHW_API_Error if identification failed or TRUE if it was successful.

hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

class hw_api {

array info ( array parameter )

}

Returns information about server configuration.

Parameters

parameter

Return Values

hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

class hw_api {

hw_api_object insert ( array parameter )

}

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set.

Parameters

parameter

The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL

The object in inserted into the server.

HW_API_INSERT_FORCE_VERSION_CONTROL

HW_API_INSERT_AUTOMATIC_CHECKOUT

HW_API_INSERT_PLAIN

HW_API_INSERT_KEEP_TIME_MODIFIED

HW_API_INSERT_DELAY_INDEXING

Return Values

See Also

hw_api->replace

hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

class hw_api {

hw_api_object insertanchor ( array parameter )

}

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor.

Parameters

parameter

The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

Return Values

hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

class hw_api {

hw_api_object insertcollection ( array parameter )

}

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection.

Parameters

parameter

The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

Return Values

hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

class hw_api {

hw_api_object insertdocument ( array parameter )

}

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document.

Parameters

parameter

The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'.

See hwapi_insert() for the meaning of each element.

Return Values

hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

class hw_api {

bool link ( array parameter )

}

Creates a link to an object. Accessing this link is like accessing the object to links points to.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

Return Values

The function returns TRUE on success or an error object.

See Also

hw_api->copy

hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

class hw_api {

bool lock ( array parameter )

}

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the system user.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'.

'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

hw_api->unlock

hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

class hw_api {

bool move ( array parameter )

}

Moves object between collections.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

HW_API_Content hw_api_content ( string content, string mimetype )

Creates a new content object from the string content.

Parameters

content

mimetype

The mimetype for the contents.

Return Values

hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

class hw_api_object {

bool assign ( array parameter )

}

Clones the attributes of an object.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

class hw_api_object {

bool attreditable ( array parameter )

}

Checks whether an attribute is editable.

Parameters

parameter

Return Values

Returns TRUE if the attribute is editable, FALSE otherwise.

hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

class hw_api_object {

int count ( array parameter )

}

Returns the number of attributes.

Parameters

parameter

Return Values

Returns the number as an integer.

hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

class hw_api_object {

bool insert ( HW_API_Attribute attribute )

}

Adds an attribute to the object.

Parameters

attribute

Return Values

Returns TRUE on success or FALSE on failure.

hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

hw_api_object hw_api_object ( array parameter )

Creates a new instance of the class hw_api_object.

Parameters

parameter

Return Values

See Also

hw_api->lock

hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

class hw_api_object {

bool remove ( string name )

}

Removes the attribute with the given name.

Parameters

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

class hw_api_object {

string title ( array parameter )

}

Returns the title attribute.

Parameters

parameter

Return Values

Returns the title as a string.

hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

class hw_api_object {

string value ( string name )

}

Returns value of an attribute.

Parameters

name

The attribute name.

Return Values

Returns the value of the attribute with the given name or FALSE if an error occurred.

hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

class hw_api {

hw_api_object object ( array parameter )

}

This function retrieves the attribute information of an object of any version. It will not return the document content.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

Return Values

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

Examples

This simple example retrieves an object and checks for errors.

Example 1. Retrieve an object

<?php
function handle_error($error)
{
  $reason = $error->reason(0);
  echo "Type: <b>";
  switch ($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</b><br />\n";
  echo "Description: " . $reason->description("en") . "<br />\n";
}

function list_attr($obj)
{
  echo "<table>\n";
  $count = $obj->count();
  for ($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("<tr><td align=\"right\" bgcolor=\"#c0c0c0\"><b>%s</b></td><td bgcolor=\"#F0F0F0\">%s</td></tr>\n",
             $attr->key(), $attr->value());
  }
  echo "</table>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection", "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See Also

hw_api->content

hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

class hw_api {

hw_api_object objectbyanchor ( array parameter )

}

This function retrieves an object the specified anchor belongs to.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

class hw_api {

array parents ( array parameter )

}

Retrieves the parents of an object. The parents can be further filtered by specifying an object query.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

class hw_api_reason {

string description ( void )

}

Returns the description of a reason

Return Values

Returns the description, as a string.

hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

class hw_api_reason {

HW_API_Reason type ( void )

}

Returns the type of a reason.

Return Values

Returns an instance of HW_API_Reason.

hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

class hw_api {

bool remove ( array parameter )

}

Removes an object from the specified parent. Collections will be removed recursively.

Parameters

parameter

You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance.

The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped.

The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

hw_api->move

hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

class hw_api {

hw_api_object replace ( array parameter )

}

Replaces the attributes and the content of an object.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document.

'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

Return Values

See Also

hw_api->insert

hw_api->setcommittedversion

(no version information, might be only in CVS)

hw_api->setcommittedversion -- Commits version other than last version

Description

class hw_api {

hw_api_object setcommittedversion ( array parameter )

}

Commits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed version.

Parameters

parameter

Return Values

hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

class hw_api {

array srcanchors ( array parameter )

}

Retrieves all source anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

class hw_api {

array srcsofdst ( array parameter )

}

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

Return Values

hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

class hw_api {

bool unlock ( array parameter )

}

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Return Values

Returns TRUE on success or an object of class HW_API_Error.

See Also

hw_api->lock

hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

class hw_api {

hw_api_object user ( array parameter )

}

Returns the own user object.

Parameters

parameter

Return Values

hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

class hw_api {

array userlist ( array parameter )

}

Returns a list of all logged in users.

Parameters

parameter

Return Values

See Also

hw_api->user

LVIII. i18n Functions

Introduction

i18n support.

Warning

This extension is still in development and it isn't available to public yet.

Table of Contents
locale_get_default -- Get the default Locale
locale_set_default -- Set the default Locale

locale_get_default

(no version information, might be only in CVS)

locale_get_default -- Get the default Locale

Description

string locale_get_default ( void )

This function returns the default Locale, which is used by PHP to localize certain features. Please note that this isn't influenced by setlocale() or the system settings.

Return Values

Returns a string with the current Locale.

Examples

Example 1. A locale_get_default() example

<?php

// get the default Locale
echo locale_get_default();

//set a new Locale...
locale_set_default('pt_PT');

// ... and print it
echo locale_get_default();

?>

The above example will output:

en_US_POSIX
pt_PT

locale_set_default

(no version information, might be only in CVS)

locale_set_default -- Set the default Locale

Description

bool locale_set_default ( string name )

Sets the default Locale for PHP programs. Please note that this has nothing to do with setlocale() nor with the system locale.

Parameters

name

The new Locale name. A comprehensive list of the supported locales is available at http://www-950.ibm.com/software/globalization/icu/demo/locales/en/?d_=en.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A locale_set_default() example

This example demonstrates a possible usage of locale_set_default() to localize the sort() functions.

<?php

// the list of the strings to sort
$array = array(
    'caramelo',
    'cacto',
    'caçada'
);

// set our locale (Portuguese, in this case)
locale_set_default('pt_PT');

// sort using the locale we previously set
sort($array, SORT_LOCALE_STRING);

print_r($array);
?>

The above example will output:

Array
(
    [0] => caçada
    [1] => cacto
    [2] => caramelo
)

If we didn't use the locale, PHP would sort the string using the ASCII characters value, thus returning (wrongly):

Array
(
    [0] => cacto
    [1] => caramelo
    [2] => caçada
)

LIX. IBM Functions (PDO_IBM)

Introduction

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.


Installation

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: 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 Chapter 7 to install the PDO_IBM extension. Issue the configure command to point to the location of your 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

PDO_IBM DSN

(no version information, might be only in CVS)

PDO_IBM DSN -- Connecting to IBM databases

Description

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.

Examples

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");

LX. IBM DB2, Cloudscape and Apache Derby Functions

Introduction

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).


Requirements

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).


Installation

To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database support site.

If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your DB2 instances.

ibm_db2 is a PECL extension, so follow the instructions in Chapter 7 to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your 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 for IIS users: If you are using the ibm_db2 driver with Microsoft Internet Information Server (IIS) you may have 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.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. ibm_db2 Configure Options

NameDefaultChangeableChangelog
ibm_db2.binmode"1"PHP_INI_ALL 
ibm_db2.i5_allow_commit"0"PHP_INI_SYSTEM 
ibm_db2.i5_dbcs_alloc"0"PHP_INI_SYSTEM 
ibm_db2.instance_nameNULLPHP_INI_SYSTEM 

Here's a short explanation of the configuration directives.

ibm_db2.binmode integer

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_allow_commit integer

This option controls the commit mode used for i5 schema collections in the PHP application.

  • 0 no commit (see i5_commit for override)

  • 1 allow commit (see i5_commit for override)

ibm_db2.i5_dbcs_alloc integer

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.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DB2_BINARY (integer)

Specifies that binary data shall be returned as is. This is the default mode.

DB2_CONVERT (integer)

Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.

DB2_PASSTHRU (integer)

Specifies that binary data shall be converted to a NULL value.

DB2_SCROLLABLE (integer)

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 (integer)

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 (integer)

Specifies the PHP variable should be bound as an IN parameter for a stored procedure.

DB2_PARAM_OUT (integer)

Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.

DB2_PARAM_INOUT (integer)

Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.

DB2_PARAM_FILE (integer)

Specifies that the column should be bound directly to a file for input.

DB2_AUTOCOMMIT_ON (integer)

Specifies that autocommit should be turned on.

DB2_AUTOCOMMIT_OFF (integer)

Specifies that autocommit should be turned off.

DB2_DOUBLE (integer)

Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.

DB2_LONG (integer)

Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.

DB2_CHAR (integer)

Specifies that the variable should be bound as a CHAR or VARCHAR data type.

DB2_CASE_NATURAL (integer)

Specifies that column names will be returned in their natural case.

DB2_CASE_LOWER (integer)

Specifies that column names will be returned in lower case.

DB2_CASE_UPPER (integer)

Specifies that column names will be returned in upper case.

DB2_DEFERRED_PREPARE_ON (integer)

Specifies that deferred prepare should be turned on for the specified statement resource.

DB2_DEFERRED_PREPARE_OFF (integer)

Specifies that deferred prepare should be turned off for the specified statement resource.


Resource Types

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

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_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_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

db2_autocommit

(PECL)

db2_autocommit --  Returns or sets the AUTOCOMMIT state for a database connection

Description

mixed db2_autocommit ( resource connection [, bool value] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Parameters

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.

Return Values

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 0 indicates that AUTOCOMMIT is off, while a value of 1 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. Returns TRUE on success or FALSE on failure.

Examples

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 == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

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 == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

db2_bind_param

(PECL)

db2_bind_param --  Binds a PHP variable to an SQL statement parameter

Description

bool db2_bind_param ( resource stmt, int parameter-number, string variable-name [, int parameter-type [, int data-type [, int precision [, int scale]]]] )

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().

Parameters

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.

scale

Specifies the scale with which the variable should be bound to the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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";	
    }
}
?>

The above example will output:

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";	
    }
}
?>

The above example will output:

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_client_info

(no version information, might be only in CVS)

db2_client_info -- Returns an object with properties that describe the DB2 database client

Description

object db2_client_info ( resource connection )

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:

Table 1. DB2 client properties

Property nameReturn typeDescription
APPL_CODEPAGEintThe application code page.
CONN_CODEPAGEintThe code page for the current connection.
DATA_SOURCE_NAMEstringThe data source name (DSN) used to create the current connection to the database.
DRIVER_NAMEstringThe name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VERstringThe 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_VERstringThe 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_CONFORMANCEstringThe 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_VERstringThe 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".

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns an object on a successful call. Returns FALSE on failure.

Examples

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);

?>

The above example will output:

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_close

(PECL)

db2_close --  Closes a database connection

Description

bool db2_close ( resource connection )

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.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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.";
}
?>

The above example will output:

Connection was successfully closed.

db2_column_privileges

(PECL)

db2_column_privileges --  Returns a result set listing the columns and associated privileges for a table

Description

resource db2_column_privileges ( resource connection [, string qualifier [, string schema [, string table-name [, string column-name]]]] )

Returns a result set listing the columns and associated privileges for a table.

Parameters

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.

Return Values

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 nameDescription
TABLE_CATName of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema.
TABLE_NAMEName of the table or view.
COLUMN_NAMEName of the column.
GRANTORAuthorization ID of the user who granted the privilege.
GRANTEEAuthorization ID of the user to whom the privilege was granted.
PRIVILEGEThe privilege for the column.
IS_GRANTABLEWhether the GRANTEE is permitted to grant this privilege to other users.

db2_columns

(PECL)

db2_columns --  Returns a result set listing the columns and associated metadata for a table

Description

resource db2_columns ( resource connection [, string qualifier [, string schema [, string table-name [, string column-name]]]] )

Returns a result set listing the columns and associated metadata for a table.

Parameters

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.

Return Values

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 nameDescription
TABLE_CATName of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema.
TABLE_NAMEName of the table or view.
COLUMN_NAMEName of the column.
DATA_TYPEThe SQL data type for the column represented as an integer value.
TYPE_NAMEA string representing the data type for the column.
COLUMN_SIZEAn 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).
NULLABLEAn integer value representing whether the column is nullable or not.
REMARKSDescription of the column.
COLUMN_DEFDefault value for the column.
SQL_DATA_TYPEAn 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_POSITIONThe 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_commit

(PECL)

db2_commit --  Commits a transaction

Description

bool db2_commit ( resource connection )

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.

Note: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be committed. For this reason, persistent connections are not recommended for use in applications that require transactions.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

db2_conn_error

(PECL)

db2_conn_error --  Returns a string containing the SQLSTATE returned by the last connection attempt

Description

string db2_conn_error ( [resource connection] )

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.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

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.

Examples

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();
}
?>

The above example will output:

SQLSTATE value: 08001

db2_conn_errormsg

(PECL)

db2_conn_errormsg --  Returns the last connection error message and SQLCODE value

Description

string db2_conn_errormsg ( [resource connection] )

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.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

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.

Examples

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();
}
?>

The above example will output:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

db2_connect

(PECL)

db2_connect --  Returns a connection to a database

Description

resource db2_connect ( string database, string username, string password [, array options] )

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

Parameters

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 i5/OS options are available as of ibm_db2 version 1.5.1. Note: prior versions of ibm_db2 do not support these new i5 options.

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: 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

SQL_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.

Return Values

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Examples

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.";
}
?>

The above example will output:

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.";
}
?>

The above example will output:

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.";
}
?>

The above example will output:

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);
?>

The above example will output:

ANIMALS
NAMES
PICTURES

db2_cursor_type

(PECL)

db2_cursor_type --  Returns the cursor type used by a statement resource

Description

int db2_cursor_type ( resource stmt )

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.

Parameters

stmt

A valid statement resource.

Return Values

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.

See Also

db2_prepare()

db2_escape_string

(no version information, might be only in CVS)

db2_escape_string --  Used to escape certain characters.

Description

string db2_escape_string ( string string_literal )

Prepends backslashes to special characters in the string argument.

Parameters

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.

Return Values

Returns string_literal with the special characters noted above prepended with backslashes.

Examples

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";
    }
}
?>

The above example will output:

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:

See Also

db2_prepare()

db2_exec

(PECL)

db2_exec --  Executes an SQL statement directly

Description

resource db2_exec ( resource connection, string statement [, array options] )

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.

Parameters

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.

cursor

Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.

Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.

Return Values

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Examples

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... ";
    }
}
?>

The above example will output:

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";
    }
} 
?>

The above example will output:

Bubbles
Gizmo
Pook
Rickety Ride

Example 3. Returning XML data as a 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 a 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);

?>

The above example will output:

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 a 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);

?>

The above example will output:

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);

?>

The above example will output:

<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

(PECL)

db2_execute --  Executes a prepared SQL statement

Description

bool db2_execute ( resource stmt [, array parameters] )

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().

Parameters

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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.";
    }
}
?>

The above example will output:

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!";
?>

The above example will output:

I have 7 pets!

Example 3. Returning XML data as a 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 a 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);

?>

The above example will output:

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 a 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);

?>

The above example will output:

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);

?>

The above example will output:

<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_fetch_array

(PECL)

db2_fetch_array --  Returns an array, indexed by column position, representing a row in a result set

Description

array db2_fetch_array ( resource stmt [, int row_number] )

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

Parameters

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.

Return Values

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.

Examples

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]);
}
?>

The above example will output:

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;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_assoc

(PECL)

db2_fetch_assoc --  Returns an array, indexed by column name, representing a row in a result set

Description

array db2_fetch_assoc ( resource stmt [, int row_number] )

Returns an array, indexed by column name, representing a row in a result set.

Parameters

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.

Return Values

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.

Examples

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']);
}
?>

The above example will output:

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;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_both

(PECL)

db2_fetch_both --  Returns an array, indexed by both column name and position, representing a row in a result set

Description

array db2_fetch_both ( resource stmt [, int row_number] )

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().

Parameters

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.

Return Values

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.

Examples

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]);
}
?>

The above example will output:

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;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_object

(PECL)

db2_fetch_object --  Returns an object with properties representing columns in the fetched row

Description

object db2_fetch_object ( resource stmt [, int row_number] )

Returns an object in which each property represents a column returned in the row fetched from a result set.

Parameters

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.

Return Values

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.

Examples

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);
}
?>

The above example will output:

Come here, Pook, my little cat!

db2_fetch_row

(PECL)

db2_fetch_row --  Sets the result set pointer to the next row or requested row

Description

bool db2_fetch_row ( resource stmt [, int row_number] )

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.

Parameters

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.

Return Values

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Examples

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";
}
?>

The above example will output:

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);
?>

The above example will output:

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_field_display_size

(PECL)

db2_field_display_size --  Returns the maximum number of bytes required to display a column

Description

int db2_field_display_size ( resource stmt, mixed column )

Returns the maximum number of bytes required to display a column in a result set.

Parameters

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.

Return Values

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

(PECL)

db2_field_name --  Returns the name of the column in the result set

Description

string db2_field_name ( resource stmt, mixed column )

Returns the name of the specified column in the result set.

Parameters

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.

Return Values

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_num

(PECL)

db2_field_num --  Returns the position of the named column in a result set

Description

int db2_field_num ( resource stmt, mixed column )

Returns the position of the named column in a result set.

Parameters

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.

Return Values

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_precision

(PECL)

db2_field_precision --  Returns the precision of the indicated column in a result set

Description

int db2_field_precision ( resource stmt, mixed column )

Returns the precision of the indicated column in a result set.

Parameters

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.

Return Values

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_scale

(PECL)

db2_field_scale --  Returns the scale of the indicated column in a result set

Description

int db2_field_scale ( resource stmt, mixed column )

Returns the scale of the indicated column in a result set.

Parameters

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.

Return Values

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_type

(PECL)

db2_field_type --  Returns the data type of the indicated column in a result set

Description

string db2_field_type ( resource stmt, mixed column )

Returns the data type of the indicated column in a result set.

Parameters

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.

Return Values

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_width

(PECL)

db2_field_width --  Returns the width of the current value of the indicated column in a result set

Description

int db2_field_width ( resource stmt, mixed column )

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.

Parameters

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.

Return Values

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_foreign_keys

(PECL)

db2_foreign_keys --  Returns a result set listing the foreign keys for a table

Description

resource db2_foreign_keys ( resource connection, string qualifier, string schema, string table-name )

Returns a result set listing the foreign keys for a table.

Parameters

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.

Return Values

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 nameDescription
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_NAMEName of the table containing the primary key.
PKCOLUMN_NAMEName 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_NAMEName of the table containing the foreign key.
FKCOLUMN_NAMEName of the column containing the foreign key.
KEY_SEQ1-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_NAMEThe name of the foreign key.
PK_NAMEThe 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_free_result

(PECL)

db2_free_result --  Frees resources associated with a result set

Description

bool db2_free_result ( resource stmt )

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.

Parameters

stmt

A valid statement resource.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

db2_free_stmt()

db2_free_stmt

(PECL)

db2_free_stmt --  Frees resources associated with the indicated statement resource

Description

bool db2_free_stmt ( resource stmt )

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.

Parameters

stmt

A valid statement resource.

Return Values

Returns TRUE on success or FALSE on failure.

db2_get_option

(no version information, might be only in CVS)

db2_get_option -- Retrieves an option value for a statement resource or a connection resource

Description

string db2_get_option ( resource resource, string option )

Retrieves the value of a specified option value for a statement resource or a connection resource.

Parameters

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:

Table 1. Resource-Parameter Matrix

KeyValueResource Type
  ConnectionStatementResult Set
useridSQL_ATTR_INFO_USERIDXX-
acctstrSQL_ATTR_INFO_ACCTSTRXX-
applnameSQL_ATTR_INFO_APPLNAMEXX-
wrkstnnameSQL_ATTR_INFO_WRKSTNNAMEXX-

Return Values

Returns the current setting of the connection attribute provided on success or FALSE on failure.

Examples

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 conection 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-conection:\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";
?>

The above example will output:

Client attributes passed through conection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

db2_lob_read

(no version information, might be only in CVS)

db2_lob_read --  Gets a user defined size of LOB files with each invocation

Description

string db2_lob_read ( resource stmt, int colnum, int length )

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

Parameters

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.

Return Values

Returns the amount of data the user specifies. Returns FALSE if the data cannot be retrieved.

Examples

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();
}

?>

The above example will output:

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_next_result

(PECL)

db2_next_result --  Requests the next result set from a stored procedure

Description

resource db2_next_result ( resource stmt )

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.

Parameters

stmt

A prepared statement returned from db2_exec() or db2_execute().

Return Values

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.

Examples

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);
}
?>

The above example will output:

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           "
}

db2_num_fields

(PECL)

db2_num_fields --  Returns the number of fields contained in a result set

Description

int db2_num_fields ( resource stmt )

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.

Parameters

stmt

A valid statement resource containing a result set.

Return Values

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.

Examples

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.";
?>

The above example will output:

There are 4 columns in the result set.

db2_num_rows

(PECL)

db2_num_rows --  Returns the number of rows affected by an SQL statement

Description

int db2_num_rows ( resource stmt )

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 boolean return value of the fetch functions to achieve the equivalent functionality with much better performance.

Parameters

stmt

A valid stmt resource containing a result set.

Return Values

Returns the number of rows affected by the last SQL statement issued by the specified statement handle.

db2_pconnect

(PECL)

db2_pconnect --  Returns a persistent connection to a database

Description

resource db2_pconnect ( string database, string username, string password [, array options] )

Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database. For more information on persistent connections, refer to Chapter 41.

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.

Parameters

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.

Return Values

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.

Examples

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.";
}
?>

The above example will output:

Persistent connection succeeded.
Second persistent connection succeeded.

See Also

db2_connect()

db2_prepare

(PECL)

db2_prepare --  Prepares an SQL statement to be executed

Description

resource db2_prepare ( resource connection, string statement [, array options] )

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().

Parameters

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.

cursor

Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.

Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.

Return Values

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().

Examples

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_primary_keys

(PECL)

db2_primary_keys --  Returns a result set listing primary keys for a table

Description

resource db2_primary_keys ( resource connection, string qualifier, string schema, string table-name )

Returns a result set listing the primary keys for a table.

Parameters

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.

Return Values

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 nameDescription
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_NAMEName of the table containing the primary key.
COLUMN_NAMEName of the column containing the primary key.
KEY_SEQ1-indexed position of the column in the key.
PK_NAMEThe name of the primary key.

db2_procedure_columns

(PECL)

db2_procedure_columns --  Returns a result set listing stored procedure parameters

Description

resource db2_procedure_columns ( resource connection, string qualifier, string schema, string procedure, string parameter )

Returns a result set listing the parameters for one or more stored procedures.

Parameters

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.

Return Values

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 nameDescription
PROCEDURE_CATThe catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEMName of the schema that contains the stored procedure.
PROCEDURE_NAMEName of the procedure.
COLUMN_NAMEName of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return valueParameter 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_TYPEThe SQL data type for the parameter represented as an integer value.
TYPE_NAMEA string representing the data type for the parameter.
COLUMN_SIZEAn 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).
NULLABLEAn integer value representing whether the parameter is nullable or not.
REMARKSDescription of the parameter.
COLUMN_DEFDefault value for the parameter.
SQL_DATA_TYPEAn 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_POSITIONThe 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_procedures

(PECL)

db2_procedures --  Returns a result set listing the stored procedures registered in a database

Description

resource db2_procedures ( resource connection, string qualifier, string schema, string procedure )

Returns a result set listing the stored procedures registered in a database.

Parameters

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.

Return Values

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 nameDescription
PROCEDURE_CATThe catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEMName of the schema that contains the stored procedure.
PROCEDURE_NAMEName of the procedure.
NUM_INPUT_PARAMSNumber of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMSNumber of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETSNumber of result sets returned by the stored procedure.
REMARKSAny comments about the stored procedure.
PROCEDURE_TYPEAlways returns 1, indicating that the stored procedure does not return a return value.

db2_result

(PECL)

db2_result --  Returns a single column from a row in the result set

Description

mixed db2_result ( resource stmt, mixed column )

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.

Parameters

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.

Return Values

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.

Examples

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";
}
?>

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

db2_rollback

(PECL)

db2_rollback --  Rolls back a transaction

Description

bool db2_rollback ( resource connection )

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.

Note: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be rolled back. For this reason, persistent connections are not recommended for use in applications that require transactions.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

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);
}
?>

The above example will output:

7
0
7

db2_server_info

(no version information, might be only in CVS)

db2_server_info -- Returns an object with properties that describe the DB2 database server

Description

object db2_server_info ( resource connection )

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:

Table 1. Database server properties

Property nameReturn typeDescription
DBMS_NAMEstringThe 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_VERstringThe 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_CODEPAGEintThe code page of the database to which you are connected.
DB_NAMEstringThe name of the database to which you are connected.
DFT_ISOLATIONstringThe 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_CHARstringThe character used to delimit an identifier.
INST_NAMEstringThe instance on the database server that contains the database.
ISOLATION_OPTIONarrayAn array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDSarrayAn array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSEboolTRUE 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_LENintMaximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LENintMaximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZEintMaximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LENintMaximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZEintMaximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LENintMaximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LENintMaximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LENintMaximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNSboolTRUE 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.
PROCEDURESboolTRUE 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_CHARSstringA string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCEstringThe 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.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns an object on a successful call. Returns FALSE on failure.

Examples

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);
}
?>

The above example will output:

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_set_option

(PECL)

db2_set_option -- Set options for connection or statement resources

Description

bool db2_set_option ( resource resource, array options, int type )

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

Parameters

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 as of ibm_db2 version 1.5.1.

Note: Prior versions of ibm_db2 do not support these new i5 options.

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 options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be accessed 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.

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:

Table 1. Resource-Parameter Matrix

KeyValueResource Type
  ConnectionStatementResult Set
autocommitDB2_AUTOCOMMIT_ONX--
autocommitDB2_AUTOCOMMIT_OFFX--
cursorDB2_SCROLLABLE-X-
cursorDB2_FORWARD_ONLY-X-
binmodeDB2_BINARYXX-
binmodeDB2_CONVERTXX-
binmodeDB2_PASSTHRUXX-
db2_attr_caseDB2_CASE_LOWERXX-
db2_attr_caseDB2_CASE_UPPERXX-
db2_attr_caseDB2_CASE_NATURALXX-
deferred_prepareDB2_DEFERRED_PREPARE_ON-X-
deferred_prepareDB2_DEFERRED_PREPARE_OFF-X-
i5_fetch_onlyDB2_I5_FETCH_ON-X-
i5_fetch_onlyDB2_I5_FETCH_OFF-X-
useridSQL_ATTR_INFO_USERIDXX-
acctstrSQL_ATTR_INFO_ACCTSTRXX-
applnameSQL_ATTR_INFO_APPLNAMEXX-
wrkstnname<