PHP Manual

PHP Manual

Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Philip Olson
Georg Richter
Damien Seguy
Jakub Vrana

Edited by

Gabor Hojtsy

This file was generated: Thu Feb 15 00:43:49 2007
Go to http://www.php.net/docs.php to get the actual version.

Copyright © 1997 - 2007 the PHP Documentation Group


PHP Manual

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

2007-02-14

Copyright © 1997-2007 the PHP Documentation Group

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
L. GMP Functions
LI. gnupg Functions
LII. Net_Gopher
LIII. hash Functions
LIV. HTTP
LV. Hyperwave Functions
LVI. Hyperwave API Functions
LVII. IBM Functions (PDO_IBM)
LVIII. IBM DB2, Cloudscape and Apache Derby Functions
LIX. ICAP Functions [removed]
LX. iconv Functions
LXI. ID3 Functions
LXII. IIS Administration Functions
LXIII. Image Functions
LXIV. Image magick Functions
LXV. IMAP, POP3 and NNTP Functions
LXVI. Informix Functions
LXVII. Informix Functions (PDO_INFORMIX)
LXVIII. Ingres II Functions
LXIX. IRC Gateway Functions
LXX. PHP / Java Integration
LXXI. JSON Functions
LXXII. KADM5
LXXIII. LDAP Functions
LXXIV. libxml Functions
LXXV. Lotus Notes Functions
LXXVI. LZF Functions
LXXVII. Mail Functions
LXXVIII. mailparse Functions
LXXIX. Mathematical Functions
LXXX. MaxDB PHP Extension
LXXXI. MCAL Functions
LXXXII. Mcrypt Encryption Functions
LXXXIII. MCVE (Monetra) Payment Functions
LXXXIV. Memcache Functions
LXXXV. Mhash Functions
LXXXVI. Mimetype Functions
LXXXVII. Ming functions for Flash
LXXXVIII. Miscellaneous Functions
LXXXIX. mnoGoSearch Functions
XC. Microsoft SQL Server Functions
XCI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
XCII. Mohawk Software Session Handler Functions
XCIII. mSQL Functions
XCIV. Multibyte String Functions
XCV. muscat Functions
XCVI. MySQL Functions
XCVII. MySQL Functions (PDO_MYSQL)
XCVIII. MySQL Improved Extension
XCIX. Ncurses Terminal Screen Control Functions
C. Network Functions
CI. Newt Functions
CII. NSAPI-specific Functions
CIII. Object Aggregation/Composition Functions
CIV. Object property and method call overloading
CV. Oracle Functions
CVI. ODBC Functions (Unified)
CVII. ODBC and DB2 Functions (PDO_ODBC)
CVIII. oggvorbis
CIX. OpenAL Audio Bindings
CX. OpenSSL Functions
CXI. Oracle Functions [deprecated]
CXII. Oracle Functions (PDO_OCI)
CXIII. Output Control Functions
CXIV. Ovrimos SQL Functions
CXV. Paradox File Access
CXVI. Parsekit Functions
CXVII. Process Control Functions
CXVIII. Regular Expression Functions (Perl-Compatible)
CXIX. PDF Functions
CXX. PDO Functions
CXXI. Phar archive stream and classes
CXXII. PHP Options&Information
CXXIII. POSIX Functions
CXXIV. Regular Expression Functions (POSIX Extended)
CXXV. PostgreSQL Functions
CXXVI. PostgreSQL Functions (PDO_PGSQL)
CXXVII. Printer Functions
CXXVIII. Program Execution Functions
CXXIX. PostScript document creation
CXXX. Pspell Functions
CXXXI. qtdom Functions
CXXXII. Radius
CXXXIII. Rar Functions
CXXXIV. GNU Readline
CXXXV. GNU Recode Functions
CXXXVI. RPM Header Reading Functions
CXXXVII. runkit Functions
CXXXVIII. SAM - Simple Asynchronous Messaging
CXXXIX. Satellite CORBA client extension [deprecated]
CXL. SCA Functions
CXLI. SDO Functions
CXLII. SDO XML Data Access Service Functions
CXLIII. SDO Relational Data Access Service Functions
CXLIV. Semaphore, Shared Memory and IPC Functions
CXLV. SESAM Database Functions
CXLVI. PostgreSQL Session Save Handler
CXLVII. Session Handling Functions
CXLVIII. Shared Memory Functions
CXLIX. SimpleXML functions
CL. SNMP Functions
CLI. SOAP Functions
CLII. Socket Functions
CLIII. Standard PHP Library (SPL) Functions
CLIV. SQLite Functions
CLV. SQLite Functions (PDO_SQLITE)
CLVI. Secure Shell2 Functions
CLVII. Statistics Functions
CLVIII. Stream Functions
CLIX. String Functions
CLX. Shockwave Flash Functions
CLXI. Swish-e bindings
CLXII. Sybase Functions
CLXIII. TCP Wrappers Functions
CLXIV. Tidy Functions
CLXV. Tokenizer Functions
CLXVI. Unicode Functions
CLXVII. URL Functions
CLXVIII. Variable Handling Functions
CLXIX. Verisign Payflow Pro Functions
CLXX. vpopmail Functions
CLXXI. W32api Functions
CLXXII. WDDX Functions
CLXXIII. win32ps Functions
CLXXIV. win32service Functions
CLXXV. xattr Functions
CLXXVI. xdiff Functions
CLXXVII. XML Parser Functions
CLXXVIII. XML-RPC Functions
CLXXIX. XMLReader functions
CLXXX. XMLWriter Functions
CLXXXI. XSL functions
CLXXXII. XSLT Functions
CLXXXIII. YAZ Functions
CLXXXIV. YP/NIS Functions
CLXXXV. Zip File Functions
CLXXXVI. Zlib Compression Functions
VII. PHP and Zend Engine Internals
44. Streams API for PHP Extension Authors
45. PDO Driver How-To
46. Zend API: Hacking the Core of PHP
47. TSRM API
48. Extending PHP 3
VIII. FAQ: Frequently Asked Questions
49. General Information
50. Mailing lists
51. Obtaining PHP
52. Database issues
53. Installation FAQ
54. Build Problems
55. Using PHP
56. PHP and HTML
57. PHP and COM
58. PHP and other languages
59. Migrating from PHP 2 to PHP 3
60. Migrating from PHP 3 to PHP 4
61. Migrating from PHP 4 to PHP 5
62. Miscellaneous Questions
IX. Appendixes
A. History of PHP and related projects
B. Migrating from PHP 4 to PHP 5
C. Migrating from PHP 3 to PHP 4
D. Migrating from PHP/FI 2 to PHP 3
E. Debugging PHP
F. Configure options
G. php.ini directives
H. List of Supported Timezones
I. Extension Categorization
J. List of Function Aliases
K. List of Reserved Words
L. List of Resource Types
M. List of Supported Protocols/Wrappers
N. List of Available Filters
O. List of Supported Socket Transports
P. PHP type comparison tables
Q. List of Parser Tokens
R. Userland Naming Guide
S. About the manual
T. Open Publication License
U. Function Index
X. HTML Help Edition
63. About This Edition
64. Using PHP Manual CHM Edition
65. The Full Text Search
66. Specialities of this Edition
67. Integrating the PHP Manual
68. Skin development
69. CHM Edition Credits

Next
Preface


Preface

Table of Contents
Authors and Contributors

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 webpages 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: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 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, Vincent Gevers, Aidan Lister, Nuno Lopes and Tom Sommer.

These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.

Prev | Home | Next
PHP Manual |  | Getting Started


Getting Started

PHP Manual
Prev Next

I. Getting Started

Table of Contents
1. Introduction
2. A simple tutorial

Prev | Home | Next
Preface |  | Introduction


Introduction

PHP Manual
Prev Next

Chapter 1. Introduction

Table of Contents
What is PHP?
What can PHP do?

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

&#60;html&#62;
    &#60;head&#62;
        &#60;title&#62;Example&#60;/title&#62;
    &#60;/head&#62;
    &#60;body&#62;

        &#60;?php
        echo "Hi, I'm a PHP script!";
        ?&#62;

    &#60;/body&#62;
&#60;/html&#62;

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.

Prev | Home | Next
Getting Started | Up | What can PHP do?


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 webserver and a web browser. You need to run the webserver, 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 D | InterBase | PostgreSQL
dBase | FrontBase | SQLite
Empress | mSQL | Solid
FilePro (read-only) | Direct MS-SQL | Sybase
Hyperwave | MySQL | Velocis
IBM DB2 | ODBC | Unix dbm
Informix | Oracle (OCI7 and OCI8)
Ingres | Ovrimos

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.

Prev | Home | Next
Introduction | Up | A simple tutorial


A simple tutorial

PHP Manual
Prev Next

Chapter 2. A simple tutorial

Table of Contents
What do I need?
Your first PHP-enabled page
Something Useful
Dealing with Forms
Using old code with new versions of PHP
What's next?

Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic webpage creation with PHP, though PHP is not only capable of creating webpages. 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 webserver 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.

Prev | Home | Next
What can PHP do? | Up | Your first PHP-enabled page


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

&#60;html&#62;
 &#60;head&#62;
  &#60;title&#62;PHP Test&#60;/title&#62;
 &#60;/head&#62;
 &#60;body&#62;
 &#60;?php echo '&#60;p&#62;Hello World&#60;/p&#62;'; ?&#62;
 &#60;/body&#62;
&#60;/html&#62;

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

&#60;?php phpinfo(); ?&#62;

Prev | Home | Next
A simple tutorial | Up | Something Useful


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)

&#60;?php
echo $_SERVER['HTTP_USER_AGENT'];
?&#62;

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

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

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. You can find a list of PHP books at http://www.php.net/books.php.

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

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

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.

Prev | Home | Next
Your first PHP-enabled page | Up | Dealing with Forms


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 &#60;?php echo htmlspecialchars($_POST['name']); ?&#62;.
You are &#60;?php echo (int)$_POST['age']; ?&#62; 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.

Prev | Home | Next
Something Useful | Up | Using old code with new versions of PHP


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.

Prev | Home | Next
Dealing with Forms | Up | What's next?


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/

Prev | Home | Next
Using old code with new versions of PHP | Up | Installation and Configuration


Language Reference

PHP Manual
Prev Next

III. Language Reference

Table of Contents
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

Prev | Home | Next
How to change configuration settings |  | Basic syntax


Basic syntax

PHP Manual
Prev Next

Chapter 10. Basic syntax

Table of Contents
Escaping from HTML
Instruction separation
Comments

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.

&#60;p&#62;This is going to be ignored.&#60;/p&#62;
&#60;?php echo 'While this is going to be parsed.'; ?&#62;
&#60;p&#62;This will also be ignored.&#60;/p&#62;

You can also use more advanced structures:

Example 10-1. Advanced escaping

&#60;?php
if ($expression) {
    ?&#62;
    &#60;strong&#62;This is true.&#60;/strong&#62;
    &#60;?php
} else {
    ?&#62;
    &#60;strong&#62;This is false.&#60;/strong&#62;
    &#60;?php
}
?&#62;
This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds 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.  &#60;?php echo 'if you want to serve XHTML or XML documents, do like this'; ?&#62;

2.  &#60;script language="php"&#62;
        echo 'some editors (like FrontPage) don\'t
              like processing instructions';
    &#60;/script&#62;

3.  &#60;? echo 'this is the simplest, an SGML processing instruction'; ?&#62;
    &#60;?= expression ?&#62; This is a shortcut for "&#60;? echo expression ?&#62;"

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

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.

Prev | Home | Next
Language Reference | Up | Instruction separation


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.

&#60;?php
    echo 'This is a test';
?&#62;

&#60;?php echo 'This is a test' ?&#62;

&#60;?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.

Prev | Home | Next
Basic syntax | Up | Comments


Comments

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

&#60;?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
?&#62;

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.

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

'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.

&#60;?php
 /*
    echo 'This is a test'; /* This comment will cause a problem */
 */
?&#62;

Prev | Home | Next
Instruction separation | Up | Types


Types

PHP Manual
Prev Next

Chapter 11. Types

Table of Contents
Introduction
Booleans
Integers
Floating point numbers
Strings
Arrays
Objects
Resource
NULL
Pseudo-types used in this documentation
Type Juggling

Introduction

PHP supports eight primitive types.

Four scalar types:

  • boolean

  • integer

  • float (floating-point number, aka 'double')

  • string

Two compound types:

  • array

  • object

And finally two special types:

  • resource

  • NULL

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

  • mixed

  • number

  • callback

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:

&#60;?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";
}
?&#62;

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.

Prev | Home | Next
Comments | Up | Booleans


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.

&#60;?php
$foo = True; // assign the value TRUE to $foo
?&#62;

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

&#60;?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 "&#60;hr&#62;\n";
}

// ...because you can simply type
if ($show_separators) {
    echo "&#60;hr&#62;\n";
}
?&#62;

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:

  • the boolean FALSE itself

  • the integer 0 (zero)

  • the float 0.0 (zero)

  • the empty string, and the string "0"

  • an array with zero elements

  • an object with zero member variables (PHP 4 only)

  • the special type NULL (including unset variables)

  • SimpleXML objects created from empty tags

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

Warning

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

&#60;?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)
?&#62;

Prev | Home | Next
Types | Up | Integers


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

&#60;?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)
?&#62;
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.

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

&#60;?php
var_dump(01090); // 010 octal = 8 decimal
?&#62;

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.

&#60;?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)
?&#62;

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.

&#60;?php
var_dump(25/7);         // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4)
?&#62;

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.

&#60;?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?&#62;

See for more information the warning about float-precision.

From strings

See String conversion to numbers

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.

Prev | Home | Next
Booleans | Up | Floating point numbers


Floating point numbers

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

&#60;?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?&#62;

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.

Prev | Home | Next
Integers | Up | Strings


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

  • double quoted

  • heredoc syntax

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.

&#60;?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';
?&#62;

Double quoted

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

Table 11-1. Escaped characters

sequence | meaning
\n | linefeed (LF or 0x0A (10) in ASCII)
\r | carriage return (CR or 0x0D (13) in ASCII)
\t | horizontal 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

&#60;?php
class foo {
    public $bar = &#60;&#60;&#60;EOT
bar
EOT;
}
?&#62;

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

&#60;?php
$str = &#60;&#60;&#60;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-&#62;foo = 'Foo';
        $this-&#62;bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

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

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

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.

&#60;?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
?&#62;

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.

&#60;?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' =&#62; 'red', 'banana' =&#62; '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-&#62;width meters broad.";

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

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:

&#60;?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-&#62;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-&#62;values[3]-&#62;name}";

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

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

&#60;?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};

?&#62;

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.

&#60;?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)
?&#62;

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:

&#60;?php
echo "\$foo==$foo; type is " . gettype ($foo) . "&#60;br /&#62;\n";
?&#62;

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.

Prev | Home | Next
Floating point numbers | Up | Arrays


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

&#60;?php
$arr = array("foo" =&#62; "bar", 12 =&#62; true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?&#62;

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.

&#60;?php
$arr = array("somearray" =&#62; array(6 =&#62; 5, 13 =&#62; 9, "a" =&#62; 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?&#62;

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.

&#60;?php
// This array is the same as ...
array(5 =&#62; 43, 32, 56, "b" =&#62; 12);

// ...this array
array(5 =&#62; 43, 6 =&#62; 32, 7 =&#62; 56, "b" =&#62; 12);
?&#62;

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.

&#60;?php
$arr = array(5 =&#62; 1, 12 =&#62; 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
?&#62;

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:

&#60;?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 =&#62; $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);
?&#62;

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().

&#60;?php
$a = array(1 =&#62; 'one', 2 =&#62; 'two', 3 =&#62; 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 =&#62; 'one', 3 =&#62; 'three');
   and NOT
   $a = array(1 =&#62; 'one', 2 =&#62;'three');
*/

$b = array_values($a);
// Now $b is array(0 =&#62; 'one', 1 =&#62;'three')
?&#62;

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:

&#60;?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?&#62;

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.

&#60;?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 &#60; $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";
}
?&#62;

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:

&#60;?php
// Let's show all errors
error_reporting(E_ALL);

$arr = array('fruit' =&#62; 'apple', 'veggie' =&#62; '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
?&#62;

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:

&#60;?php
echo $arr[somefunc($bar)];
?&#62;

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.

&#60;?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";
?&#62;

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:

&#60;?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";
?&#62;

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.

&#60;?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());
?&#62;

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.

&#60;?php
// this
$a = array( 'color' =&#62; 'red',
            'taste' =&#62; 'sweet',
            'shape' =&#62; 'round',
            'name'  =&#62; '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 =&#62; 'a' , 1 =&#62; 'b' , 2 =&#62; 'c'),
// or simply array('a', 'b', 'c')
?&#62;

Example 11-6. Using array()

&#60;?php
// Array as (property-)map
$map = array( 'version'    =&#62; 4,
              'OS'         =&#62; 'Linux',
              'lang'       =&#62; 'english',
              'short_tags' =&#62; true
            );

// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 =&#62; 7, 1 =&#62; 8, ...)

$switching = array(         10, // key = 0
                    5    =&#62;  6,
                    3    =&#62;  7,
                    'a'  =&#62;  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =&#62;  2, // key = 8 (integer!)
                    '02' =&#62; 77, // key = '02'
                    0    =&#62; 12  // the value 10 will be overwritten by 12
                  );

// empty array
$empty = array();
?&#62;

Example 11-7. Collection

&#60;?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?&#62;

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

&#60;?php
// PHP 5
foreach ($colors as &#38;$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 =&#62; $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?&#62;

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

&#60;?php
$firstquarter  = array(1 =&#62; 'January', 'February', 'March');
print_r($firstquarter);
?&#62;

The above example will output:

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example 11-10. Filling an array

&#60;?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle);
?&#62;

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

&#60;?php
sort($files);
print_r($files);
?&#62;

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

&#60;?php
$fruits = array ( "fruits"  =&#62; array ( "a" =&#62; "orange",
                                       "b" =&#62; "banana",
                                       "c" =&#62; "apple"
                                     ),
                  "numbers" =&#62; array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   =&#62; array (      "first",
                                       5 =&#62; "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";
?&#62;

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.

&#60;?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &#38;$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?&#62;

Prev | Home | Next
Strings | Up | Objects


Objects

Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.

&#60;?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar-&#62;do_foo();
?&#62;

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.

&#60;?php
$obj = (object) 'ciao';
echo $obj-&#62;scalar;  // outputs 'ciao'
?&#62;

Prev | Home | Next
Arrays | Up | Resource


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.

Prev | Home | Next
Objects | Up | NULL


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.

&#60;?php
$var = NULL;
?&#62;

See also is_null() and unset().

Prev | Home | Next
Resource | Up | Pseudo-types used in this documentation


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 builtin 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

&#60;?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'));
?&#62;

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.

Prev | Home | Next
NULL | Up | Type Juggling


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.

&#60;?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)
?&#62;

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:

&#60;?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?&#62;

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.

&#60;?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?&#62;

The casts allowed are:

  • (int), (integer) - cast to integer

  • (bool), (boolean) - cast to boolean

  • (float), (double), (real) - cast to float

  • (string) - cast to string

  • (array) - cast to array

  • (object) - cast to object

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

&#60;?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?&#62;

Note: Instead of casting a variable to string, you can also enclose the variable in double quotes.

&#60;?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";
}
?&#62;

It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:

  • Converting to boolean

  • Converting to integer

  • Converting to float

  • Converting to string

  • Converting to array

  • Converting to object

  • Converting to resource

  • The type comparison tables

Prev | Home | Next
Pseudo-types used in this documentation | Up | Variables


Variables

PHP Manual
Prev Next

Chapter 12. Variables

Table of Contents
Basics
Predefined variables
Variable scope
Variable variables
Variables from outside PHP

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 R.

For information on variable related functions, see the Variable Functions Reference.

&#60;?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.
?&#62;

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:

&#60;?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &#38;$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?&#62;

One important thing to note is that only named variables may be assigned by reference.

&#60;?php
$foo = 25;
$bar = &#38;$foo;      // This is a valid assignment.
$bar = &#38;(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &#38;test();    // Invalid.
?&#62;

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

&#60;?php
echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 =&#62; 25
echo $unset_string . "abc"; // "" . "abc" =&#62; "abc"
$unset_array[3] = "def"; // array() + array(3 =&#62; "def") =&#62; array(3 =&#62; "def")
?&#62;

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.

Prev | Home | Next
Type Juggling | Up | Predefined variables


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.

Prev | Home | Next
Variables | Up | Variable scope


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:

&#60;?php
$a = 1;
include 'b.inc';
?&#62;

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:

&#60;?php
$a = 1; /* global scope */

function Test()
{
    echo $a; /* reference to local scope variable */
}

Test();
?&#62;

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

&#60;?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
}

Sum();
echo $b;
?&#62;

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

&#60;?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?&#62;

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

&#60;?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'];
}
?&#62;

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

&#60;?php
function Test()
{
    $a = 0;
    echo $a;
    $a++;
}
?&#62;

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

&#60;?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?&#62;

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

&#60;?php
function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count &#60; 10) {
        Test();
    }
    $count--;
}
?&#62;

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

&#60;?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;
}
?&#62;

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:

&#60;?php
function test_global_ref() {
    global $obj;
    $obj = &#38;new stdclass;
}

function test_global_noref() {
    global $obj;
    $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?&#62;

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:

&#60;?php
function &#38;get_instance_ref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign a reference to the static variable
        $obj = &#38;new stdclass;
    }
    $obj-&#62;property++;
    return $obj;
}

function &#38;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-&#62;property++;
    return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?&#62;

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.

Prev | Home | Next
Predefined variables | Up | Variable variables


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:

&#60;?php
$a = 'hello';
?&#62;

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.

&#60;?php
$$a = 'world';
?&#62;

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:

&#60;?php
echo "$a ${$a}";
?&#62;

produces the exact same output as:

&#60;?php
echo "$a $hello";
?&#62;

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.

Prev | Home | Next
Variable scope | Up | Variables from outside PHP


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

&#60;?php
if (isset($_POST['action']) &#38;&#38; $_POST['action'] == 'submitted') {
    echo '&#60;pre&#62;';
    print_r($_POST);
    echo '&#60;a href="'. $_SERVER['PHP_SELF'] .'"&#62;Please try again&#60;/a&#62;';

    echo '&#60;/pre&#62;';
} else {
?&#62;
&#60;form action="&#60;?php echo $_SERVER['PHP_SELF']; ?&#62;" method="post"&#62;
    Name:  &#60;input type="text" name="personal[name]" /&#62;&#60;br /&#62;
    Email: &#60;input type="text" name="personal[email]" /&#62;&#60;br /&#62;
    Beer: &#60;br /&#62;
    &#60;select multiple name="beer[]"&#62;
        &#60;option value="warthog"&#62;Warthog&#60;/option&#62;
        &#60;option value="guinness"&#62;Guinness&#60;/option&#62;
        &#60;option value="stuttgarter"&#62;Stuttgarter Schwabenbräu&#60;/option&#62;
    &#60;/select&#62;&#60;br /&#62;
    &#60;input type="hidden" name="action" value="submitted" /&#62;
    &#60;input type="submit" name="submit" value="submit me!" /&#62;
&#60;/form&#62;
&#60;?php
}
?&#62;

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:

&#60;?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?&#62;

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

&#60;?php
if (isset($_COOKIE['count'])) {
    $count = $_COOKIE['count'] + 1;
} else {
    $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?&#62;

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:

&#60;?php
$varname.ext;  /* invalid variable name */
?&#62;
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.

Prev | Home | Next
Variable variables | Up | Constants


Constants

PHP Manual
Prev Next

Chapter 13. Constants

Table of Contents
Syntax
Magic 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 R.

Example 13-1. Valid and invalid constant names

&#60;?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");

?&#62;

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

&#60;?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?&#62;

See also Class Constants.

Prev | Home | Next
Variables from outside PHP | Up | Magic 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

Name | Description
__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().

Prev | Home | Next
Constants | Up | Expressions


Expressions

PHP Manual
Prev Next

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:

&#60;?php
function foo ()
{
    return 5;
}
?&#62;

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:

&#60;?php
$first ? $second : $third
?&#62;

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:

&#60;?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. */
?&#62;

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.

Prev | Home | Next
Magic constants | Up | Operators


Operators

PHP Manual
Prev Next

Chapter 15. Operators

Table of Contents
Operator Precedence
Arithmetic Operators
Assignment Operators
Bitwise Operators
Comparison Operators
Error Control Operators
Execution Operators
Incrementing/Decrementing Operators
Logical Operators
String Operators
Array Operators
Type 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

Associativity | Operators | Additional Information
non-associative | new | new
left | [ | array()
non-associative | ++ -- | increment/decrement
non-associative | ~ - (int) (float) (string) (array) (object) @ | types
non-associative | instanceof | 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
left | and | logical
left | xor | logical
left | or | 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

&#60;?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) -&#62; $a = 5, $b = 5
?&#62;
Use parentheses to increase readability of the code.

Note: Although ! has a higher precedence than =, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

Prev | Home | Next
Expressions | Up | Arithmetic Operators


Arithmetic Operators

Remember basic arithmetic from school? These work just like those.

Table 15-2. Arithmetic Operators

Example | Name | Result
-$a | Negation | Opposite of $a.
$a + $b | Addition | Sum of $a and $b.
$a - $b | Subtraction | Difference of $a and $b.
$a * $b | Multiplication | Product of $a and $b.
$a / $b | Division | Quotient of $a and $b.
$a % $b | Modulus | Remainder of $a divided by $b.

The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers).

Note: Remainder $a % $b is negative for negative $a.

See also the manual page on Math functions.

Prev | Home | Next
Operators | Up | Assignment Operators


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:

&#60;?php

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

?&#62;

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:

&#60;?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!";

?&#62;

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 PHP5 objects are assigned by reference unless explicitly told otherwise with the new clone keyword.

Prev | Home | Next
Arithmetic Operators | Up | Bitwise Operators


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.

&#60;?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
?&#62;

Table 15-3. Bitwise Operators

Example | Name | Result
$a & $b | And | Bits that are set in both $a and $b are set.
$a | $b | Or | Bits that are set in either $a or $b are set.
$a ^ $b | Xor | Bits that are set in $a or $b but not both are set.
~ $a | Not | Bits that are set in $a are not set, and vice versa.
$a << $b | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b | Shift 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.

Prev | Home | Next
Assignment Operators | Up | Comparison Operators


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

Example | Name | Result
$a == $b | Equal | TRUE if $a is equal to $b.
$a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b | Not equal | TRUE if $a is not equal to $b.
$a <> $b | Not equal | TRUE if $a is not equal to $b.
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b | Less than | TRUE if $a is strictly less than $b.
$a > $b | Greater than | TRUE if $a is strictly greater than $b.
$a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b.
$a >= $b | Greater 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.

&#60;?php
var_dump(0 == "a"); // 0 == 0 -&#62; true
var_dump("1" == "01"); // 1 == 1 -&#62; true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?&#62;

For various types, comparison is done according to the following table (in order).

Table 15-5. Comparison with Various Types

Type of Operand 1 | Type of Operand 2 | Result
null or string | string | Convert NULL to "", numerical or lexical comparison
bool or null | anything | Convert to bool, FALSE < TRUE
object | object | Built-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 number | string, resource or number | Translate strings and resources to numbers, usual math
array | array | Array 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)
array | anything | array is always greater
object | anything | object is always greater

Example 15-2. Transcription of standard array comparison

&#60;?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
    if (count($op1) &#60; count($op2)) {
        return -1; // $op1 &#60; $op2
    } elseif (count($op1) &#62; count($op2)) {
        return 1; // $op1 &#62; $op2
    }
    foreach ($op1 as $key =&#62; $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val &#60; $op2[$key]) {
            return -1;
        } elseif ($val &#62; $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?&#62;

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

&#60;?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'];
}

?&#62;
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

&#60;?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.
?&#62;

Prev | Home | Next
Bitwise Operators | Up | Error Control Operators


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.

&#60;?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.

?&#62;

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.

Prev | Home | Next
Comparison Operators | Up | Execution Operators


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().

&#60;?php
$output = `ls -al`;
echo "&#60;pre&#62;$output&#60;/pre&#62;";
?&#62;

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.

Prev | Home | Next
Error Control Operators | Up | Incrementing/Decrementing Operators


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

Example | Name | Effect
++$a | Pre-increment | Increments $a by one, then returns $a.
$a++ | Post-increment | Returns $a, then increments $a by one.
--$a | Pre-decrement | Decrements $a by one, then returns $a.
$a-- | Post-decrement | Returns $a, then decrements $a by one.

Here's a simple example script:

&#60;?php
echo "&#60;h3&#62;Postincrement&#60;/h3&#62;";
$a = 5;
echo "Should be 5: " . $a++ . "&#60;br /&#62;\n";
echo "Should be 6: " . $a . "&#60;br /&#62;\n";

echo "&#60;h3&#62;Preincrement&#60;/h3&#62;";
$a = 5;
echo "Should be 6: " . ++$a . "&#60;br /&#62;\n";
echo "Should be 6: " . $a . "&#60;br /&#62;\n";

echo "&#60;h3&#62;Postdecrement&#60;/h3&#62;";
$a = 5;
echo "Should be 5: " . $a-- . "&#60;br /&#62;\n";
echo "Should be 4: " . $a . "&#60;br /&#62;\n";

echo "&#60;h3&#62;Predecrement&#60;/h3&#62;";
$a = 5;
echo "Should be 4: " . --$a . "&#60;br /&#62;\n";
echo "Should be 4: " . $a . "&#60;br /&#62;\n";
?&#62;

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

&#60;?php
$i = 'W';
for ($n=0; $n&#60;6; $n++) {
    echo ++$i . "\n";
}
?&#62;

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.

Prev | Home | Next
Execution Operators | Up | Logical Operators


Logical Operators

Table 15-7. Logical Operators

Example | Name | Result
$a and $b | And | TRUE if both $a and $b are TRUE.
$a or $b | Or | TRUE if either $a or $b is TRUE.
$a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both.
! $a | Not | TRUE if $a is not TRUE.
$a && $b | And | TRUE if both $a and $b are TRUE.
$a || $b | Or | TRUE 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.)

Prev | Home | Next
Incrementing/Decrementing Operators | Up | String Operators


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.

&#60;?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?&#62;

See also the manual sections on the String type and String functions.

Prev | Home | Next
Logical Operators | Up | Array Operators


Array Operators

Table 15-8. Array Operators

Example | Name | Result
$a + $b | Union | Union of $a and $b.
$a == $b | Equality | TRUE if $a and $b have the same key/value pairs.
$a === $b | Identity | TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b | Inequality | TRUE if $a is not equal to $b.
$a <> $b | Inequality | TRUE if $a is not equal to $b.
$a !== $b | Non-identity | TRUE if $a is not identical to $b.

The + operator appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

&#60;?php
$a = array("a" =&#62; "apple", "b" =&#62; "banana");
$b = array("a" =&#62; "pear", "b" =&#62; "strawberry", "c" =&#62; "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);
?&#62;

When executed, this script will print the following:
Union of $a and $b:
array(3) {
  ["a"]=&#62;
  string(5) "apple"
  ["b"]=&#62;
  string(6) "banana"
  ["c"]=&#62;
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=&#62;
  string(4) "pear"
  ["b"]=&#62;
  string(10) "strawberry"
  ["c"]=&#62;
  string(6) "cherry"
}

Elements of arrays are equal for the comparison if they have the same key and value.

Example 15-6. Comparing arrays

&#60;?php
$a = array("apple", "banana");
$b = array(1 =&#62; "banana", "0" =&#62; "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?&#62;

See also the manual sections on the Array type and Array functions.

Prev | Home | Next
String Operators | Up | Type Operators


Type Operators

PHP has a single type operator: instanceof is used to determine whether a given object, his parents or their implemented interfaces are of a specified object class.

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.

&#60;?php
class A { }
class B { }

$thing = new A;

if ($thing instanceof A) {
    echo 'A';
}
if ($thing instanceof B) {
    echo 'B';
}
?&#62;

As $thing is an object of type A, but not B, only the block dependent on the A type will be executed:

A

See also get_class() and is_a().

Prev | Home | Next
Array Operators | Up | Control Structures


Control Structures

PHP Manual
Prev Next

Chapter 16. Control Structures

Table of Contents
if
else
elseif
Alternative syntax for control structures
while
do-while
for
foreach
break
continue
switch
declare
return
require()
include()
require_once()
include_once()

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:

&#60;?php
if ($a &#62; $b)
    echo "a is bigger than b";
?&#62;

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:

&#60;?php
if ($a &#62; $b) {
    echo "a is bigger than b";
    $b = $a;
}
?&#62;

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.

Prev | Home | Next
Type Operators | Up | else


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:

&#60;?php
if ($a &#62; $b) {
    echo "a is bigger than b";
} else {
    echo "a is NOT bigger than b";
}
?&#62;

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).

Prev | Home | Next
Control Structures | Up | 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:

&#60;?php
if ($a &#62; $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?&#62;

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.

Prev | Home | Next
else | Up | Alternative syntax for control structures


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.

&#60;?php if ($a == 5): ?&#62;
A is equal to 5
&#60;?php endif; ?&#62;

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:

&#60;?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;
?&#62;

See also while, for, and if for further examples.

Prev | Home | Next
elseif | Up | while


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 numbers from 1 to 10:

&#60;?php
/* example 1 */

$i = 1;
while ($i &#60;= 10) {
    echo $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i &#60;= 10):
    echo $i;
    $i++;
endwhile;
?&#62;

Prev | Home | Next
Alternative syntax for control structures | Up | do-while


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:

&#60;?php
$i = 0;
do {
    echo $i;
} while ($i &#62; 0);
?&#62;

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:

&#60;?php
do {
    if ($i &#60; 5) {
        echo "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i &#60; $minimum_limit) {
        break;
    }
   echo "i is ok";

    /* process i */

} while (0);
?&#62;

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'.

Prev | Home | Next
while | Up | for


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 numbers from 1 to 10:

&#60;?php
/* example 1 */

for ($i = 1; $i &#60;= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i &#62; 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
    if ($i &#62; 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i &#60;= 10; $j += $i, print $i, $i++);
?&#62;

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;

Prev | Home | Next
do-while | Up | foreach


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.

&#60;?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &#38;$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?&#62;

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:

&#60;?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value&#60;br /&#62;\n";
}

foreach ($arr as $value) {
    echo "Value: $value&#60;br /&#62;\n";
}
?&#62;

The following are also functionally identical:

&#60;?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value&#60;br /&#62;\n";
}

foreach ($arr as $key =&#62; $value) {
    echo "Key: $key; Value: $value&#60;br /&#62;\n";
}
?&#62;

Some more examples to demonstrate usages:

&#60;?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] =&#62; $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" =&#62; 1,
    "two" =&#62; 2,
    "three" =&#62; 3,
    "seventeen" =&#62; 17
);

foreach ($a as $k =&#62; $v) {
    echo "\$a[$k] =&#62; $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";
}
?&#62;

Prev | Home | Next
for | Up | break


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.

&#60;?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&#60;br /&#62;\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5&#60;br /&#62;\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting&#60;br /&#62;\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?&#62;

Prev | Home | Next
foreach | Up | continue


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.

&#60;?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ &#60; 5) {
    echo "Outer&#60;br /&#62;\n";
    while (1) {
        echo "&#38;nbsp;&#38;nbsp;Middle&#60;br /&#62;\n";
        while (1) {
            echo "&#38;nbsp;&#38;nbsp;Inner&#60;br /&#62;\n";
            continue 3;
        }
        echo "This never gets output.&#60;br /&#62;\n";
    }
    echo "Neither does this.&#60;br /&#62;\n";
}
?&#62;

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

&#60;?php
  for ($i = 0; $i &#60; 5; ++$i) {
      if ($i == 2)
          continue
      print "$i\n";
  }
?&#62;

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.

Prev | Home | Next
break | Up | switch


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

&#60;?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;
}
?&#62;

Example 16-2. switch structure allows usage of strings

&#60;?php
switch ($i) {
case "apple":
    echo "i is apple";
    break;
case "bar":
    echo "i is bar";
    break;
case "cake":
    echo "i is cake";
    break;
}
?&#62;

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:

&#60;?php
switch ($i) {
case 0:
    echo "i equals 0";
case 1:
    echo "i equals 1";
case 2:
    echo "i equals 2";
}
?&#62;

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.

&#60;?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";
}
?&#62;

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:

&#60;?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";
}
?&#62;

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 .

&#60;?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;
?&#62;

Prev | Home | Next
continue | Up | declare


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.

&#60;?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
?&#62;

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

&#60;?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 &#60; 50; ++$x) {
        echo similar_text(md5($x), md5($x*$x)), "&#60;br /&#62;;";
    }
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?&#62;
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().

Prev | Home | Next
switch | Up | return


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).

Prev | Home | Next
declare | Up | require()


require

PHP Manual
Prev Chapter 16. Control Structures Next

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

&#60;?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?&#62;

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.

Prev | Home | Next
return | Up | include()


include

PHP Manual
Prev Chapter 16. Control Structures Next

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 include_path relative to the directory of current script. E.g. if your include_path is ., 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/ 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
&#60;?php

$color = 'green';
$fruit = 'apple';

?&#62;

test.php
&#60;?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?&#62;

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

&#60;?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

?&#62;

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 M 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

&#60;?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&#38;bar=2';

// Won't work; looks for a file named 'file.php?foo=1&#38;bar=2' on the
// local filesystem.
include 'file.php?foo=1&#38;bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&#38;bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Works.
include 'file.php';  // Works.

?&#62;

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

&#60;?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';
}
?&#62;

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
&#60;?php

$var = 'PHP';

return $var;

?&#62;

noreturn.php
&#60;?php

$var = 'PHP';

?&#62;

testreturns.php
&#60;?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?&#62;

$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

&#60;?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;
}

?&#62;

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

PHP Manual
Prev Chapter 16. Control Structures Next

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

&#60;?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)
?&#62;
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

PHP Manual
Prev Chapter 16. Control Structures Next

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

&#60;?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)
?&#62;
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().

Prev | Home | Next
require_once() | Up | Functions


Functions

PHP Manual
Prev Next

Chapter 17. Functions

Table of Contents
User-defined functions
Function arguments
Returning values
Variable functions
Internal (built-in) functions

User-defined functions

A function may be defined using syntax such as the following:

Example 17-1. Pseudo code to demonstrate function uses

&#60;?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?&#62;

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 R.

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

&#60;?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";
}

?&#62;

Example 17-3. Functions within functions

&#60;?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();

?&#62;

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

&#60;?php
function recursion($a)
{
    if ($a &#60; 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?&#62;

Prev | Home | Next
include_once() | Up | Function arguments


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

&#60;?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?&#62;

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

&#60;?php
function add_some_extra(&#38;$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?&#62;

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

&#60;?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?&#62;

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

&#60;?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");
?&#62;

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

&#60;?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected
?&#62;

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

&#60;?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // works as expected
?&#62;

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.

Prev | Home | Next
Functions | Up | Returning values


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()

&#60;?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?&#62;

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

&#60;?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?&#62;

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

&#60;?php
function &#38;returns_reference()
{
    return $someref;
}

$newref =&#38; returns_reference();
?&#62;

For more information on references, please check out References Explained.

Prev | Home | Next
Function arguments | Up | Variable functions


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

&#60;?php
function foo() {
    echo "In foo()&#60;br /&#62;\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.&#60;br /&#62;\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()
?&#62;

You can also call an object's method by using the variable functions feature.

Example 17-15. Variable method example

&#60;?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this-&#62;$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo-&#62;$funcname();  // This calls $foo-&#62;Variable()

?&#62;

See also call_user_func(), variable variables and function_exists().

Prev | Home | Next
Returning values | Up | Internal (built-in) functions


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().

Prev | Home | Next
Variable functions | Up | Classes and Objects (PHP 4)


Classes and Objects (PHP 4)

PHP Manual
Prev Next

Chapter 18. Classes and Objects (PHP 4)

Table of Contents
class
extends
Constructors
Scope Resolution Operator (::)
parent
Serializing objects - objects in sessions
The magic functions __sleep and __wakeup
References inside the constructor
Comparing objects

class

A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:

&#60;?php
class Cart {
    var $items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart

    function add_item($artnr, $num) {
        $this-&#62;items[$artnr] += $num;
    }

    // Take $num articles of $artnr out of the cart

    function remove_item($artnr, $num) {
        if ($this-&#62;items[$artnr] &#62; $num) {
            $this-&#62;items[$artnr] -= $num;
            return true;
        } elseif ($this-&#62;items[$artnr] == $num) {
            unset($this-&#62;items[$artnr]);
            return true;
        } else {
            return false;
        }
    }
}
?&#62;

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:

&#60;?php
class test {
?&#62;
&#60;?php
    function test() {
        print 'OK';
    }
}
?&#62;

However, the following is allowed:

&#60;?php
class test {
    function test() {
        ?&#62;
        &#60;?php
        print 'OK';
    }
}
?&#62;

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).

&#60;?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-&#62;todays_date = date("Y-m-d");
        $this-&#62;name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?&#62;

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.

&#60;?php
$cart = new Cart;
$cart-&#62;add_item("10", 1);

$another_cart = new Cart;
$another_cart-&#62;add_item("0815", 3);
?&#62;

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.

&#60;?php
// correct, single $
$cart-&#62;items = array("10" =&#62; 1);

// invalid, because $cart-&#62;$items becomes $cart-&#62;""
$cart-&#62;$items = array("10" =&#62; 1);

// correct, but may or may not be what was intended:
// $cart-&#62;$myvar becomes $cart-&#62;items
$myvar = 'items';
$cart-&#62;$myvar = array("10" =&#62; 1);
?&#62;

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:

&#60;?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-&#62;foo();
A::foo();
$b = new B();
$b-&#62;bar();
B::bar();
?&#62;

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.

Prev | Home | Next
Internal (built-in) functions | Up | extends


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'.

&#60;?php
class Named_Cart extends Cart {
    var $owner;

    function set_owner ($name) {
        $this-&#62;owner = $name;
    }
}
?&#62;

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:

&#60;?php
$ncart = new Named_Cart;    // Create a named cart
$ncart-&#62;set_owner("kris");  // Name that cart
print $ncart-&#62;owner;        // print the cart owners name
$ncart-&#62;add_item("10", 1);  // (inherited functionality from cart)
?&#62;

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.

Prev | Home | Next
Classes and Objects (PHP 4) | Up | Constructors


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.

&#60;?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this-&#62;add_item("10", 1);
    }
}
?&#62;

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.

&#60;?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1) {
        $this-&#62;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);
?&#62;

You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.

&#60;?php
class A
{
    function A()
    {
        echo "I am the constructor of A.&#60;br /&#62;\n";
    }

    function B()
    {
        echo "I am a regular function named B in class A.&#60;br /&#62;\n";
        echo "I am not a constructor in A.&#60;br /&#62;\n";
    }
}

class B extends A
{
}

// This will call B() as a constructor
$b = new B;
?&#62;

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.

Prev | Home | Next
extends | Up | Scope Resolution Operator (::)


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.

&#60;?php
class A {
    function example() {
        echo "I am the original function A::example().&#60;br /&#62;\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().&#60;br /&#62;\n";
        A::example();
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().&#60;br /&#62;
A::example();

// create an object of class B.
$b = new B;

// this will print
//   I am the redefined function B::example().&#60;br /&#62;
//   I am the original function A::example().&#60;br /&#62;
$b-&#62;example();
?&#62;

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.

Prev | Home | Next
Constructors | Up | parent


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.

&#60;?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.&#60;br /&#62;\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.&#60;br /&#62;\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b-&#62;example();
?&#62;

Prev | Home | Next
Scope Resolution Operator (::) | Up | Serializing objects - objects in sessions


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.

&#60;?php
// classa.inc:

  class A {
      var $one = 1;

      function show_one() {
          echo $this-&#62;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-&#62;show_one();
?&#62;

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.

Prev | Home | Next
parent | Up | The magic functions __sleep and __wakeup


The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized.

The intended use of __sleep is to close any database connections that object may have, committing pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Prev | Home | Next
Serializing objects - objects in sessions | Up | References inside the constructor


References inside the constructor

Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

&#60;?php
class Foo {
    function Foo($name) {
        // create a reference inside the global array $globalref
        global $globalref;
        $globalref[] = &#38;$this;
        // set name to passed value
        $this-&#62;setName($name);
        // and put it out
        $this-&#62;echoName();
    }

    function echoName() {
        echo "&#60;br /&#62;", $this-&#62;name;
    }

    function setName($name) {
        $this-&#62;name = $name;
    }
}
?&#62;

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

&#60;?php
$bar1 = new Foo('set in constructor');
$bar1-&#62;echoName();
$globalref[0]-&#62;echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =&#38; new Foo('set in constructor');
$bar2-&#62;echoName();
$globalref[1]-&#62;echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?&#62;

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.

&#60;?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1-&#62;setName('set from outside');

// as mentioned before this is not the case.
$bar1-&#62;echoName();
$globalref[0]-&#62;echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2-&#62;setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2-&#62;name and $globalref[1]-&#62;name are the same too
$bar2-&#62;echoName();
$globalref[1]-&#62;echoName();

/* output:
set from outside
set from outside */
?&#62;

Another final example, try to understand it.

&#60;?php
class A {
    function A($i) {
        $this-&#62;value = $i;
        // try to figure out why we do not need a reference here
        $this-&#62;b = new B($this);
    }

    function createRef() {
        $this-&#62;c = new B($this);
    }

    function echoValue() {
        echo "&#60;br /&#62;","class ",get_class($this),': ',$this-&#62;value;
    }
}

class B {
    function B(&#38;$a) {
        $this-&#62;a = &#38;$a;
    }

    function echoValue() {
        echo "&#60;br /&#62;","class ",get_class($this),': ',$this-&#62;a-&#62;value;
    }
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =&#38; new A(10);
$a-&#62;createRef();

$a-&#62;echoValue();
$a-&#62;b-&#62;echoValue();
$a-&#62;c-&#62;echoValue();

$a-&#62;value = 11;

$a-&#62;echoValue();
$a-&#62;b-&#62;echoValue(); // *
$a-&#62;c-&#62;echoValue();

?&#62;

The above example will output:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11

Prev | Home | Next
The magic functions __sleep and __wakeup | Up | Comparing objects


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

&#60;?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&#38;$o1, &#38;$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-&#62;flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this-&#62;flag = true;
    }

    function turnOff() {
        $this-&#62;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);
?&#62;

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

&#60;?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this-&#62;set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this-&#62;set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this-&#62;set)) {
            unset($this-&#62;set[$name]);
        }
    }
}

$u = new FlagSet();
$u-&#62;addFlag('flag1', $o);
$u-&#62;addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=&#62;$q, 'flag2'=&#62;$p));
$w = new FlagSet(array('flag1'=&#62;$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);
?&#62;

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

Prev | Home | Next
References inside the constructor | Up | Classes and Objects (PHP 5)


Classes and Objects (PHP 5)

PHP Manual
Prev Next

Chapter 19. Classes and Objects (PHP 5)

Table of Contents
Introduction
The Basics
Autoloading Objects
Constructors and Destructors
Visibility
Scope Resolution Operator (::)
Static Keyword
Class Constants
Class Abstraction
Object Interfaces
Overloading
Object Iteration
Patterns
Magic Methods
Final Keyword
Object cloning
Comparing objects
Reflection
Type Hinting

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 R.

Prev | Home | Next
Comparing objects | Up | The Basics


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

&#60;?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-&#62;foo();
A::foo();
$b = new B();
$b-&#62;bar();
B::bar();
?&#62;

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

&#60;?php
class SimpleClass
{
    // member declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this-&#62;var;
    }
}
?&#62;

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

&#60;?php
class SimpleClass
{
    // invalid member declarations:
    public $var1 = 'hello '.'world';
    public $var2 = &#60;&#60;&#60;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);

}
?&#62;

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

&#60;?php
$instance = new SimpleClass();
?&#62;

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

&#60;?php
$assigned   =  $instance;
$reference  =&#38; $instance;

$instance-&#62;var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?&#62;

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 Inherintance

&#60;?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended-&#62;displayVar();
?&#62;

The above example will output:

Extending class
a default value

Prev | Home | Next
Classes and Objects (PHP 5) | Up | Autoloading Objects


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.

Example 19-7. Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

&#60;?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?&#62;

Prev | Home | Next
The Basics | Up | Constructors and Destructors


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

&#60;?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();
?&#62;

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

&#60;?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this-&#62;name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this-&#62;name . "\n";
   }
}

$obj = new MyDestructableClass();
?&#62;

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.

Prev | Home | Next
Autoloading Objects | Up | Visibility


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

&#60;?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this-&#62;public;
        echo $this-&#62;protected;
        echo $this-&#62;private;
    }
}

$obj = new MyClass();
echo $obj-&#62;public; // Works
echo $obj-&#62;protected; // Fatal Error
echo $obj-&#62;private; // Fatal Error
$obj-&#62;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-&#62;public;
        echo $this-&#62;protected;
        echo $this-&#62;private;
    }
}

$obj2 = new MyClass2();
echo $obj-&#62;public; // Works
echo $obj2-&#62;private; // Undefined
echo $obj2-&#62;protected; // Fatal Error
$obj2-&#62;printHello(); // Shows Public, Protected2, not Private

?&#62;

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

&#60;?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-&#62;MyPublic();
        $this-&#62;MyProtected();
        $this-&#62;MyPrivate();
    }
}

$myclass = new MyClass;
$myclass-&#62;MyPublic(); // Works
$myclass-&#62;MyProtected(); // Fatal Error
$myclass-&#62;MyPrivate(); // Fatal Error
$myclass-&#62;Foo(); // Public, Protected and Private work

/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This is public
    function Foo2()
    {
        $this-&#62;MyPublic();
        $this-&#62;MyProtected();
        $this-&#62;MyPrivate(); // Fatal Error
    }
}

$myclass2 = new MyClass2;
$myclass2-&#62;MyPublic(); // Works
$myclass2-&#62;Foo2(); // Public and Protected work, not Private
?&#62;

Prev | Home | Next
Constructors and Destructors | Up | Scope Resolution Operator (::)


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

&#60;?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

echo MyClass::CONST_VALUE;
?&#62;

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

&#60;?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();
?&#62;

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

&#60;?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-&#62;myFunc();
?&#62;

Prev | Home | Next
Visibility | Up | Static Keyword


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

&#60;?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-&#62;staticValue() . "\n";
print $foo-&#62;my_static . "\n";      // Undefined "Property" my_static

// $foo::my_static is not possible

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar-&#62;fooStatic() . "\n";
?&#62;

Example 19-16. Static method example

&#60;?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
?&#62;

Prev | Home | Next
Scope Resolution Operator (::) | Up | Class Constants


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

&#60;?php
class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}

echo MyClass::constant . "\n";

$class = new MyClass();
$class-&#62;showConstant();
// echo $class::constant;  is not allowed
?&#62;

Prev | Home | Next
Static Keyword | Up | Class Abstraction


Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.

Example 19-18. Abstract class example

&#60;?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-&#62;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-&#62;printOut();
echo $class1-&#62;prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2-&#62;printOut();
echo $class2-&#62;prefixValue('FOO_') ."\n";
?&#62;

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.

Prev | Home | Next
Class Constants | Up | Object Interfaces


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

&#60;?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-&#62;vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this-&#62;vars as $name =&#62; $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-&#62;vars[$name] = $var;
    }
}

?&#62;

See also the instanceof operator.

Prev | Home | Next
Class Abstraction | Up | Overloading


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.

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

&#60;?php
class Setter
{
    public $n;
    private $x = array("a" =&#62; 1, "b" =&#62; 2, "c" =&#62; 3);

    public function __get($nm)
    {
        echo "Getting [$nm]\n";

        if (isset($this-&#62;x[$nm])) {
            $r = $this-&#62;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-&#62;x[$nm])) {
            $this-&#62;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-&#62;x[$nm]);
    }

    public function __unset($nm)
    {
        echo "Unsetting $nm\n";

        unset($this-&#62;x[$nm]);
    }
}

$foo = new Setter();
$foo-&#62;n = 1;
$foo-&#62;a = 100;
$foo-&#62;a++;
$foo-&#62;z++;

var_dump(isset($foo-&#62;a)); //true
unset($foo-&#62;a);
var_dump(isset($foo-&#62;a)); //false

// this doesn't pass through the __isset() method
// because 'n' is a public property
var_dump(isset($foo-&#62;n));

var_dump($foo);
?&#62;

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"]=&#62;
  int(1)
  ["x:private"]=&#62;
  array(2) {
    ["b"]=&#62;
    int(2)
    ["c"]=&#62;
    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

&#60;?php
class Caller
{
    private $x = array(1, 2, 3);

    public function __call($m, $a)
    {
        print "Method $m called:\n";
        var_dump($a);
        return $this-&#62;x;
    }
}

$foo = new Caller();
$a = $foo-&#62;test(1, "2", 3.4, true);
var_dump($a);
?&#62;

The above example will output:

Method test called:
array(4) {
    [0]=&#62;
    int(1)
    [1]=&#62;
    string(1) "2"
    [2]=&#62;
    float(3.4)
    [3]=&#62;
    bool(true)
}
array(3) {
    [0]=&#62;
    int(1)
    [1]=&#62;
    int(2)
    [2]=&#62;
    int(3)
}

Prev | Home | Next
Object Interfaces | Up | Object Iteration


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

&#60;?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 =&#62; $value) {
           print "$key =&#62; $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key =&#62; $value) {
    print "$key =&#62; $value\n";
}
echo "\n";

$class-&#62;iterateVisible();

?&#62;

The above example will output:

var1 =&#62; value 1
var2 =&#62; value 2
var3 =&#62; value 3

MyClass::iterateVisible:
var1 =&#62; value 1
var2 =&#62; value 2
var3 =&#62; value 3
protected =&#62; protected var
private =&#62; 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

&#60;?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this-&#62;var = $array;
        }
    }

    public function rewind() {
        echo "rewinding\n";
        reset($this-&#62;var);
    }

    public function current() {
        $var = current($this-&#62;var);
        echo "current: $var\n";
        return $var;
    }

    public function key() {
        $var = key($this-&#62;var);
        echo "key: $var\n";
        return $var;
    }

    public function next() {
        $var = next($this-&#62;var);
        echo "next: $var\n";
        return $var;
    }

    public function valid() {
        $var = $this-&#62;current() !== false;
        echo "valid: {$var}\n";
        return $var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a =&#62; $b) {
    print "$a: $b\n";
}
?&#62;

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

&#60;?php
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this-&#62;items);
    }

    public function add($value) {
        $this-&#62;items[$this-&#62;count++] = $value;
    }
}

$coll = new MyCollection();
$coll-&#62;add('value 1');
$coll-&#62;add('value 2');
$coll-&#62;add('value 3');

foreach ($coll as $key =&#62; $val) {
    echo "key/value: [$key -&#62; $val]\n\n";
}
?&#62;

The above example will output:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -&#62; value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -&#62; value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -&#62; value 3]

next:
current:
valid:

Note: For more examples of iterators, see the SPL Extension.

Prev | Home | Next
Overloading | Up | Patterns


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

&#60;?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');
        }
    }
}
?&#62;

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:

&#60;?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?&#62;

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

&#60;?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);
    }

}

?&#62;

This allows a single instance of the Example class to be retrieved.

&#60;?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-&#62;bark();

// This will issue an E_USER_ERROR.
$test_clone = clone $test;

?&#62;

Prev | Home | Next
Object Iteration | Up | Magic Methods


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.

The intended use of __sleep is to close any database connections that the object may have, commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example 19-27. Sleep and wakeup

&#60;?php
class Connection {
    protected $link;
    private $server, $username, $password, $db;

    public function __construct($server, $username, $password, $db)
    {
        $this-&#62;server = $server;
        $this-&#62;username = $username;
        $this-&#62;password = $password;
        $this-&#62;db = $db;
        $this-&#62;connect();
    }

    private function connect()
    {
        $this-&#62;link = mysql_connect($this-&#62;server, $this-&#62;username, $this-&#62;password);
        mysql_select_db($this-&#62;db, $this-&#62;link);
    }

    public function __sleep()
    {
        mysql_close($this-&#62;link);
    }

    public function __wakeup()
    {
        $this-&#62;connect();
    }
}
?&#62;

__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

&#60;?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this-&#62;foo = $foo;
    }

    public function __toString() {
        return $this-&#62;foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?&#62;

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, ...).

Prev | Home | Next
Patterns | Up | Final Keyword


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

&#60;?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()
?&#62;

Example 19-30. Final class example

&#60;?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)
?&#62;

Prev | Home | Next
Magic Methods | Up | Object cloning


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

&#60;?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this-&#62;instance = ++self::$instances;
    }

    public function __clone() {
        $this-&#62;instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // Force a copy of this-&#62;object, otherwise
        // it will point to same object.
        $this-&#62;object1 = clone $this-&#62;object1;
    }
}

$obj = new MyCloneable();

$obj-&#62;object1 = new SubObject();
$obj-&#62;object2 = new SubObject();

$obj2 = clone $obj;

print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?&#62;

The above example will output:

Original Object:
MyCloneable Object
(
    [object1] =&#62; SubObject Object
        (
            [instance] =&#62; 1
        )

    [object2] =&#62; SubObject Object
        (
            [instance] =&#62; 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] =&#62; SubObject Object
        (
            [instance] =&#62; 3
        )

    [object2] =&#62; SubObject Object
        (
            [instance] =&#62; 2
        )

)

Prev | Home | Next
Final Keyword | Up | Comparing objects


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

&#60;?php
function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

function compareObjects(&#38;$o1, &#38;$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-&#62;flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this-&#62;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);
?&#62;

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

Prev | Home | Next
Object cloning | Up | Reflection


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:

&#60;?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunction { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?&#62;

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

&#60;?php
Reflection::export(new ReflectionClass('Exception'));
?&#62;

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.

&#60;?php
class ReflectionFunction implements Reflector
{
    final private __clone()
    public object __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()
}
?&#62;

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

&#60;?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(
    "===&#62; The %s function '%s'\n".
    "     declared in %s\n".
    "     lines %d to %d\n",
    $func-&#62;isInternal() ? 'internal' : 'user-defined',
    $func-&#62;getName(),
    $func-&#62;getFileName(),
    $func-&#62;getStartLine(),
    $func-&#62;getEndline()
);

// Print documentation comment
printf("---&#62; Documentation:\n %s\n", var_export($func-&#62;getDocComment(), 1));

// Print static variables if existant
if ($statics = $func-&#62;getStaticVariables())
{
    printf("---&#62; Static variables: %s\n", var_export($statics, 1));
}

// Invoke the function
printf("---&#62; Invokation results in: ");
var_dump($func-&#62;invoke());

// you may prefer to use the export() method
echo "\nReflectionFunction::export() results:\n";
echo ReflectionFunction::export('counter');
?&#62;

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.

&#60;?php
class ReflectionParameter implements Reflector
{
    final private __clone()
    public object __construct(string name)
    public string __toString()
    public static string export(mixed function, mixed parameter, bool return)
    public string getName()
    public bool isPassedByReference()
    public ReflectionFunction getDeclaringFunction()
    public ReflectionClass getDeclaringClass()
    public ReflectionClass getClass()
    public bool isArray()
    public bool allowsNull()
    public bool isPassedByReference()
    public bool getPosition()
    public bool isOptional()
    public bool isDefaultValueAvailable()
    public mixed getDefaultValue()
}
?&#62;

Note:
     getDefaultValue(),
     isDefaultValueAvailable() and
     isOptional() were added in PHP 5.0.3,
     while isArray() was added in PHP 5.1.0.
     getDeclaringFunction() and
     getPosition() were added in PHP 5.1.3.

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

&#60;?php
function foo($a, $b, $c) { }
function bar(Exception $a, &#38;$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-&#62;getParameters() as $i =&#62; $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-&#62;getName(),
        var_export($param-&#62;getClass(), 1),
        var_export($param-&#62;allowsNull(), 1),
        var_export($param-&#62;isPassedByReference(), 1),
        $param-&#62;isOptional() ? 'yes' : 'no'
    );
}
?&#62;

ReflectionClass

The ReflectionClass class lets you reverse-engineer classes.

&#60;?php
class ReflectionClass implements Reflector
{
    final private __clone()
    public object __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()
}
?&#62;

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

&#60;?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(
    "===&#62; 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-&#62;isInternal() ? 'internal' : 'user-defined',
        $class-&#62;isAbstract() ? ' abstract' : '',
        $class-&#62;isFinal() ? ' final' : '',
        $class-&#62;isInterface() ? 'interface' : 'class',
        $class-&#62;getName(),
        var_export($class-&#62;getParentClass(), 1),
        $class-&#62;getFileName(),
        $class-&#62;getStartLine(),
        $class-&#62;getEndline(),
        $class-&#62;getModifiers(),
        implode(' ', Reflection::getModifierNames($class-&#62;getModifiers()))
);

// Print documentation comment
printf("---&#62; Documentation:\n %s\n", var_export($class-&#62;getDocComment(), 1));

// Print which interfaces are implemented by this class
printf("---&#62; Implements:\n %s\n", var_export($class-&#62;getInterfaces(), 1));

// Print class constants
printf("---&#62; Constants: %s\n", var_export($class-&#62;getConstants(), 1));

// Print class properties
printf("---&#62; Properties: %s\n", var_export($class-&#62;getProperties(), 1));

// Print class methods
printf("---&#62; Methods: %s\n", var_export($class-&#62;getMethods(), 1));

// If this class is instantiable, create an instance
if ($class-&#62;isInstantiable()) {
    $counter = $class-&#62;newInstance();

    echo '---&#62; $counter is instance? ';
    echo $class-&#62;isInstance($counter) ? 'yes' : 'no';

    echo "\n---&#62; new Object() is instance? ";
    echo $class-&#62;isInstance(new Object()) ? 'yes' : 'no';
}
?&#62;

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.

&#60;?php
class ReflectionObject extends ReflectionClass
{
    final private __clone()
    public object __construct(mixed object)
    public string __toString()
    public static string export(mixed object, bool return)
}
?&#62;

ReflectionMethod

The ReflectionMethod class lets you reverse-engineer class methods.

&#60;?php
class ReflectionMethod extends ReflectionFunction
{
    public __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()
}
?&#62;

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

&#60;?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(
    "===&#62; 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-&#62;isInternal() ? 'internal' : 'user-defined',
        $method-&#62;isAbstract() ? ' abstract' : '',
        $method-&#62;isFinal() ? ' final' : '',
        $method-&#62;isPublic() ? ' public' : '',
        $method-&#62;isPrivate() ? ' private' : '',
        $method-&#62;isProtected() ? ' protected' : '',
        $method-&#62;isStatic() ? ' static' : '',
        $method-&#62;getName(),
        $method-&#62;isConstructor() ? 'the constructor' : 'a regular method',
        $method-&#62;getFileName(),
        $method-&#62;getStartLine(),
        $method-&#62;getEndline(),
        $method-&#62;getModifiers(),
        implode(' ', Reflection::getModifierNames($method-&#62;getModifiers()))
);

// Print documentation comment
printf("---&#62; Documentation:\n %s\n", var_export($method-&#62;getDocComment(), 1));

// Print static variables if existant
if ($statics= $method-&#62;getStaticVariables()) {
    printf("---&#62; Static variables: %s\n", var_export($statics, 1));
}

// Invoke the method
printf("---&#62; Invokation results in: ");
var_dump($method-&#62;invoke(NULL));
?&#62;

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.

&#60;?php
class ReflectionProperty implements Reflector
{
    final private __clone()
    public __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()
}
?&#62;

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

&#60;?php
class String
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String', 'length');

// Print out basic information
printf(
    "===&#62; The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop-&#62;isPublic() ? ' public' : '',
        $prop-&#62;isPrivate() ? ' private' : '',
        $prop-&#62;isProtected() ? ' protected' : '',
        $prop-&#62;isStatic() ? ' static' : '',
        $prop-&#62;getName(),
        $prop-&#62;isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop-&#62;getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---&#62; Value is: ");
var_dump($prop-&#62;getValue($obj));

// Change value
$prop-&#62;setValue($obj, 10);
printf("---&#62; Setting value to 10, new value is: ");
var_dump($prop-&#62;getValue($obj));

// Dump object
var_dump($obj);
?&#62;

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().

&#60;?php
class ReflectionExtension implements Reflector {
    final private __clone()
    public __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()
}
?&#62;

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

&#60;?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-&#62;getName(),
        $ext-&#62;getVersion() ? $ext-&#62;getVersion() : 'NO_VERSION',
        sizeof($ext-&#62;getFunctions()),
        var_export($ext-&#62;getFunctions(), 1),

        sizeof($ext-&#62;getConstants()),
        var_export($ext-&#62;getConstants(), 1),

        sizeof($ext-&#62;getINIEntries()),
        var_export($ext-&#62;getINIEntries(), 1),

        sizeof($ext-&#62;getClassNames()),
        var_export($ext-&#62;getClassNames(), 1)
);
?&#62;

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

&#60;?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = '';

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this-&#62;visibility= Reflection::getModifierNames($this-&#62;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'));
?&#62;

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

Prev | Home | Next
Comparing objects | Up | Type Hinting


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

&#60;?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-&#62;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';
}
?&#62;

Failing to satisfy the type hint results in a fatal error.

&#60;?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass-&#62;test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass-&#62;test($foo);

// Fatal Error: Argument 1 must not be null
$myclass-&#62;test(null);

// Works: Prints Hello World
$myclass-&#62;test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass-&#62;test_array('a string');

// Works: Prints the array
$myclass-&#62;test_array(array('a', 'b', 'c'));
?&#62;

Type hinting also works with functions:

&#60;?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-&#62;var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?&#62;

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.

Prev | Home | Next
Reflection | Up | Exceptions


Exceptions

PHP Manual
Prev Next

Chapter 20. Exceptions

Table of Contents
Extending 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

&#60;?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-&#62;getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?&#62;

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

&#60;?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
}
?&#62;

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

&#60;?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-&#62;code}]: {$this-&#62;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-&#62;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-&#62;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-&#62;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";
?&#62;

Prev | Home | Next
Type Hinting | Up | References Explained


References Explained

PHP Manual
Prev Next

Chapter 21. References Explained

Table of Contents
What References Are
What References Do
What References Are Not
Passing by Reference
Returning References
Unsetting References
Spotting References

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.

Prev | Home | Next
Exceptions | Up | What References Do


What References Do

PHP references allow you to make two variables to refer to the same content. Meaning, when you do:

&#60;?php
$a =&#38; $b;
?&#62;

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.

The same syntax can be used with functions, that return references, and with new operator (in PHP 4.0.4 and later):

&#60;?php
$bar =&#38; new fooclass();
$foo =&#38; find_var($bar);
?&#62;

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-1. Referencing global variables inside function

&#60;?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =&#38; $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =&#38; $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'
?&#62;
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-2. References and foreach statement

&#60;?php
$ref = 0;
$row =&#38; $ref;
foreach (array(1, 2, 3) as $row) {
    // do something
}
echo $ref; // 3 - last element of the iterated array
?&#62;

Warning

Complex arrays are sometimes rather copied than referenced. Thus following example will not work as expected.

Example 21-3. References with complex arrays

&#60;?php
$top = array(
    'A' =&#62; array(),
    'B' =&#62; array(
        'B_b' =&#62; array(),
    ),
);

$top['A']['parent'] = &#38;$top;
$top['B']['parent'] = &#38;$top;
$top['B']['B_b']['data'] = 'test';
print_r($top['A']['parent']['B']['B_b']); // array()
?&#62;

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:

&#60;?php
function foo(&#38;$var)
{
    $var++;
}

$a=5;
foo($a);
?&#62;

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.

Prev | Home | Next
References Explained | Up | What References Are Not


What References Are Not

As said before, references aren't pointers. That means, the following construct won't do what you expect:

&#60;?php
function foo(&#38;$var)
{
    $var =&#38; $GLOBALS["baz"];
}
foo($bar);
?&#62;

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.

Prev | Home | Next
What References Do | Up | Passing by Reference


Passing by Reference

You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:

&#60;?php
function foo(&#38;$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?&#62;

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.:

    &#60;?php
    function &#38;bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());
    ?&#62;

    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:

&#60;?php
function bar() // Note the missing &#38;
{
    $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
?&#62;

These requirements are for PHP 4.0.4 and later.

Prev | Home | Next
What References Are Not | Up | Returning References


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:

&#60;?php
function &#38;find_var($param)
{
    /* ...code... */
    return $found_var;
}

$foo =&#38; find_var($bar);
$foo-&#62;x = 2;
?&#62;

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.

Prev | Home | Next
Passing by Reference | Up | Unsetting References


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:

&#60;?php
$a = 1;
$b =&#38; $a;
unset($a);
?&#62;

won't unset $b, just $a.

Again, it might be useful to think about this as analogous to Unix unlink call.

Prev | Home | Next
Returning References | Up | Spotting References


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:

&#60;?php
$var =&#38; $GLOBALS["var"];
?&#62;

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.

Prev | Home | Next
Unsetting References | Up | Security


Security

PHP Manual
Prev Next

IV. Security

Table of Contents
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

Prev | Home | Next
Spotting References |  | Introduction


Introduction

PHP Manual
Prev Next

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.

Prev | Home | Next
Security | Up | General considerations


General considerations

PHP Manual
Prev Next

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.

Prev | Home | Next
Introduction | Up | Installed as CGI binary


Installed as CGI binary

PHP Manual
Prev Next

Chapter 24. Installed as CGI binary

Table of Contents
Possible attacks
Case 1: only public files served
Case 2: using --enable-force-cgi-redirect
Case 3: setting doc_root or user_dir
Case 4: PHP parser outside of web tree

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.

Prev | Home | Next
General considerations | Up | Case 1: only public files served


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).

Prev | Home | Next
Installed as CGI binary | Up | Case 2: using --enable-force-cgi-redirect


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.

Prev | Home | Next
Case 1: only public files served | Up | Case 3: setting doc_root or user_dir


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.

Prev | Home | Next
Case 2: using --enable-force-cgi-redirect | Up | Case 4: PHP parser outside of web tree


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.

Prev | Home | Next
Case 3: setting doc_root or user_dir | Up | Installed as an Apache module


Installed as an Apache module

PHP Manual
Prev Next

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.

Prev | Home | Next
Case 4: PHP parser outside of web tree | Up | Filesystem Security


Filesystem Security

PHP Manual
Prev Next

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

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

Example 26-2. ... A filesystem attack

&#60;?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd has been deleted!";
?&#62;
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

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

$homedir = "/home/$username";

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

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

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

Example 26-4. More secure file name checking

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

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

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

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.

Prev | Home | Next
Installed as an Apache module | Up | Database Security


Database Security

PHP Manual
Prev Next

Chapter 27. Database Security

Table of Contents
Designing Databases
Connecting to Database
Encrypted Storage Model
SQL Injection

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.

Prev | Home | Next
Filesystem Security | Up | Connecting to Database


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.

Prev | Home | Next
Database Security | Up | Encrypted Storage Model


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

&#60;?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) &#62; 0) {
    echo 'Welcome, $username!';
} else {
    echo 'Authentication failed for $username.';
}

?&#62;

Prev | Home | Next
Connecting to Database | Up | SQL Injection


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)

&#60;?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);

?&#62;
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)

&#60;?php

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);

?&#62;
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)

&#60;?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?&#62;
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:

&#60;?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
...;";

?&#62;

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)

&#60;?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?&#62;
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

&#60;?php

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

?&#62;

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

    &#60;?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);

    ?&#62;

  • 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.

Prev | Home | Next
Encrypted Storage Model | Up | Error Reporting


Error Reporting

PHP Manual
Prev Next

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 webserver has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.

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

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

&#60;?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");
}
?&#62;

Prev | Home | Next
SQL Injection | Up | Using Register Globals


Using Register Globals

PHP Manual
Prev Next

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

&#60;?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";
}
?&#62;

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

&#60;?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo "Hello &#60;b&#62;{$_SESSION['username']}&#60;/b&#62;";

} else {

    echo "Hello &#60;b&#62;Guest&#60;/b&#62;&#60;br /&#62;";
    echo "Would you like to login?";

}
?&#62;

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

&#60;?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

}
?&#62;

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

Prev | Home | Next
Error Reporting | Up | User Submitted Data


User Submitted Data

PHP Manual
Prev Next

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

&#60;?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);

?&#62;
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).

Prev | Home | Next
Using Register Globals | Up | Magic Quotes


Magic Quotes

PHP Manual
Prev Next

Chapter 31. Magic Quotes

Table of Contents
What are Magic Quotes
Why use Magic Quotes
Why not to use Magic Quotes
Disabling 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.

Prev | Home | Next
User Submitted Data | Up | Why use Magic Quotes


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.

Prev | Home | Next
Magic Quotes | Up | Why not to use Magic Quotes


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().

Prev | Home | Next
Why use Magic Quotes | Up | Disabling Magic Quotes


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

&#60;?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);
}
?&#62;

Prev | Home | Next
Why not to use Magic Quotes | Up | Hiding PHP


Hiding PHP

PHP Manual
Prev Next

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.

Prev | Home | Next
Disabling Magic Quotes | Up | Keeping Current


Keeping Current

PHP Manual
Prev Next

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.

Prev | Home | Next
Hiding PHP | Up | Features


Features

PHP Manual
Prev Next

V. Features

Table of Contents
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

Prev | Home | Next
Keeping Current |  | HTTP authentication with PHP


HTTP authentication with PHP

PHP Manual
Prev Next

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

&#60;?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 "&#60;p&#62;Hello {$_SERVER['PHP_AUTH_USER']}.&#60;/p&#62;";
    echo "&#60;p&#62;You entered {$_SERVER['PHP_AUTH_PW']} as your password.&#60;/p&#62;";
}
?&#62;

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.

&#60;?php
$realm = 'Restricted area';

//user =&#62; password
$users = array('admin' =&#62; 'mypass', 'guest' =&#62; '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 &#38; 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'=&#62;1, 'nc'=&#62;1, 'cnonce'=&#62;1, 'qop'=&#62;1, 'username'=&#62;1, 'uri'=&#62;1, 'response'=&#62;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;
}
?&#62;

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

&#60;?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 &#38;&#38; $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    authenticate();
} else {
    echo "&#60;p&#62;Welcome: {$_SERVER['PHP_AUTH_USER']}&#60;br /&#62;";
    echo "Old: {$_REQUEST['OldAuth']}";
    echo "&#60;form action='{$_SERVER['PHP_SELF']}' METHOD='post'&#62;\n";
    echo "&#60;input type='hidden' name='SeenBefore' value='1' /&#62;\n";
    echo "&#60;input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' /&#62;\n";
    echo "&#60;input type='submit' value='Re Authenticate' /&#62;\n";
    echo "&#60;/form&#62;&#60;/p&#62;\n";
}
?&#62;

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.

Prev | Home | Next
Features | Up | Cookies


Cookies

PHP Manual
Prev Next

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.

Prev | Home | Next
HTTP authentication with PHP | Up | Sessions


Sessions

PHP Manual
Prev Next

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.

Prev | Home | Next
Cookies | Up | Dealing with XForms


Dealing with XForms

PHP Manual
Prev Next

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.

Prev | Home | Next
Sessions | Up | Handling file uploads


Handling file uploads

PHP Manual
Prev Next

Chapter 38. Handling file uploads

Table of Contents
POST method uploads
Error Messages Explained
Common Pitfalls
Uploading multiple files
PUT method support

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. This is an advisory to the browser, PHP also checks it. 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.

&#60;?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 '&#60;pre&#62;';
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 "&#60;/pre&#62;";

?&#62;

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>
&#60;?php
foreach ($_FILES["pictures"]["error"] as $key =&#62; $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");
    }
}
?&#62;

Prev | Home | Next
Dealing with XForms | Up | Error Messages Explained


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.

Prev | Home | Next
Handling file uploads | Up | Common Pitfalls


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[]).

Prev | Home | Next
Error Messages Explained | Up | Uploading multiple files


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.

Prev | Home | Next
Common Pitfalls | Up | PUT method support


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

&#60;?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);
?&#62;

Note: All documentation below applies to PHP 3 only.

Example 38-6. Saving HTTP PUT files with PHP 3

&#60;?php copy($PHP_UPLOADED_FILE_NAME, $DOCUMENT_ROOT . $REQUEST_URI); ?&#62;

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.

Prev | Home | Next
Uploading multiple files | Up | Using remote files


Using remote files

PHP Manual
Prev Next

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 M 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 LXIII, 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

&#60;?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "&#60;p&#62;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 ("&#60;title&#62;(.*)&#60;/title&#62;", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?&#62;

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

&#60;?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "&#60;p&#62;Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?&#62;

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().

Prev | Home | Next
PUT method support | Up | Connection handling


Connection handling

PHP Manual
Prev Next

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.

Prev | Home | Next
Using remote files | Up | Persistent Database Connections


Persistent Database Connections

PHP Manual
Prev Next

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().

Prev | Home | Next
Connection handling | Up | Safe Mode


Safe Mode

PHP Manual
Prev Next

Chapter 42. Safe Mode

Table of Contents
Security and Safe Mode
Functions restricted/disabled by 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

Name | Default | Changeable | Changelog
safe_mode | "0" | PHP_INI_SYSTEM |
safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available 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_basedir | NULL | PHP_INI_SYSTEM |
disable_functions | "" | php.ini only | Available since PHP 4.0.1.
disable_classes | "" | php.ini only | Available 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 this script.php
&#60;?php
 readfile('/etc/passwd');
?&#62;
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.

Prev | Home | Next
Persistent Database Connections | Up | Functions restricted/disabled by safe mode


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

Function | Limitations
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 operator | This 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 | ??

Prev | Home | Next
Safe Mode | Up | Using PHP from the command line


Using PHP from the command line

PHP Manual
Prev Next

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

    Directive | CLI SAPI default value | Comment
    html_errors | FALSE | 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_flush | TRUE | 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_time | 0 (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_argv TRUE

    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

    Constant Description
    STDIN An already opened stream to stdin. This saves opening it with
    &#60;?php

    $stdin = fopen('php://stdin', 'r');

    ?&#62;
    If you want to read single line from stdin, you can use
    &#60;?php
    $line = trim(fgets(STDIN)); // reads one line from STDIN
    fscanf(STDIN, "%d\n", $number); // reads number from STDIN
    ?&#62;
    STDOUT An already opened stream to stdout. This saves opening it with
    &#60;?php

    $stdout = fopen('php://stdout', 'w');

    ?&#62;
    STDERR An already opened stream to stderr. This saves opening it with
    &#60;?php

    $stderr = fopen('php://stderr', 'w');

    ?&#62;

    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:

    &#60;?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?&#62;

    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 as interactive shell
  -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

  --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
&#60;?php
var_dump($argv);
?&#62;

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

Option | Long Option | Description
-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.

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

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

Example 43-3. 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.

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

-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 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-4. Script intended to be run from command line (script.php)

#!/usr/bin/php
&#60;?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?&#62;

This is a command line PHP script with one option.

  Usage:
  &#60;?php echo $argv[0]; ?&#62; &#60;option&#62;

  &#60;option&#62; can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

&#60;?php
} else {
    echo $argv[1];
}
?&#62;

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-5. 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.

Prev | Home | Next
Functions restricted/disabled by safe mode | Up | Function Reference


Function Reference

PHP Manual
Prev Next

VI. Function Reference

See also Appendix I.

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
L. GMP Functions
LI. gnupg Functions
LII. Net_Gopher
LIII. hash Functions
LIV. HTTP
LV. Hyperwave Functions
LVI. Hyperwave API Functions
LVII. IBM Functions (PDO_IBM)
LVIII. IBM DB2, Cloudscape and Apache Derby Functions
LIX. ICAP Functions [removed]
LX. iconv Functions
LXI. ID3 Functions
LXII. IIS Administration Functions
LXIII. Image Functions
LXIV. Image magick Functions
LXV. IMAP, POP3 and NNTP Functions
LXVI. Informix Functions
LXVII. Informix Functions (PDO_INFORMIX)
LXVIII. Ingres II Functions
LXIX. IRC Gateway Functions
LXX. PHP / Java Integration
LXXI. JSON Functions
LXXII. KADM5
LXXIII. LDAP Functions
LXXIV. libxml Functions
LXXV. Lotus Notes Functions
LXXVI. LZF Functions
LXXVII. Mail Functions
LXXVIII. mailparse Functions
LXXIX. Mathematical Functions
LXXX. MaxDB PHP Extension
LXXXI. MCAL Functions
LXXXII. Mcrypt Encryption Functions
LXXXIII. MCVE (Monetra) Payment Functions
LXXXIV. Memcache Functions
LXXXV. Mhash Functions
LXXXVI. Mimetype Functions
LXXXVII. Ming functions for Flash
LXXXVIII. Miscellaneous Functions
LXXXIX. mnoGoSearch Functions
XC. Microsoft SQL Server Functions
XCI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
XCII. Mohawk Software Session Handler Functions
XCIII. mSQL Functions
XCIV. Multibyte String Functions
XCV. muscat Functions
XCVI. MySQL Functions
XCVII. MySQL Functions (PDO_MYSQL)
XCVIII. MySQL Improved Extension
XCIX. Ncurses Terminal Screen Control Functions
C. Network Functions
CI. Newt Functions
CII. NSAPI-specific Functions
CIII. Object Aggregation/Composition Functions
CIV. Object property and method call overloading
CV. Oracle Functions
CVI. ODBC Functions (Unified)
CVII. ODBC and DB2 Functions (PDO_ODBC)
CVIII. oggvorbis
CIX. OpenAL Audio Bindings
CX. OpenSSL Functions
CXI. Oracle Functions [deprecated]
CXII. Oracle Functions (PDO_OCI)
CXIII. Output Control Functions
CXIV. Ovrimos SQL Functions
CXV. Paradox File Access
CXVI. Parsekit Functions
CXVII. Process Control Functions
CXVIII. Regular Expression Functions (Perl-Compatible)
CXIX. PDF Functions
CXX. PDO Functions
CXXI. Phar archive stream and classes
CXXII. PHP Options&Information
CXXIII. POSIX Functions
CXXIV. Regular Expression Functions (POSIX Extended)
CXXV. PostgreSQL Functions
CXXVI. PostgreSQL Functions (PDO_PGSQL)
CXXVII. Printer Functions
CXXVIII. Program Execution Functions
CXXIX. PostScript document creation
CXXX. Pspell Functions
CXXXI. qtdom Functions
CXXXII. Radius
CXXXIII. Rar Functions
CXXXIV. GNU Readline
CXXXV. GNU Recode Functions
CXXXVI. RPM Header Reading Functions
CXXXVII. runkit Functions
CXXXVIII. SAM - Simple Asynchronous Messaging
CXXXIX. Satellite CORBA client extension [deprecated]
CXL. SCA Functions
CXLI. SDO Functions
CXLII. SDO XML Data Access Service Functions
CXLIII. SDO Relational Data Access Service Functions
CXLIV. Semaphore, Shared Memory and IPC Functions
CXLV. SESAM Database Functions
CXLVI. PostgreSQL Session Save Handler
CXLVII. Session Handling Functions
CXLVIII. Shared Memory Functions
CXLIX. SimpleXML functions
CL. SNMP Functions
CLI. SOAP Functions
CLII. Socket Functions
CLIII. Standard PHP Library (SPL) Functions
CLIV. SQLite Functions
CLV. SQLite Functions (PDO_SQLITE)
CLVI. Secure Shell2 Functions
CLVII. Statistics Functions
CLVIII. Stream Functions
CLIX. String Functions
CLX. Shockwave Flash Functions
CLXI. Swish-e bindings
CLXII. Sybase Functions
CLXIII. TCP Wrappers Functions
CLXIV. Tidy Functions
CLXV. Tokenizer Functions
CLXVI. Unicode Functions
CLXVII. URL Functions
CLXVIII. Variable Handling Functions
CLXIX. Verisign Payflow Pro Functions
CLXX. vpopmail Functions
CLXXI. W32api Functions
CLXXII. WDDX Functions
CLXXIII. win32ps Functions
CLXXIV. win32service Functions
CLXXV. xattr Functions
CLXXVI. xdiff Functions
CLXXVII. XML Parser Functions
CLXXVIII. XML-RPC Functions
CLXXIX. XMLReader functions
CLXXX. XMLWriter Functions
CLXXXI. XSL functions
CLXXXII. XSLT Functions
CLXXXIII. YAZ Functions
CLXXXIV. YP/NIS Functions
CLXXXV. Zip File Functions
CLXXXVI. Zlib Compression Functions

Prev | Home | Next
Using PHP from the command line |  | .NET Functions


Apache-specific Functions

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
engine | "1" | PHP_INI_ALL | Available since PHP 4.0.5.
child_terminate | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
last_modified | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
xbithack | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Prev | Home | Next
dotnet_load | Up | apache_child_terminate


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()

Prev | Home | Next
Apache-specific Functions | Up | apache_get_modules


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

Version | Description
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

&#60;?php
print_r(apache_get_modules());
?&#62;

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
)

Prev | Home | Next
apache_child_terminate | Up | apache_get_version


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

Version | Description
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

&#60;?php
$version = apache_get_version();
echo "$version\n";
?&#62;

The above example will output something similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See Also

phpinfo()

Prev | Home | Next
apache_get_modules | Up | apache_getenv


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.

&#60;?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?&#62;

The above example will output something similar to:

42.24.42.240

See Also

apache_setenv()
getenv()
Superglobals

Prev | Home | Next
apache_get_version | Up | apache_lookup_uri


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

&#60;?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info-&#62;filename)) {
    echo 'file exists!';
}
?&#62;

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!

Prev | Home | Next
apache_getenv | Up | apache_note


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.

Prev | Home | Next
apache_lookup_uri | Up | apache_request_headers


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

&#60;?php
$headers = apache_request_headers();

foreach ($headers as $header =&#62; $value) {
    echo "$header: $value &#60;br /&#62;\n";
}
?&#62;

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.

See Also

apache_response_headers()

Prev | Home | Next
apache_note | Up | apache_reset_timeout


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.

Prev | Home | Next
apache_request_headers | Up | apache_response_headers


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

&#60;?php
print_r(apache_response_headers());
?&#62;

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.

See Also

apache_request_headers()
headers_sent()

Prev | Home | Next
apache_reset_timeout | Up | apache_setenv


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()

&#60;?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?&#62;

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()

Prev | Home | Next
apache_response_headers | Up | ascii2ebcdic


ascii2ebcdic

(PHP 3 >= 3.0.17)

ascii2ebcdic -- Translate string from ASCII to EBCDIC

Description

int ascii2ebcdic ( string ascii_str )

ascii2ebcdic() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the ASCII encoded string ascii_str to its equivalent EBCDIC representation (binary safe), and returns the result.

Parameters

ascii_str

The ASCII string that will be translated.

Return Values

The EBCDIC representation of an ASCII string.

See Also

ebcdic2ascii()

Prev | Home | Next
apache_setenv | Up | 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()

Prev | Home | Next
ascii2ebcdic | Up | getallheaders


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

Version | Description
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.

See Also

apache_response_headers()

Prev | Home | Next
ebcdic2ascii | Up | virtual


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

Version | Description
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.

Prev | Home | Next
getallheaders | Up | Alternative PHP Cache


Advanced PHP debugger

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Constant | Value | Description
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

Prev | Home | Next
apc_store | Up | apd_breakpoint


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);

Prev | Home | Next
Advanced PHP debugger | Up | apd_callstack


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

&#60;?php
print_r(apd_callstack());
?&#62;

Prev | Home | Next
apd_breakpoint | Up | apd_clunk


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

&#60;?php
apd_clunk("Some Warning", "&#60;br/&#62;");
?&#62;

See Also

apd_croak()

Prev | Home | Next
apd_callstack | Up | apd_continue


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

&#60;?php
apd_continue(0);
?&#62;

Prev | Home | Next
apd_clunk | Up | apd_croak


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

&#60;?php
apd_croak("Some Warning","&#60;P&#62;");
?&#62;

See Also

apd_clunk()

Prev | Home | Next
apd_continue | Up | apd_dump_function_table


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

&#60;?php
apd_dump_function_table();
?&#62;

Prev | Home | Next
apd_croak | Up | apd_dump_persistent_resources


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

&#60;?php
print_r(apd_dump_persistent_resources());
?&#62;

See Also

apd_dump_regular()

Prev | Home | Next
apd_dump_function_table | Up | apd_dump_regular_resources


apd_dump_regular_resources

(no version information, might be only in CVS)

apd_dump_regular_resources -- Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Return Values

An array containing the current regular resources.

Examples

Example 1. apd_dump_regular_resources() example

&#60;?php
print_r(apd_dump_regular_resources());
?&#62;

See Also

apd_dump_persistent_resources()

Prev | Home | Next
apd_dump_persistent_resources | Up | apd_echo


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

&#60;?php
apd_echo($i);
?&#62;

Prev | Home | Next
apd_dump_regular_resources | Up | apd_get_active_symbols


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

&#60;?php
apd_echo(apd_get_active_symbols());
?&#62;

Prev | Home | Next
apd_echo | Up | apd_set_pprof_trace


apd_set_pprof_trace

(PECL)

apd_set_pprof_trace -- Starts the session debugging

Description

void apd_set_pprof_trace ( [string dump_directory] )

Starts debugging to 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.

Return Values

No value is returned.

Examples

Example 1. apd_set_pprof_trace() example

&#60;?php
apd_set_pprof_trace();
?&#62;

See Also

apd_set_session_trace()

Prev | Home | Next
apd_get_active_symbols | Up | apd_set_session_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

&#60;?php
apd_set_session_trace(99);
?&#62;

Prev | Home | Next
apd_set_pprof_trace | Up | apd_set_session


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

&#60;?php
apd_set_session(9);
?&#62;

Prev | Home | Next
apd_set_session_trace | Up | apd_set_socket_session_trace


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

&#60;?php
  apd_set_socket_session_trace("127.0.0.1",APD_AF_INET,7112,0);
?&#62;

Prev | Home | Next
apd_set_session | Up | override_function


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

&#60;?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?&#62;

Prev | Home | Next
apd_set_socket_session_trace | Up | rename_function


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

&#60;?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?&#62;

Prev | Home | Next
override_function | Up | Array Functions


Array Functions

PHP Manual
Prev Next

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)

See Also

See also is_array(), explode(),
implode(), split(),
preg_split(), and unset().

Table of Contents
array_change_key_case -- Returns an array with all string keys lowercased or uppercased
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

Prev | Home | Next
rename_function | Up | array_change_key_case


array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case -- Returns an array with all string keys lowercased or uppercased

Description

array array_change_key_case ( array input [, int case] )

array_change_key_case() changes the keys in the input array to be all lowercase or uppercase. The change depends on the last optional case parameter. You can pass two constants there, CASE_UPPER and CASE_LOWER. The default is CASE_LOWER. The function will leave number indices as is.

Example 1. array_change_key_case() example

&#60;?php
$input_array = array("FirSt" =&#62; 1, "SecOnd" =&#62; 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?&#62;

The above example will output:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

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.

Prev | Home | Next
Array Functions | Up | array_chunk


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] )

array_chunk() splits the array into several arrays with size values in them. You may also have an array with less values at the end. You get the arrays as members of a multidimensional array indexed with numbers starting from zero.

By setting the optional preserve_keys parameter to TRUE, you can force PHP to preserve the original keys from the input array. If you specify FALSE new number indices will be used in each resulting array with indices starting from zero. The default is FALSE.

Example 1. array_chunk() example

&#60;?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?&#62;

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
        )

)

Prev | Home | Next
array_change_key_case | Up | array_combine


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 )

Returns an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Returns FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Example 1. A simple array_combine() example

&#60;?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?&#62;

The above example will output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

See also array_merge(),
array_walk(), and
array_values().

Prev | Home | Next
array_chunk | Up | array_count_values


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.

Example 1. array_count_values() example

&#60;?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?&#62;

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

See also count(),
array_unique(),
array_values(), and
count_chars().

Prev | Home | Next
array_combine | Up | array_diff_assoc


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 ...] )

array_diff_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().

Example 1. array_diff_assoc() example

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?&#62;

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above 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.

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.

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_diff_assoc($array1[0], $array2[0]);.

See also array_diff(),
array_intersect(),
and array_intersect_assoc().

Prev | Home | Next
array_count_values | Up | array_diff_key


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 ...] )

array_diff_key() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.

Example 1. array_diff_key() example

&#60;?php
$array1 = array('blue'  =&#62; 1, 'red'  =&#62; 2, 'green'  =&#62; 3, 'purple' =&#62; 4);
$array2 = array('green' =&#62; 5, 'blue' =&#62; 6, 'yellow' =&#62; 7, 'cyan'   =&#62; 8);

var_dump(array_diff_key($array1, $array2));
?&#62;

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

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.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

See also array_diff(),
array_udiff()
array_diff_assoc(),
array_diff_uassoc(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_diff_ukey(),
array_intersect(),
array_intersect_assoc(),
array_intersect_uassoc(),
array_intersect_key() and
array_intersect_ukey().

Prev | Home | Next
array_diff_assoc | Up | array_diff_uassoc


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] )

array_diff_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().

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 argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.

Example 1. array_diff_uassoc() example

&#60;?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a &#62; $b)? 1:-1;
}

$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?&#62;

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above 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.

The equality of 2 indices is checked by the user supplied callback function.

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_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

See also
array_diff(),
array_diff_assoc(),
array_udiff(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_intersect(),
array_intersect_assoc(),
array_uintersect(),
array_uintersect_assoc() and
array_uintersect_uassoc().

Prev | Home | Next
array_diff_key | Up | array_diff_ukey


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] )

array_diff_ukey() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.

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_diff_ukey() example

&#60;?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 &#62; $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  =&#62; 1, 'red'  =&#62; 2, 'green'  =&#62; 3, 'purple' =&#62; 4);
$array2 = array('green' =&#62; 5, 'blue' =&#62; 6, 'yellow' =&#62; 7, 'cyan'   =&#62; 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?&#62;

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

See also array_diff(),
array_udiff()
array_diff_assoc(),
array_diff_uassoc(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_diff_key(),
array_intersect(),
array_intersect_assoc(),
array_intersect_uassoc(),
array_intersect_key() and
array_intersect_ukey().

Prev | Home | Next
array_diff_uassoc | Up | array_diff


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 ...] )

array_diff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved.

Example 1. array_diff() example

&#60;?php
$array1 = array("a" =&#62; "green", "red", "blue", "red");
$array2 = array("b" =&#62; "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?&#62;

Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
    [1] => blue
)

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

Warning

This was broken in PHP 4.0.4!

See also array_diff_assoc(),
array_intersect(), and
array_intersect_assoc().

Prev | Home | Next
array_diff_ukey | Up | array_fill_keys


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 )

array_fill() fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter. Note that num must be a number greater than zero, or PHP will throw a warning.

Example 1. array_fill() example

&#60;?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?&#62;

$a now is:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

See also str_repeat() and range().

Prev | Home | Next
array_fill_keys | Up | array_filter


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] )

array_filter() 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.

Example 1. array_filter() example

&#60;?php
function odd($var)
{
    return($var &#38; 1);
}

function even($var)
{
    return(!($var &#38; 1));
}

$array1 = array("a"=&#62;1, "b"=&#62;2, "c"=&#62;3, "d"=&#62;4, "e"=&#62;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"));
?&#62;

The above example will output:

Odd :
Array
(
    [a] =&#62; 1
    [c] =&#62; 3
    [e] =&#62; 5
)
Even:
Array
(
    [0] =&#62; 6
    [2] =&#62; 8
    [4] =&#62; 10
    [6] =&#62; 12
)

Users may not change the array itself from the callback function. e.g. Add/delete an element, unset the array that array_filter() is applied to. If the array is changed, the behavior of this function is undefined.

If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE. See converting to boolean for more information.

Example 2. array_filter() without callback

&#60;?php

$entry = array(
             0 =&#62; 'foo',
             1 =&#62; false,
             2 =&#62; -1,
             3 =&#62; null,
             4 =&#62; ''
          );

print_r(array_filter($entry));
?&#62;

The above example will output:

Array
(
    [0] => foo
    [2] => -1
)

See also array_map(), array_reduce(), and array_walk().

Prev | Home | Next
array_fill | Up | array_flip


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

&#60;?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?&#62;

Example 2. array_flip() example : collision

&#60;?php
$trans = array("a" =&#62; 1, "b" =&#62; 1, "c" =&#62; 2);
$trans = array_flip($trans);
print_r($trans);
?&#62;

now $trans is:

Array
(
    [1] => b
    [2] => c
)

See also array_values(),
array_keys(), and
array_reverse().

Prev | Home | Next
array_filter | Up | array_intersect_assoc


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

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?&#62;

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().

Prev | Home | Next
array_flip | Up | array_intersect_key


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

&#60;?php
$array1 = array('blue'  =&#62; 1, 'red'  =&#62; 2, 'green'  =&#62; 3, 'purple' =&#62; 4);
$array2 = array('green' =&#62; 5, 'blue' =&#62; 6, 'yellow' =&#62; 7, 'cyan'   =&#62; 8);

var_dump(array_intersect_key($array1, $array2));
?&#62;

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().

Prev | Home | Next
array_intersect_assoc | Up | array_intersect_uassoc


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

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "GREEN", "B" =&#62; "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?&#62;

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().

Prev | Home | Next
array_intersect_key | Up | 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

&#60;?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 &#62; $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  =&#62; 1, 'red'  =&#62; 2, 'green'  =&#62; 3, 'purple' =&#62; 4);
$array2 = array('green' =&#62; 5, 'blue' =&#62; 6, 'yellow' =&#62; 7, 'cyan'   =&#62; 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?&#62;

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().

Prev | Home | Next
array_intersect_uassoc | Up | array_intersect


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

&#60;?php
$array1 = array("a" =&#62; "green", "red", "blue");
$array2 = array("b" =&#62; "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?&#62;

The above example will output:

Array
(
    [a] =&#62; green
    [0] =&#62; 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().

Prev | Home | Next
array_intersect_ukey | Up | array_key_exists


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

&#60;?php
$search_array = array('first' =&#62; 1, 'second' =&#62; 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?&#62;

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.

&#60;?php
$search_array = array('first' =&#62; null, 'second' =&#62; 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?&#62;

See also isset(),
array_keys(), and
in_array().

Prev | Home | Next
array_intersect | Up | array_keys


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

&#60;?php
$array = array(0 =&#62; 100, "color" =&#62; "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" =&#62; array("blue", "red", "green"),
               "size"  =&#62; array("small", "medium", "large"));
print_r(array_keys($array));
?&#62;

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().

Prev | Home | Next
array_key_exists | Up | array_map


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

&#60;?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?&#62;

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example 2. array_map() - using more arrays

&#60;?php
function show_Spanish($n, $m)
{
    return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
    return(array($n =&#62; $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);
?&#62;

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

&#60;?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);
?&#62;

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.

Prev | Home | Next
array_keys | Up | array_merge_recursive


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

&#60;?php
$ar1 = array("color" =&#62; array("favorite" =&#62; "red"), 5);
$ar2 = array(10, "color" =&#62; array("favorite" =&#62; "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?&#62;

The above example will output:

Array
(
    [color] =&#62; Array
        (
            [favorite] =&#62; Array
                (
                    [0] =&#62; red
                    [1] =&#62; green
                )

            [0] =&#62; blue
        )

    [0] =&#62; 5
    [1] =&#62; 10
)

See also array_merge().

Prev | Home | Next
array_map | Up | 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

&#60;?php
$array1 = array("color" =&#62; "red", 2, 4);
$array2 = array("a", "b", "color" =&#62; "green", "shape" =&#62; "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?&#62;

The above example will output:

Array
(
    [color] =&#62; green
    [0] =&#62; 2
    [1] =&#62; 4
    [2] =&#62; a
    [3] =&#62; b
    [shape] =&#62; trapezoid
    [4] =&#62; 4
)

Example 2. Simple array_merge() example

&#60;?php
$array1 = array();
$array2 = array(1 =&#62; "data");
$result = array_merge($array1, $array2);
?&#62;

Don't forget that numeric keys will be renumbered!

Array
(
    [0] =&#62; data
)

If you want to completely preserve the arrays and just want to append them to each other, use the + operator:

&#60;?php
$array1 = array();
$array2 = array(1 =&#62; "data");
$result = $array1 + $array2;
?&#62;

The numeric key will be preserved and thus the association remains.

Array
(
    [1] =&#62; 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

&#60;?php
$beginning = 'foo';
$end = array(1 =&#62; 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?&#62;

The above example will output:

Array
(
    [0] =&#62; foo
    [1] =&#62; bar
)

See also array_merge_recursive(), array_combine() and array operators.

Prev | Home | Next
array_merge_recursive | Up | array_multisort


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

&#60;?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?&#62;

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

&#60;?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);
?&#62;

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().

&#60;?php
$data[] = array('volume' =&#62; 67, 'edition' =&#62; 2);
$data[] = array('volume' =&#62; 86, 'edition' =&#62; 1);
$data[] = array('volume' =&#62; 85, 'edition' =&#62; 6);
$data[] = array('volume' =&#62; 98, 'edition' =&#62; 2);
$data[] = array('volume' =&#62; 86, 'edition' =&#62; 6);
$data[] = array('volume' =&#62; 67, 'edition' =&#62; 7);
?&#62;

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.

&#60;?php
// Obtain a list of columns
foreach ($data as $key =&#62; $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);
?&#62;

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.

&#60;?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);
?&#62;

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

Prev | Home | Next
array_merge | Up | array_pad


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

&#60;?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
?&#62;

See also array_fill() and range().

Prev | Home | Next
array_multisort | Up | array_pop


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

&#60;?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?&#62;

After this, $stack will have only 3 elements:

Array
(
    [0] =&#62; orange
    [1] =&#62; banana
    [2] =&#62; apple
)

and raspberry will be assigned to $fruit.

See also array_push(),
array_shift(), and
array_unshift().

Prev | Home | Next
array_pad | Up | array_product


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:

&#60;?php
$array[] = $var;
?&#62;
repeated for each var.

Returns the new number of elements in the array.

Example 1. array_push() example

&#60;?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?&#62;

The above example will output:

Array
(
    [0] =&#62; orange
    [1] =&#62; banana
    [2] =&#62; apple
    [3] =&#62; 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().

Prev | Home | Next
array_product | Up | array_rand


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

&#60;?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";
?&#62;

See also shuffle().

Prev | Home | Next
array_push | Up | array_reduce


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

&#60;?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);
?&#62;

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().

Prev | Home | Next
array_rand | Up | array_reverse


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

&#60;?php
$input  = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?&#62;

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] =&#62; Array
        (
            [0] =&#62; green
            [1] =&#62; red
        )

    [1] =&#62; 4
    [2] =&#62; php
)
Array
(
    [2] =&#62; Array
        (
            [0] =&#62; green
            [1] =&#62; red
        )

    [1] =&#62; 4
    [0] =&#62; php
)

Note: The second parameter was added in PHP 4.0.3.

See also array_flip().

Prev | Home | Next
array_reduce | Up | array_search


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

&#60;?php
$array = array(0 =&#62; 'blue', 1 =&#62; 'red', 2 =&#62; 'green', 3 =&#62; 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?&#62;

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().

Prev | Home | Next
array_reverse | Up | array_shift


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

&#60;?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?&#62;

This would result in $stack having 3 elements left:

Array
(
    [0] =&#62; banana
    [1] =&#62; apple
    [2] =&#62; raspberry
)

and orange will be assigned to $fruit.

See also array_unshift(),
array_push(), and
array_pop().

Prev | Home | Next
array_search | Up | array_slice


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 reset numeric array keys by default. Since PHP 5.0.2, you can change this behaviour by setting preserve_keys to TRUE.

Example 1. array_slice() examples

&#60;?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));
?&#62;

The above example will output:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

See also array_splice() and unset().

Prev | Home | Next
array_shift | Up | array_splice


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

&#60;?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");
?&#62;

See also array_slice(),
unset(), and
array_merge().

Prev | Home | Next
array_slice | Up | array_sum


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

&#60;?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" =&#62; 1.2, "b" =&#62; 2.3, "c" =&#62; 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?&#62;

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).

Prev | Home | Next
array_splice | Up | array_udiff_assoc


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

&#60;?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this-&#62;priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a-&#62;priv_member === $b-&#62;priv_member) return 0;
        return ($a-&#62;priv_member &#62; $b-&#62;priv_member)? 1:-1;
    }
}

$a = array("0.1" =&#62; new cr(9), "0.5" =&#62; new cr(12), 0 =&#62; new cr(23), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);
$b = array("0.2" =&#62; new cr(9), "0.5" =&#62; new cr(22), 0 =&#62; new cr(3), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?&#62;

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().

Prev | Home | Next
array_sum | Up | array_udiff_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

&#60;?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this-&#62;priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a-&#62;priv_member === $b-&#62;priv_member) return 0;
        return ($a-&#62;priv_member &#62; $b-&#62;priv_member)? 1:-1;
    }

    function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a &#62; $b)? 1:-1;
    }
}
$a = array("0.1" =&#62; new cr(9), "0.5" =&#62; new cr(12), 0 =&#62; new cr(23), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);
$b = array("0.2" =&#62; new cr(9), "0.5" =&#62; new cr(22), 0 =&#62; new cr(3), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?&#62;

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().

Prev | Home | Next
array_udiff_assoc | Up | array_udiff


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

&#60;?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this-&#62;priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a-&#62;priv_member === $b-&#62;priv_member) return 0;
        return ($a-&#62;priv_member &#62; $b-&#62;priv_member)? 1:-1;
    }
}
$a = array("0.1" =&#62; new cr(9), "0.5" =&#62; new cr(12), 0 =&#62; new cr(23), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);
$b = array("0.2" =&#62; new cr(9), "0.5" =&#62; new cr(22), 0 =&#62; new cr(3), 1=&#62; new cr(4), 2 =&#62; new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?&#62;

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().

Prev | Home | Next
array_udiff_uassoc | Up | array_uintersect_assoc


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

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "GREEN", "B" =&#62; "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?&#62;

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().

Prev | Home | Next
array_udiff | Up | 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

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "GREEN", "B" =&#62; "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?&#62;

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().

Prev | Home | Next
array_uintersect_assoc | Up | array_uintersect


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

&#60;?php
$array1 = array("a" =&#62; "green", "b" =&#62; "brown", "c" =&#62; "blue", "red");
$array2 = array("a" =&#62; "GREEN", "B" =&#62; "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?&#62;

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().

Prev | Home | Next
array_uintersect_uassoc | Up | array_unique


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

&#60;?php
$input = array("a" =&#62; "green", "red", "b" =&#62; "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?&#62;

The above example will output:

Array
(
    [a] =&#62; green
    [0] =&#62; red
    [1] =&#62; blue
)

Example 2. array_unique() and types

&#60;?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?&#62;

The above example will output:

array(2) {
  [0] =&#62; int(4)
  [2] =&#62; string(1) "3"
}

Prev | Home | Next
array_uintersect | Up | array_unshift


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

&#60;?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?&#62;

The above example will output:

Array
(
    [0] =&#62; apple
    [1] =&#62; raspberry
    [2] =&#62; orange
    [3] =&#62; banana
)

See also array_shift(),
array_push(), and
array_pop().

Prev | Home | Next
array_unique | Up | array_values


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

&#60;?php
$array = array("size" =&#62; "XL", "color" =&#62; "gold");
print_r(array_values($array));
?&#62;

The above example will output:

Array
(
    [0] =&#62; XL
    [1] =&#62; gold
)

See also array_keys().

Prev | Home | Next
array_unshift | Up | array_walk_recursive


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

&#60;?php
$sweet = array('a' =&#62; 'apple', 'b' =&#62; 'banana');
$fruits = array('sweet' =&#62; $sweet, 'sour' =&#62; 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?&#62;

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.

Prev | Home | Next
array_values | Up | array_walk


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

&#60;?php
$fruits = array("d" =&#62; "lemon", "a" =&#62; "orange", "b" =&#62; "banana", "c" =&#62; "apple");

function test_alter(&#38;$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2&#60;br /&#62;\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?&#62;

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.

Prev | Home | Next
array_walk_recursive | Up | array


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

&#60;?php
$fruits = array (
    "fruits"  =&#62; array("a" =&#62; "orange", "b" =&#62; "banana", "c" =&#62; "apple"),
    "numbers" =&#62; array(1, 2, 3, 4, 5, 6),
    "holes"   =&#62; array("first", 5 =&#62; "second", "third")
);
?&#62;

Example 2. Automatic index with array()

&#60;?php
$array = array(1, 1, 1, 1,  1, 8 =&#62; 1,  4 =&#62; 1, 19, 3 =&#62; 13);
print_r($array);
?&#62;

The above example will output:

Array
(
    [0] =&#62; 1
    [1] =&#62; 1
    [2] =&#62; 1
    [3] =&#62; 13
    [4] =&#62; 1
    [8] =&#62; 1
    [9] =&#62; 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()

&#60;?php
$firstquarter = array(1 =&#62; 'January', 'February', 'March');
print_r($firstquarter);
?&#62;

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

&#60;?php

$foo = array('bar' =&#62; 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?&#62;

See also array_pad(),
list(),
count(),
foreach, and
range().

Prev | Home | Next
array_walk | Up | arsort


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

&#60;?php
$fruits = array("d" =&#62; "lemon", "a" =&#62; "orange", "b" =&#62; "banana", "c" =&#62; "apple");
arsort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "$key = $val\n";
}
?&#62;

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().

Prev | Home | Next
array | Up | asort


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

&#60;?php
$fruits = array("d" =&#62; "lemon", "a" =&#62; "orange", "b" =&#62; "banana", "c" =&#62; "apple");
asort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "$key = $val\n";
}
?&#62;

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().

Prev | Home | Next
arsort | Up | compact


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

&#60;?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?&#62;

The above example will output:

Array
(
    [event] =&#62; SIGGRAPH
    [city] =&#62; San Francisco
    [state] =&#62; CA
)

See also extract().

Prev | Home | Next
asort | Up | count


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

&#60;?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
?&#62;

Example 2. Recursive count() example (PHP >= 4.2.0)

&#60;?php
$food = array('fruits' =&#62; array('orange', 'banana', 'apple'),
              'veggie' =&#62; array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?&#62;

See also is_array(),
isset(), and
strlen().

Prev | Home | Next
compact | Up | current


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

&#60;?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';
?&#62;

See also end(), key(),
next(), prev(),
reset(), and each().

Prev | Home | Next
count | Up | 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

&#60;?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?&#62;

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

&#60;?php
$foo = array("Robert" =&#62; "Bob", "Seppo" =&#62; "Sepi");
$bar = each($foo);
print_r($bar);
?&#62;

$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()

&#60;?php
$fruit = array('a' =&#62; 'apple', 'b' =&#62; 'banana', 'c' =&#62; 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key =&#62; $val\n";
}
?&#62;

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.

Prev | Home | Next
current | Up | end


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

&#60;?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?&#62;

See also current(),
each(),
prev(),
next() and
reset().

Prev | Home | Next
each | Up | extract


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

&#60;?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = "large";
$var_array = array("color" =&#62; "blue",
                   "size"  =&#62; "medium",
                   "shape" =&#62; "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?&#62;

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().

Prev | Home | Next
end | Up | in_array


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

&#60;?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?&#62;

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

&#60;?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";
}
?&#62;

The above example will output:

1.13 found with strict check

Example 3. in_array() with an array as needle

&#60;?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";
}
?&#62;

The above example will output:

'ph' was found
  'o' was found

See also array_search(),
array_key_exists(), and
isset().

Prev | Home | Next
extract | Up | key


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

&#60;?php
$array = array(
    'fruit1' =&#62; 'apple',
    'fruit2' =&#62; 'orange',
    'fruit3' =&#62; 'grape',
    'fruit4' =&#62; 'apple',
    'fruit5' =&#62; 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'&#60;br /&#62;';
    }
    next($array);
}
?&#62;

See also current() and next().

Prev | Home | Next
in_array | Up | krsort


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

&#60;?php
$fruits = array("d"=&#62;"lemon", "a"=&#62;"orange", "b"=&#62;"banana", "c"=&#62;"apple");
krsort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "$key = $val\n";
}
?&#62;

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().

Prev | Home | Next
key | Up | ksort


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

&#60;?php
$fruits = array("d"=&#62;"lemon", "a"=&#62;"orange", "b"=&#62;"banana", "c"=&#62;"apple");
ksort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "$key = $val\n";
}
?&#62;

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.

Prev | Home | Next
krsort | Up | list


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

&#60;?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";

?&#62;

Example 2. An example use of list()

&#60;table&#62;
 &#60;tr&#62;
  &#60;th&#62;Employee name&#60;/th&#62;
  &#60;th&#62;Salary&#60;/th&#62;
 &#60;/tr&#62;

&#60;?php

$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " &#60;tr&#62;\n" .
          "  &#60;td&#62;&#60;a href=\"info.php?id=$id\"&#62;$name&#60;/a&#62;&#60;/td&#62;\n" .
          "  &#60;td&#62;$salary&#60;/td&#62;\n" .
          " &#60;/tr&#62;\n";
}

?&#62;

&#60;/table&#62;

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

&#60;?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?&#62;

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().

Prev | Home | Next
ksort | Up | natcasesort


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

&#60;?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);
?&#62;

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().

Prev | Home | Next
list | Up | natsort


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

&#60;?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);
?&#62;

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().

Prev | Home | Next
natcasesort | Up | next


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

&#60;?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';
?&#62;

See also
current(), end(),
prev(), reset(),
and each().

Prev | Home | Next
natsort | Up | pos


pos

(PHP 3, PHP 4, PHP 5)

pos -- Alias of current()

Description

This function is an alias of: current()

Prev | Home | Next
next | Up | prev


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

&#60;?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';
?&#62;

See also current(), end(),
next(), reset(),
and each().

Prev | Home | Next
pos | Up | range


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

&#60;?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;
}
?&#62;

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.

Prev | Home | Next
prev | Up | reset


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

&#60;?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "&#60;br /&#62;\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "&#60;br /&#62;\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "&#60;br /&#62;\n"; // "step one"

?&#62;

See also current(),
each(), end(),
next(), and prev().

Prev | Home | Next
range | Up | rsort


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

&#60;?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "$key = $val\n";
}
?&#62;

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().

Prev | Home | Next
reset | Up | shuffle


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

&#60;?php
$numbers = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?&#62;

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().

Prev | Home | Next
rsort | Up | sizeof


sizeof

(PHP 3, PHP 4, PHP 5)

sizeof -- Alias of count()

Description

This function is an alias of: count().

Prev | Home | Next
shuffle | Up | sort


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

&#60;?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key =&#62; $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?&#62;

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().

Prev | Home | Next
sizeof | Up | uasort


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().

Prev | Home | Next
sort | Up | uksort


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

&#60;?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" =&#62; 1, "the Earth" =&#62; 2, "an apple" =&#62; 3, "a banana" =&#62; 4);

uksort($a, "cmp");

foreach ($a as $key =&#62; $value) {
    echo "$key: $value\n";
}
?&#62;

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().

Prev | Home | Next
uasort | Up | usort


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

&#60;?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a &#60; $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key =&#62; $value) {
    echo "$key: $value\n";
}
?&#62;

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

&#60;?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";
}
?&#62;

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

&#60;?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this-&#62;name = $name;
    }

    /* This is the static comparing function: */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a-&#62;name);
        $bl = strtolower($b-&#62;name);
        if ($al == $bl) {
            return 0;
        }
        return ($al &#62; $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-&#62;name . "\n";
}
?&#62;

The above example will output:

b
c
d

See also uasort(),
uksort(), sort(),
asort(),
arsort(),ksort(),
natsort(), and rsort().

Prev | Home | Next
uksort | Up | Aspell functions [deprecated]


Aspell functions [deprecated]

PHP Manual
Prev Next

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]

Prev | Home | Next
usort | Up | aspell_check_raw


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

&#60;?php

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?&#62;

See Also

aspell_check()

Prev | Home | Next
Aspell functions [deprecated] | Up | 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

&#60;?php

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?&#62;

See Also

aspell_check_raw()

Prev | Home | Next
aspell_check_raw | Up | aspell_new


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

&#60;?php
$aspell_link = aspell_new("english");
?&#62;

Prev | Home | Next
aspell_check | Up | aspell_suggest


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

&#60;?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&#60;br /&#62;\n";
    }
}

?&#62;

Prev | Home | Next
aspell_new | Up | BCMath Arbitrary Precision Mathematics Functions


BCMath Arbitrary Precision Mathematics Functions

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
bcmath.scale | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Prev | Home | Next
aspell_suggest | Up | bcadd


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

&#60;?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?&#62;

See Also

bcsub()

Prev | Home | Next
BCMath Arbitrary Precision Mathematics Functions | Up | bccomp


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

&#60;?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?&#62;

Prev | Home | Next
bcadd | Up | bcdiv


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

&#60;?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?&#62;

See Also

bcmul()

Prev | Home | Next
bccomp | Up | bcmod


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

&#60;?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?&#62;

See Also

bcdiv()

Prev | Home | Next
bcdiv | Up | bcmul


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

&#60;?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?&#62;

See Also

bcdiv()

Prev | Home | Next
bcmod | Up | bcpow


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

&#60;?php

echo bcpow('4.2', '3', 2); // 74.08

?&#62;

See Also

bcpowmod()
bcsqrt()

Prev | Home | Next
bcmul | Up | bcpowmod


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.

&#60;?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?&#62;

See Also

bcpow()
bcmod()

Prev | Home | Next
bcpow | Up | bcscale


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

&#60;?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

?&#62;

Prev | Home | Next
bcpowmod | Up | bcsqrt


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

&#60;?php

echo bcsqrt('2', 3); // 1.414

?&#62;

See Also

bcpow()

Prev | Home | Next
bcscale | Up | bcsub


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

&#60;?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?&#62;

See Also

bcadd()

Prev | Home | Next
bcsqrt | Up | PHP bytecode Compiler


PHP bytecode Compiler

PHP Manual
Prev Next

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. for the compression to work

  • To install on PHP 4.3 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, 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

Prev | Home | Next
bcsub | Up | bcompiler_load_exe


bcompiler_load_exe

(PECL)

bcompiler_load_exe -- Reads and creates classes from a bcompiler exe file

Description

bool bcompiler_load_exe ( string filename )

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.

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Example 1. bcompiler_load() example

&#60;?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?&#62;

Prev | Home | Next
PHP bytecode Compiler | Up | bcompiler_load


bcompiler_load

(PECL)

bcompiler_load -- Reads and creates classes from a bz compressed file

Description

bool bcompiler_load ( string filename )

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.

Reads data from a bzcompressed file and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.

Example 1. bcompiler_load() example

&#60;?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?&#62;

Prev | Home | Next
bcompiler_load_exe | Up | bcompiler_parse_class


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 )

Note: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.

Reads the bytecodes of a class and calls back to a user function.

Example 1. bcompiler_parse_class() example

&#60;?php

function readByteCodes($data) {
  print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?&#62;

Prev | Home | Next
bcompiler_load | Up | bcompiler_read


bcompiler_read

(PECL)

bcompiler_read -- Reads and creates classes from a filehandle

Description

bool bcompiler_read ( resource filehandle )

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.

Reads data from a open file handle and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.

Example 1. bcompiler_read() example

&#60;?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?&#62;

Prev | Home | Next
bcompiler_parse_class | Up | bcompiler_write_class


bcompiler_write_class

(PECL)

bcompiler_write_class -- Writes an defined class as bytecodes

Description

bool bcompiler_write_class ( resource filehandle, string className [, string extends] )

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.

This reads the bytecodes from PHP for an existing class, and writes them to the open file handle, It does not perform dependency checking, so make sure you write the classes in an order that will not result in an 'undefined class' occurring when you load it.

Example 1. bcompiler_write_class() example

&#60;?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);

?&#62;

See also bcompiler_write_header(), and bcompiler_write_footer().

Prev | Home | Next
bcompiler_read | Up | bcompiler_write_constant


bcompiler_write_constant

(PECL)

bcompiler_write_constant -- Writes a defined constant as bytecodes

Description

bool bcompiler_write_constant ( resource filehandle, string constantName )

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.

This function reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Example 1. bcompiler_write_constant() example

&#60;?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);

?&#62;

See also bcompiler_write_header(), and bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_class | Up | bcompiler_write_exe_footer


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 )

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.

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

The startpos is the file position at which the Bytecodes start, and can be obtained using ftell($fh).

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Example 1. bcompiler_write_footer() example

&#60;?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);
?&#62;

See also bcompiler_write_header(),
bcompiler_write_class(), and
bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_constant | Up | bcompiler_write_file


bcompiler_write_file

(PECL)

bcompiler_write_file -- Writes a php source file as bytecodes

Description

bool bcompiler_write_file ( resource filehandle, string filename )

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.

This function complies specified source file into bytecodes, and writes them to the open file handle.

Example 1. bcompiler_write_file() example

&#60;?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";
*/
?&#62;

See also bcompiler_write_header(), and bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_exe_footer | Up | bcompiler_write_footer


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 )

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.

Writes the single character \x00 to indicate End of compiled data.

Example 1. bcompiler_write_footer() example

&#60;?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);

?&#62;

See also bcompiler_write_header(), and bcompiler_write_header().

Prev | Home | Next
bcompiler_write_file | Up | bcompiler_write_function


bcompiler_write_function

(PECL)

bcompiler_write_function -- Writes an defined function as bytecodes

Description

bool bcompiler_write_function ( resource filehandle, string functionName )

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.

This 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).

Example 1. bcompiler_write_function() example

&#60;?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);

?&#62;

See also bcompiler_write_header(), and bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_footer | Up | bcompiler_write_functions_from_file


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 )

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.

This function searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle. Always remember to include/require the file you intend to compile.

Example 1. bcompiler_write_functions_from_file() example

&#60;?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);

?&#62;

See also bcompiler_write_header(), and bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_function | Up | bcompiler_write_header


bcompiler_write_header

(PECL)

bcompiler_write_header -- Writes the bcompiler header

Description

bool bcompiler_write_header ( resource filehandle [, string write_ver] )

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.

Writes the header part of a bcompiler file. Optional second parameter can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Example 1. bcompiler_write_header() example

&#60;?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?&#62;

See also bcompiler_write_file(),
bcompiler_write_class(),
bcompiler_write_function(), and
bcompiler_write_footer().

Prev | Home | Next
bcompiler_write_functions_from_file | Up | Bzip2 Compression Functions


Bzip2 Compression Functions

PHP Manual
Prev Next

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

&#60;?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);

?&#62;
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

Prev | Home | Next
bcompiler_write_header | Up | bzclose


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()

Prev | Home | Next
Bzip2 Compression Functions | Up | bzcompress


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

&#60;?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?&#62;

See Also

bzdecompress()

Prev | Home | Next
bzclose | Up | 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

&#60;?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n&#60;br /&#62;\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n&#60;br /&#62;\n";
?&#62;

See Also

bzcompress()

Prev | Home | Next
bzcompress | Up | bzerrno


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.

See Also

bzerror()
bzerrstr()

Prev | Home | Next
bzdecompress | Up | bzerror


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

&#60;?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?&#62;

See Also

bzerrno()
bzerrstr()

Prev | Home | Next
bzerrno | Up | bzerrstr


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.

See Also

bzerrno()
bzerror()

Prev | Home | Next
bzerror | Up | bzflush


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.

See Also

bzread()
bzwrite()

Prev | Home | Next
bzerrstr | Up | bzopen


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

&#60;?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?&#62;

See Also

bzclose()

Prev | Home | Next
bzflush | Up | bzread


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

&#60;?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: &#60;br /&#62;\n";
echo $decompressed_file;

?&#62;

See Also

bzwrite()
feof()
bzopen()

Prev | Home | Next
bzopen | Up | bzwrite


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

&#60;?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?&#62;

See Also

bzread()
bzopen()

Prev | Home | Next
bzread | Up | Calendar Functions


Calendar Functions

PHP Manual
Prev Next

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.boogle.com/info/cal-overview.html. 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

Prev | Home | Next
bzwrite | Up | cal_days_in_month


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.

Example 1. cal_days_in_month() example

&#60;?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?&#62;

See also jdtounix().

Prev | Home | Next
Calendar Functions | Up | cal_from_jd


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.

Example 1. cal_from_jd() example

&#60;?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?&#62;

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
)

See also cal_to_jd().

Prev | Home | Next
cal_days_in_month | Up | cal_info


cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( [int calendar] )

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar

  • 1 or CAL_JULIAN - Julian Calendar

  • 2 or CAL_JEWISH - Jewish Calendar

  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array. This functionality is available beginning with PHP 5.

Example 1. cal_info() example

&#60;?php
$info = cal_info(0);
print_r($info);
?&#62;

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
)

Prev | Home | Next
cal_from_jd | Up | cal_to_jd


cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

See also cal_from_jd().

Prev | Home | Next
cal_info | Up | easter_date


easter_date

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_date -- Get Unix timestamp for midnight on Easter of a given year

Description

int easter_date ( [int year] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.

Example 1. easter_date() example

&#60;?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

?&#62;

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>)

See easter_days() for calculating Easter before 1970 or after 2037.

Prev | Home | Next
cal_to_jd | Up | 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.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.

The method parameter was also introduced in PHP 4.3.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

Example 1. easter_days() example

&#60;?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

?&#62;

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

See also easter_date().

Prev | Home | Next
easter_date | Up | FrenchToJD


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.

Prev | Home | Next
easter_days | Up | GregorianToJD


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.

Example 1. Calendar functions

&#60;?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?&#62;

Prev | Home | Next
FrenchToJD | Up | JDDayOfWeek


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.

Table 1. Calendar week modes

Mode | Meaning
0 (Default) | Returns the day number as an int (0=Sunday, 1=Monday, etc)
1 | Returns string containing the day of week (English-Gregorian)
2 | Returns a string containing the abbreviated day of week (English-Gregorian)

Prev | Home | Next
GregorianToJD | Up | JDMonthName


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

Mode | Meaning | Values
0 | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1 | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December
2 | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 | Julian | January, February, March, April, May, June, July, August, September, October, November, December
4 | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5 | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

Prev | Home | Next
JDDayOfWeek | Up | JDToFrench


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.

Prev | Home | Next
JDMonthName | Up | JDToGregorian


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".

Prev | Home | Next
JDToFrench | Up | jdtojewish


jdtojewish

(PHP 3, PHP 4, PHP 5)

jdtojewish -- Converts a Julian day count to a Jewish calendar date

Description

string jdtojewish ( int juliandaycount [, bool hebrew [, int fl]] )

Converts a Julian Day Count to the Jewish Calendar.

The optional hebrew and fl parameters became available in PHP 5.0.0

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format. The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

Example 1. jdtojewish() Example

&#60;?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH);
?&#62;

Prev | Home | Next
JDToGregorian | Up | JDToJulian


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".

Prev | Home | Next
jdtojewish | Up | jdtounix


jdtounix

(PHP 4, PHP 5)

jdtounix -- Convert Julian Day to Unix timestamp

Description

int jdtounix ( int jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

See also unixtojd().

Prev | Home | Next
JDToJulian | Up | JewishToJD


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.

Prev | Home | Next
jdtounix | Up | JulianToJD


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.

Prev | Home | Next
JewishToJD | Up | unixtojd


unixtojd

(PHP 4, PHP 5)

unixtojd -- Convert Unix timestamp to Julian Day

Description

int unixtojd ( [int timestamp] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

See also jdtounix().

Prev | Home | Next
JulianToJD | Up | CCVS API Functions [deprecated]


CCVS API Functions [deprecated]

PHP Manual
Prev Next

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

Prev | Home | Next
unixtojd | Up | ccvs_add


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.

Prev | Home | Next
CCVS API Functions [deprecated] | Up | ccvs_auth


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.

Prev | Home | Next
ccvs_add | Up | ccvs_command


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.

Prev | Home | Next
ccvs_auth | Up | ccvs_count


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.

Prev | Home | Next
ccvs_command | Up | ccvs_delete


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.

Prev | Home | Next
ccvs_count | Up | ccvs_done


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.

Prev | Home | Next
ccvs_delete | Up | ccvs_init


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.

Prev | Home | Next
ccvs_done | Up | ccvs_lookup


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.

Prev | Home | Next
ccvs_init | Up | ccvs_new


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.

Prev | Home | Next
ccvs_lookup | Up | ccvs_report


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.

Prev | Home | Next
ccvs_new | Up | ccvs_return


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.

Prev | Home | Next
ccvs_report | Up | ccvs_reverse


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.

Prev | Home | Next
ccvs_return | Up | ccvs_sale


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.

Prev | Home | Next
ccvs_reverse | Up | ccvs_status


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.

Prev | Home | Next
ccvs_sale | Up | ccvs_textvalue


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.

Prev | Home | Next
ccvs_status | Up | ccvs_void


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.

Prev | Home | Next
ccvs_textvalue | Up | Class/Object Functions


Classkit Functions

PHP Manual
Prev Next

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.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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

Prev | Home | Next
property_exists | Up | classkit_import


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

&#60;?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?&#62;
&#60;?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e-&#62;foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e-&#62;foo();

?&#62;

The above example will output:

foo!
bar!

See Also

classkit_method_add()
classkit_method_copy()

Prev | Home | Next
Classkit Functions | Up | classkit_method_add


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

&#60;?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-&#62;add(12, 4);
?&#62;

The above example will output:

16

See Also

classkit_method_copy()
classkit_method_redefine()
classkit_method_remove()
classkit_method_rename()
create_function()

Prev | Home | Next
classkit_import | Up | classkit_method_copy


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

&#60;?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();
?&#62;

The above example will output:

foo!

See Also

classkit_method_add()
classkit_method_redefine()
classkit_method_remove()
classkit_method_rename()

Prev | Home | Next
classkit_method_add | Up | classkit_method_redefine


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

&#60;?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e-&#62;foo();

// Redefine the 'foo' method
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e-&#62;foo();
?&#62;

The above example will output:

Before: foo!
After: bar!

See Also

classkit_method_add()
classkit_method_copy()
classkit_method_remove()
classkit_method_rename()

Prev | Home | Next
classkit_method_copy | Up | classkit_method_remove


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

&#60;?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'));

?&#62;

The above example will output:

bar

See Also

classkit_method_add()
classkit_method_copy()
classkit_method_redefine()
classkit_method_rename()

Prev | Home | Next
classkit_method_redefine | Up | classkit_method_rename


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

&#60;?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();
?&#62;

The above example will output:

foo!

See Also

classkit_method_add()
classkit_method_copy()
classkit_method_redefine()
classkit_method_remove()

Prev | Home | Next
classkit_method_remove | Up | ClibPDF Functions


Class/Object Functions

PHP Manual
Prev Next

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

&#60;?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable($edible, $color="green")
    {
        $this-&#62;edible = $edible;
        $this-&#62;color = $color;
    }

    function is_edible()
    {
        return $this-&#62;edible;
    }

    function what_color()
    {
        return $this-&#62;color;
    }

} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach()
    {
        $this-&#62;Vegetable(true, "green");
    }

    function cook_it()
    {
        $this-&#62;cooked = true;
    }

    function is_cooked()
    {
        return $this-&#62;cooked;
    }

} // end of class Spinach

?&#62;

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

&#60;pre&#62;
&#60;?php

include "classes.inc";

// utility functions

function print_vars($obj)
{
    foreach (get_object_vars($obj) as $prop =&#62; $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");
?&#62;
&#60;/pre&#62;

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

Prev | Home | Next
ccvs_void | Up | call_user_method_array


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.

See Also

call_user_func_array()
call_user_func()

Prev | Home | Next
Class/Object Functions | Up | call_user_method


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.

See Also

call_user_func_array()
call_user_func()

Prev | Home | Next
call_user_method_array | Up | class_exists


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

Version | Description
5.0.0 | The autoload was added.

Examples

Example 1. class_exists() example

&#60;?php
// Check the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?&#62;

Example 2. autoload parameter example

&#60;?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();
}

?&#62;

See Also

interface_exists()
get_declared_classes()

Prev | Home | Next
call_user_method | Up | get_class_methods


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 of 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

Version | Description
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

&#60;?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";
}

?&#62;

The above example will output:

myclass
myfunc1
myfunc2

See Also

get_class()
get_class_vars()
get_object_vars()

Prev | Home | Next
class_exists | Up | get_class_vars


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

Version | Description
Prior to 4.2.0 | Uninitialized class variables will not be reported by get_class_vars()

Examples

Example 1. get_class_vars() example

&#60;?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-&#62;var1 = "foo";
        $this-&#62;var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name =&#62; $value) {
    echo "$name : $value\n";
}

?&#62;

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

See Also

get_class_methods()
get_object_vars()

Prev | Home | Next
get_class_methods | Up | get_class


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

Version | Description
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()

&#60;?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-&#62;name();

?&#62;

The above example will output:

Its name is foo
My name is foo

See Also

get_parent_class()
gettype()
is_subclass_of()

Prev | Home | Next
get_class_vars | Up | get_declared_classes


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 libraries you have compiled into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

Examples

Example 1. get_declared_classes() example

&#60;?php
print_r(get_declared_classes());
?&#62;

The above example will output something similar to:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

See Also

class_exists()
get_declared_interfaces()

Prev | Home | Next
get_class | Up | get_declared_interfaces


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

&#60;?php
print_r(get_declared_interfaces());
?&#62;

The above example will output something similar to:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

See Also

get_declared_classes()

Prev | Home | Next
get_declared_classes | Up | get_object_vars


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

Version | Description
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()

&#60;?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y)
    {
        $this-&#62;x = $x;
        $this-&#62;y = $y;
    }

    function setLabel($label)
    {
        $this-&#62;label = $label;
    }

    function getPoint()
    {
        return array("x" =&#62; $this-&#62;x,
                     "y" =&#62; $this-&#62;y,
                     "label" =&#62; $this-&#62;label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1-&#62;setLabel("point #1");
print_r(get_object_vars($p1));

?&#62;

The above example will output:

Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

See Also

get_class_methods()
get_class_vars()

Prev | Home | Next
get_declared_interfaces | Up | get_parent_class


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

Version | Description
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()

&#60;?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();

?&#62;

The above example will output:

I'm dad's son
I'm dad's son too

See Also

get_class()
is_subclass_of()

Prev | Home | Next
get_object_vars | Up | interface_exists


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

&#60;?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?&#62;

See Also

class_exists()

Prev | Home | Next
get_parent_class | Up | is_a


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

&#60;?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";
}
?&#62;

Example 2. Using the instanceof operator in PHP 5

&#60;?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?&#62;

See Also

get_class()
get_parent_class()
is_subclass_of()

Prev | Home | Next
interface_exists | Up | is_subclass_of


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

Version | Description
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

&#60;?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";
}
?&#62;

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

See Also

get_class()
get_parent_class()
is_a()

Prev | Home | Next
is_a | Up | method_exists


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

&#60;?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?&#62;

The above example will output:

bool(true)

See Also

function_exists()
is_callable()

Prev | Home | Next
is_subclass_of | Up | property_exists


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

&#60;?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();

?&#62;

See Also

method_exists()

Prev | Home | Next
method_exists | Up | Classkit Functions


COM and .Net (Windows)

PHP Manual
Prev Next

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

&#60;?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject-&#62;Next()) {
   echo $obj-&#62;Name . "&#60;br /&#62;";
}
?&#62;

Example 3. foreach in PHP 5

&#60;?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj-&#62;Name . "&#60;br /&#62;";
}
?&#62;

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

Name | Default | Changeable | Changelog
com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

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 57. 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

Prev | Home | Next
cpdf_translate | Up | COM


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 key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage

Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky 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)

&#60;?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word-&#62;Version}\n";

//bring it to front
$word-&#62;Visible = 1;

//open an empty document
$word-&#62;Documents-&#62;Add();

//do some weird stuff
$word-&#62;Selection-&#62;TypeText("This is a test...");
$word-&#62;Documents[1]-&#62;SaveAs("Useless test.doc");

//closing word
$word-&#62;Quit();

//free the object
$word = null;
?&#62;

Example 2. COM example (2)

&#60;?php

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn-&#62;Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn-&#62;Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs-&#62;Fields-&#62;Count();
echo $num_columns . "\n";

for ($i=0; $i &#60; $num_columns; $i++) {
    $fld[$i] = $rs-&#62;Fields($i);
}

$rowcount = 0;
while (!$rs-&#62;EOF) {
    for ($i=0; $i &#60; $num_columns; $i++) {
        echo $fld[$i]-&#62;value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs-&#62;MoveNext();
}

$rs-&#62;Close();
$conn-&#62;Close();

$rs = null;
$conn = null;

?&#62;

Prev | Home | Next
COM and .Net (Windows) | Up | DOTNET


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

&#60;?php
  $stack = new DOTNET("mscorlib", "System.Collections.Stack");
  $stack-&#62;Push(".Net");
  $stack-&#62;Push("Hello ");
  echo $stack-&#62;Pop() . $stack-&#62;Pop();
?&#62;

Note: You need to install the .Net runtime on your web server to take advantage of this feature.

Prev | Home | Next
COM | Up | VARIANT


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

&#60;?php
$v = new VARIANT(42);
print "The type is " . $v-&#62;type . "&#60;br/&#62;";
print "The value is " . $v-&#62;value . "&#60;br/&#62;";
?&#62;

Example 2. Variant example, PHP 5 style

&#60;?php
$v = new VARIANT(42);
print "The type is " . variant_get_type($v) . "&#60;br/&#62;";
print "The value is " . $v . "&#60;br/&#62;";
?&#62;

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().

Prev | Home | Next
DOTNET | Up | com_addref


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.

Prev | Home | Next
VARIANT | Up | com_create_guid


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.

Prev | Home | Next
com_addref | Up | com_event_sink


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

&#60;?php
class IEEventSinker {
  var $terminated = false;

  function ProgressChange($progress, $progressmax) {
    echo "Download progress: $progress / $progressmax\n";
  }

  function DocumentComplete(&#38;$dom, $url) {
    echo "Document $url complete\n";
  }

  function OnQuit() {
    echo "Quit!\n";
    $this-&#62;terminated = true;
  }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the &#38; for PHP 5!
$sink =&#38; new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie-&#62;Visible = true;
$ie-&#62;Navigate("http://www.php.net");
while(!$sink-&#62;terminated) {
  com_message_pump(4000);
}
$ie = null;
?&#62;

See also com_print_typeinfo(), com_message_pump().

Prev | Home | Next
com_create_guid | Up | com_get_active_object


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.

Prev | Home | Next
com_event_sink | Up | com_get


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

&#60;?php
// do this
$var = $obj-&#62;property;
// instead of this:
$var = com_get($obj, 'property');
?&#62;

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.

Prev | Home | Next
com_get_active_object | Up | com_invoke


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

&#60;?php
// do this
$val = $obj-&#62;method($one, $two);
// instead of this:
$val = com_invoke($obj, 'method', $one, $two);
?&#62;

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.

Prev | Home | Next
com_get | Up | com_isenum


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.

Prev | Home | Next
com_invoke | Up | com_load_typelib


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.

Prev | Home | Next
com_isenum | Up | com_load


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

&#60;?php
// do this
$obj = new COM($module);
// instead of this:
$obj = com_load($module);
?&#62;

Note: This function does not exist in PHP 5; use the COM class instead.

Prev | Home | Next
com_load_typelib | Up | com_message_pump


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.

Prev | Home | Next
com_load | Up | com_print_typeinfo


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().

Prev | Home | Next
com_message_pump | Up | com_propget


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.

Prev | Home | Next
com_print_typeinfo | Up | com_propput


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.

Prev | Home | Next
com_propget | Up | com_propset


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.

Prev | Home | Next
com_propput | Up | com_release


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.

Prev | Home | Next
com_propset | Up | com_set


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

&#60;?php
// do this
$obj-&#62;property = $value;
// instead of this:
com_set($obj, 'property', $value);
?&#62;

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.

Prev | Home | Next
com_release | Up | variant_abs


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.

Prev | Home | Next
com_set | Up | variant_add


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

If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

See also variant_sub().

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.

Prev | Home | Next
variant_abs | Up | variant_and


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 is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | FALSE
TRUE | NULL | NULL
FALSE | TRUE | FALSE
FALSE | FALSE | FALSE
FALSE | NULL | FALSE
NULL | TRUE | NULL
NULL | FALSE | FALSE
NULL | NULL | NULL

See also variant_or().

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.

Prev | Home | Next
variant_add | Up | variant_cast


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().

Prev | Home | Next
variant_and | Up | variant_cat


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.

Prev | Home | Next
variant_cast | Up | variant_cmp


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

value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are NULL

This function will only compare scalar values, not arrays or variant records.

lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:

Table 2. Variant Comparision Flags

value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

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.

Prev | Home | Next
variant_cat | Up | variant_date_from_timestamp


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().

Prev | Home | Next
variant_cmp | Up | variant_date_to_timestamp


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().

Prev | Home | Next
variant_date_from_timestamp | Up | variant_div


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

If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

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.

Prev | Home | Next
variant_date_to_timestamp | Up | variant_eqv


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.

Prev | Home | Next
variant_div | Up | variant_fix


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.

Prev | Home | Next
variant_eqv | Up | variant_get_type


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.

Prev | Home | Next
variant_fix | Up | variant_idiv


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

If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

See also variant_div().

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.

Prev | Home | Next
variant_get_type | Up | variant_imp


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 is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | TRUE
FALSE | NULL | TRUE
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

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.

Prev | Home | Next
variant_idiv | Up | variant_int


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.

Prev | Home | Next
variant_imp | Up | variant_mod


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.

Prev | Home | Next
variant_int | Up | variant_mul


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

If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Boolean values are converted to -1 for FALSE and 0 for TRUE.

See also variant_div(), variant_idiv().

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.

Prev | Home | Next
variant_mod | Up | variant_neg


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.

Prev | Home | Next
variant_mul | Up | variant_not


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.

Prev | Home | Next
variant_neg | Up | variant_or


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 is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
FALSE | NULL | NULL
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

See also variant_and(), variant_xor().

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.

Prev | Home | Next
variant_not | Up | variant_pow


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.

Prev | Home | Next
variant_or | Up | variant_round


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.

Prev | Home | Next
variant_pow | Up | variant_set_type


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().

Prev | Home | Next
variant_round | Up | variant_set


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.

Prev | Home | Next
variant_set_type | Up | variant_sub


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

If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

See also variant_add().

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.

Prev | Home | Next
variant_set | Up | variant_xor


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 is | If right is | then the result is
TRUE | TRUE | FALSE
TRUE | FALSE | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
NULL | NULL | NULL

See also variant_and(), variant_or().

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.

Prev | Home | Next
variant_sub | Up | Crack Functions


ClibPDF Functions

PHP Manual
Prev Next

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.

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

&#60;?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);
?&#62;

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

&#60;?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-- &#62; 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 &#60; 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 &#60; 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);
?&#62;

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

Prev | Home | Next
classkit_method_rename | Up | cpdf_add_annotation


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.

Prev | Home | Next
ClibPDF Functions | Up | cpdf_add_outline


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

&#60;?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);
?&#62;

Prev | Home | Next
cpdf_add_annotation | Up | cpdf_arc


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()

Prev | Home | Next
cpdf_add_outline | Up | cpdf_begin_text


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

&#60;?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?&#62;

See Also

cpdf_end_text()

Prev | Home | Next
cpdf_arc | Up | cpdf_circle


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()

Prev | Home | Next
cpdf_begin_text | Up | cpdf_clip


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.

Prev | Home | Next
cpdf_circle | Up | cpdf_close


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()

Prev | Home | Next
cpdf_clip | Up | cpdf_closepath_fill_stroke


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.

See Also

cpdf_closepath()
cpdf_stroke()
cpdf_fill()
cpdf_setgray_fill()
cpdf_setgray()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor()

Prev | Home | Next
cpdf_close | Up | cpdf_closepath_stroke


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.

See Also

cpdf_closepath()
cpdf_stroke()

Prev | Home | Next
cpdf_closepath_fill_stroke | Up | cpdf_closepath


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.

Prev | Home | Next
cpdf_closepath_stroke | Up | cpdf_continue_text


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.

See Also

cpdf_show_xy()
cpdf_text()
cpdf_set_leading()
cpdf_set_text_pos()

Prev | Home | Next
cpdf_closepath | Up | cpdf_curveto


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.

See Also

cpdf_moveto()
cpdf_rmoveto()
cpdf_rlineto()
cpdf_lineto()

Prev | Home | Next
cpdf_continue_text | Up | cpdf_end_text


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

&#60;?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?&#62;

See Also

cpdf_begin_text()

Prev | Home | Next
cpdf_curveto | Up | cpdf_fill_stroke


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.

See Also

cpdf_closepath()
cpdf_stroke()
cpdf_fill()
cpdf_setgray_fill()
cpdf_setgray()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor()

Prev | Home | Next
cpdf_end_text | Up | cpdf_fill


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.

See Also

cpdf_closepath()
cpdf_stroke()
cpdf_setgray_fill()
cpdf_setgray()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor()

Prev | Home | Next
cpdf_fill_stroke | Up | cpdf_finalize_page


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.

See Also

cpdf_page_init()

Prev | Home | Next
cpdf_fill | Up | cpdf_finalize


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()

Prev | Home | Next
cpdf_finalize_page | Up | cpdf_global_set_document_limits


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()

Prev | Home | Next
cpdf_finalize | Up | cpdf_import_jpeg


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.

See Also

cpdf_place_inline_image()

Prev | Home | Next
cpdf_global_set_document_limits | Up | cpdf_lineto


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.

See Also

cpdf_moveto()
cpdf_rmoveto()
cpdf_curveto()

Prev | Home | Next
cpdf_import_jpeg | Up | cpdf_moveto


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.

Prev | Home | Next
cpdf_lineto | Up | cpdf_newpath


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.

Prev | Home | Next
cpdf_moveto | Up | cpdf_open


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.

See Also

cpdf_close()
cpdf_output_buffer()

Prev | Home | Next
cpdf_newpath | Up | cpdf_output_buffer


cpdf_output_buffer

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

bool cpdf_output_buffer ( int pdf_document )

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()

Prev | Home | Next
cpdf_open | Up | cpdf_page_init


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.

See Also

cpdf_set_current_page()

Prev | Home | Next
cpdf_output_buffer | Up | cpdf_place_inline_image


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.

See Also

cpdf_import_jpeg()

Prev | Home | Next
cpdf_page_init | Up | cpdf_rect


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

&#60;?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);

?&#62;

Prev | Home | Next
cpdf_place_inline_image | Up | cpdf_restore


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

&#60;?php
cpdf_save($pdf);
// do all kinds of rotations, transformations, ...
cpdf_restore($pdf)
?&#62;

See Also

cpdf_save()

Prev | Home | Next
cpdf_rect | Up | cpdf_rlineto


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.

See Also

cpdf_moveto()
cpdf_rmoveto()
cpdf_curveto()

Prev | Home | Next
cpdf_restore | Up | cpdf_rmoveto


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()

Prev | Home | Next
cpdf_rlineto | Up | cpdf_rotate_text


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.

Prev | Home | Next
cpdf_rmoveto | Up | cpdf_rotate


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.

Prev | Home | Next
cpdf_rotate_text | Up | cpdf_save_to_file


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.

See Also

cpdf_output_buffer()
cpdf_open()

Prev | Home | Next
cpdf_rotate | Up | cpdf_save


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()

Prev | Home | Next
cpdf_save_to_file | Up | cpdf_scale


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.

Prev | Home | Next
cpdf_save | Up | cpdf_set_action_url


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.

Prev | Home | Next
cpdf_scale | Up | cpdf_set_char_spacing


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.

See Also

cpdf_set_word_spacing()
cpdf_set_leading()

Prev | Home | Next
cpdf_set_action_url | Up | cpdf_set_creator


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.

See Also

cpdf_set_subject()
cpdf_set_title()
cpdf_set_keywords()

Prev | Home | Next
cpdf_set_char_spacing | Up | cpdf_set_current_page


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.

See Also

cpdf_finalize_page()

Prev | Home | Next
cpdf_set_creator | Up | cpdf_set_font_directories


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.

Prev | Home | Next
cpdf_set_current_page | Up | cpdf_set_font_map_file


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.

Prev | Home | Next
cpdf_set_font_directories | Up | cpdf_set_font


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.

Prev | Home | Next
cpdf_set_font_map_file | Up | cpdf_set_horiz_scaling


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.

Prev | Home | Next
cpdf_set_font | Up | cpdf_set_keywords


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.

See Also

cpdf_set_title()
cpdf_set_creator()
cpdf_set_subject()

Prev | Home | Next
cpdf_set_horiz_scaling | Up | cpdf_set_leading


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.

See Also

cpdf_continue_text()

Prev | Home | Next
cpdf_set_keywords | Up | cpdf_set_page_animation


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.

Prev | Home | Next
cpdf_set_leading | Up | cpdf_set_subject


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.

See Also

cpdf_set_title()
cpdf_set_creator()
cpdf_set_keywords()

Prev | Home | Next
cpdf_set_page_animation | Up | cpdf_set_text_matrix


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.

Prev | Home | Next
cpdf_set_subject | Up | cpdf_set_text_pos


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.

See Also

cpdf_show()
cpdf_text()

Prev | Home | Next
cpdf_set_text_matrix | Up | cpdf_set_text_rendering


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.

Prev | Home | Next
cpdf_set_text_pos | Up | cpdf_set_text_rise


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.

Prev | Home | Next
cpdf_set_text_rendering | Up | cpdf_set_title


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.

See Also

cpdf_set_subject()
cpdf_set_creator()
cpdf_set_keywords()

Prev | Home | Next
cpdf_set_text_rise | Up | cpdf_set_viewer_preferences


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.

Prev | Home | Next
cpdf_set_title | Up | cpdf_set_word_spacing


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.

See Also

cpdf_set_char_spacing()
cpdf_set_leading()

Prev | Home | Next
cpdf_set_viewer_preferences | Up | cpdf_setdash


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.

Prev | Home | Next
cpdf_set_word_spacing | Up | cpdf_setflat


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.

Prev | Home | Next
cpdf_setdash | Up | cpdf_setgray_fill


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.

See Also

cpdf_setrgbcolor_fill()

Prev | Home | Next
cpdf_setflat | Up | cpdf_setgray_stroke


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.

See Also

cpdf_setrgbcolor_stroke()

Prev | Home | Next
cpdf_setgray_fill | Up | cpdf_setgray


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.

See Also

cpdf_setrgbcolor_stroke()
cpdf_setrgbcolor_fill()

Prev | Home | Next
cpdf_setgray_stroke | Up | cpdf_setlinecap


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.

Prev | Home | Next
cpdf_setgray | Up | cpdf_setlinejoin


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.

Prev | Home | Next
cpdf_setlinecap | Up | cpdf_setlinewidth


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.

Prev | Home | Next
cpdf_setlinejoin | Up | cpdf_setmiterlimit


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.

Prev | Home | Next
cpdf_setlinewidth | Up | cpdf_setrgbcolor_fill


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.

See Also

cpdf_setrgbcolor_stroke()
cpdf_setrgbcolor()

Prev | Home | Next
cpdf_setmiterlimit | Up | cpdf_setrgbcolor_stroke


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.

See Also

cpdf_setrgbcolor()
cpdf_setrgbcolor_fill()

Prev | Home | Next
cpdf_setrgbcolor_fill | Up | cpdf_setrgbcolor


cpdf_setrgbcolor

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

bool cpdf_setrgbcolor ( int pdf_document, float red_value, float green_value, float blue_value )

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.

See Also

cpdf_setrgbcolor_stroke()
cpdf_setrgbcolor_fill()

Prev | Home | Next
cpdf_setrgbcolor_stroke | Up | cpdf_show_xy


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()

Prev | Home | Next
cpdf_setrgbcolor | Up | cpdf_show


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.

See Also

cpdf_text()
cpdf_begin_text()
cpdf_end_text()

Prev | Home | Next
cpdf_show_xy | Up | cpdf_stringwidth


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()

Prev | Home | Next
cpdf_show | Up | cpdf_stroke


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.

See Also

cpdf_closepath()
cpdf_closepath_stroke()

Prev | Home | Next
cpdf_stringwidth | Up | cpdf_text


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()

Prev | Home | Next
cpdf_stroke | Up | cpdf_translate


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.

Prev | Home | Next
cpdf_text | Up | COM and .Net (Windows)


Crack Functions

PHP Manual
Prev Next

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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Crack configuration options

Name | Default | Changeable | Changelog
crack.default_dictionary | NULL | PHP_INI_PERDIR | Available since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

&#60;?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);
?&#62;

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

Prev | Home | Next
variant_xor | Up | crack_check


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.

Prev | Home | Next
Crack Functions | Up | crack_closedict


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.

See Also

crack_opendict()

Prev | Home | Next
crack_check | Up | crack_getlastmessage


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()

Prev | Home | Next
crack_closedict | Up | crack_opendict


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.

See Also

crack_check()
crack_closedict()

Prev | Home | Next
crack_getlastmessage | Up | Character Type Functions


Character Type Functions

PHP Manual
Prev Next

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

Prev | Home | Next
crack_opendict | Up | ctype_alnum


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)

&#60;?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";
    }
}
?&#62;

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.

See Also

ctype_alpha()
ctype_digit()
setlocale()

Prev | Home | Next
Character Type Functions | Up | ctype_alpha


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)

&#60;?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";
    }
}
?&#62;

The above example will output:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

See Also

ctype_upper()
ctype_lower()
setlocale()

Prev | Home | Next
ctype_alnum | Up | ctype_cntrl


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

&#60;?php
$strings = array('string1' =&#62; "\n\r\t", 'string2' =&#62; 'arf12');
foreach ($strings as $name =&#62; $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";
    }
}
?&#62;

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()

Prev | Home | Next
ctype_alpha | Up | ctype_digit


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

&#60;?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";
    }
}
?&#62;

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.

See Also

ctype_alnum()
ctype_xdigit()

Prev | Home | Next
ctype_cntrl | Up | ctype_graph


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

&#60;?php
$strings = array('string1' =&#62; "asdf\n\r\t", 'string2' =&#62; 'arf12', 'string3' =&#62; 'LKA#@%.54');
foreach ($strings as $name =&#62; $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";
    }
}
?&#62;

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.

See Also

ctype_alnum()
ctype_print()
ctype_punct()

Prev | Home | Next
ctype_digit | Up | ctype_lower


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)

&#60;?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";
    }
}
?&#62;

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.

See Also

ctype_alpha()
ctype_upper()
setlocale()

Prev | Home | Next
ctype_graph | Up | ctype_print


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

&#60;?php
$strings = array('string1' =&#62; "asdf\n\r\t", 'string2' =&#62; 'arf12', 'string3' =&#62; 'LKA#@%.54');
foreach ($strings as $name =&#62; $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";
    }
}
?&#62;

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.

See Also

ctype_cntrl()
ctype_graph()
ctype_punct()

Prev | Home | Next
ctype_lower | Up | ctype_punct


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

&#60;?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&#38;$()');
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";
    }
}
?&#62;

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.

See Also

ctype_cntrl()
ctype_graph()

Prev | Home | Next
ctype_print | Up | ctype_space


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

&#60;?php
$strings = array('string1' =&#62; "\n\r\t", 'string2' =&#62; "\narf12", 'string3' =&#62; '\n\r\t');
foreach ($strings as $name =&#62; $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";
    }
}
?&#62;

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.

See Also

ctype_cntrl()
ctype_graph()
ctype_punct()

Prev | Home | Next
ctype_punct | Up | ctype_upper


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)

&#60;?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";
    }
}
?&#62;

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.

See Also

ctype_alpha()
ctype_lower()
setlocale()

Prev | Home | Next
ctype_space | Up | ctype_xdigit


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

&#60;?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";
    }
}
?&#62;

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()

Prev | Home | Next
ctype_upper | Up | CURL, Client URL Library Functions


CURL, Client URL Library Functions

PHP Manual
Prev Next

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.

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_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_FTP_USE_EPSV (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_CAPATH (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLOPT_NOSIGNAL (integer)

CURLOPT_PROXYTYPE (integer)

CURLOPT_BUFFERSIZE (integer)

CURLOPT_HTTPGET (integer)

CURLOPT_HTTP_VERSION (integer)

CURLOPT_SSLKEY (integer)

CURLOPT_SSLKEYTYPE (integer)

CURLOPT_SSLKEYPASSWD (integer)

CURLOPT_SSLENGINE (integer)

CURLOPT_SSLENGINE_DEFAULT (integer)

CURLOPT_SSLCERTTYPE (integer)

CURLOPT_CRLF (integer)

CURLOPT_ENCODING (integer)

CURLOPT_PROXYPORT (integer)

CURLOPT_UNRESTRICTED_AUTH (integer)

CURLOPT_FTP_USE_EPRT (integer)

CURLOPT_HTTP200ALIASES (integer)

CURLOPT_HTTPAUTH (integer)

CURLAUTH_BASIC (integer)

CURLAUTH_DIGEST (integer)

CURLAUTH_GSSNEGOTIATE (integer)

CURLAUTH_NTLM (integer)

CURLAUTH_ANY (integer)

CURLAUTH_ANYSAFE (integer)

CURLOPT_PROXYAUTH (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_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_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)

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

&#60;?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);
?&#62;

Table of Contents
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

Prev | Home | Next
ctype_xdigit | Up | curl_close


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 webpage

&#60;?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);
?&#62;

See Also

curl_init()
curl_multi_close()

Prev | Home | Next
CURL, Client URL Library Functions | Up | curl_copy_handle


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

&#60;?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);
?&#62;

Prev | Home | Next
curl_close | Up | curl_errno


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.

See Also

curl_error()
Curl error codes

Prev | Home | Next
curl_copy_handle | Up | curl_error


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.

See Also

curl_errno()
Curl error codes

Prev | Home | Next
curl_errno | Up | curl_exec


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 you initialize 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 webpage

&#60;?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);
?&#62;

See Also

curl_multi_exec()

Prev | Home | Next
curl_error | Up | curl_getinfo


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"

Prev | Home | Next
curl_exec | Up | curl_init


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 webpage

&#60;?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);
?&#62;

See Also

curl_close()
curl_multi_init()

Prev | Home | Next
curl_getinfo | Up | curl_multi_add_handle


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.

See Also

curl_multi_remove_handle()
curl_multi_init()
curl_init()

Prev | Home | Next
curl_init | Up | curl_multi_close


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.

See Also

curl_multi_init()
curl_close()

Prev | Home | Next
curl_multi_add_handle | Up | curl_multi_exec


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 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

still_running

See Also

curl_multi_init()
curl_exec()

Prev | Home | Next
curl_multi_close | Up | curl_multi_getcontent


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 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

ch

A cURL handle returned by curl_init().

See Also

curl_multi_init()

Prev | Home | Next
curl_multi_exec | Up | curl_multi_info_read


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] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ChangeLog

Version | Description
5.2.0 | msgs_in_queue was added.

See Also

curl_multi_init()

Prev | Home | Next
curl_multi_getcontent | Up | curl_multi_init


curl_multi_init

(PHP 5)

curl_multi_init -- Returns a new cURL multi handle

Description

resource curl_multi_init ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

See Also

curl_init()
curl_multi_close()

Prev | Home | Next
curl_multi_info_read | Up | curl_multi_remove_handle


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 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ch

A cURL handle returned by curl_init().

See Also

curl_init()
curl_multi_init()
curl_multi_add_handle()

Prev | Home | Next
curl_multi_init | Up | curl_multi_select


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] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

timeout

See Also

curl_multi_init()

Prev | Home | Next
curl_multi_remove_handle | Up | curl_setopt_array


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 that you want to set

value

The value to be set on option.

value should be a bool for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_AUTOREFERER | TRUE to automatically set the Referer: field in requests where it follows a Location: redirect. | Available since PHP 5.1.0.
CURLOPT_BINARYTRANSFER | TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.
CURLOPT_COOKIESESSION | TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. | Available since PHP 5.1.0.
CURLOPT_CRLF | TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERROR | TRUE to fail silently if the HTTP code returned is greater than 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. You can then retrieve this value using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only. | Added in PHP 5.0.0.
CURLOPT_FTP_USE_EPSV | TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.
CURLOPT_FTPAPPEND | TRUE to append to the remote file instead of overwriting it.
CURLOPT_FTPASCII | An alias of CURLOPT_TRANSFERTEXT. Use that instead.
CURLOPT_FTPLISTONLY | TRUE to only list the names of an FTP directory.
CURLOPT_HEADER | TRUE to include the header in the output.
CURLOPT_HTTPGET | TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNEL | TRUE to tunnel through a given HTTP proxy.
CURLOPT_MUTE | TRUE to be completely silent with regards to the cURL functions.
CURLOPT_NETRC | TRUE to scan your ~/.netrc file to find your username and password for the remote site that you're establishing a connection with.
CURLOPT_NOBODY | TRUE to exclude the body from the output.
CURLOPT_NOPROGRESS TRUE to disable the progress meter for cURL transfers.

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:

Option | Set value to | Notes
CURLOPT_BUFFERSIZE | The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. | Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_CLOSEPOLICY | Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT | The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.
CURLOPT_DNS_CACHE_TIMEOUT | The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
CURLOPT_FTPSSLAUTH | The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). | Added in cURL 7.12.2 and PHP 5.1.0.
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

You can use the bitwise | (or) operator to combine more than one method. If you do this, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Added in PHP 5.0.0.
CURLOPT_INFILESIZE | The expected size, in bytes, of the file when uploading a file to a remote site.
CURLOPT_LOW_SPEED_LIMIT | The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.
CURLOPT_LOW_SPEED_TIME | The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.
CURLOPT_MAXCONNECTS | The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRS | The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT | An alternative port number to connect to.
CURLOPT_PROXYAUTH | The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. | Added in cURL 7.10.7 and PHP 5.1.0.
CURLOPT_PROXYPORT | The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. | Added in PHP 5.0.0.
CURLOPT_PROXYTYPE | Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. | Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_RESUME_FROM | The offset, in bytes, to resume a transfer from.
CURLOPT_SSL_VERIFYHOST | 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.
CURLOPT_SSLVERSION | The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases you must set this manually.
CURLOPT_TIMECONDITION | How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_ISUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default. | Added in PHP 5.1.0.
CURLOPT_TIMEOUT | The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEVALUE | The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.

value should be a string for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_CAINFO | The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATH | A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE | The contents of the "Set-Cookie: " header to be used in the HTTP request.
CURLOPT_COOKIEFILE | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
CURLOPT_COOKIEJAR | The name of a file to save all internal cookies to when the connection closes.
CURLOPT_CUSTOMREQUEST A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note: Don't do this without making sure your server supports the custom request method first.

CURLOPT_EGBSOCKET | Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.
CURLOPT_ENCODING | The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. | Added in cURL 7.10.
CURLOPT_FTPPORT | The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS | The full data to post in a HTTP "POST" operation.
CURLOPT_PROXY | The HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWD | A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE | A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE | Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER | The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LIST | A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT | The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD | The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE | The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". | Added in cURL 7.9.3 and PHP 5.0.0.
CURLOPT_SSLENGINE | The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT | The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY | The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

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. You can also set this when initializing a session with curl_init().
CURLOPT_USERAGENT | The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection.

value should be an array for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_HTTP200ALIASES | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3 and PHP 5.0.0.
CURLOPT_HTTPHEADER | An array of HTTP header fields to set.
CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_QUOTE | An array of FTP commands to execute on the server prior to the FTP request.

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_FILE | The file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILE | The file that the transfer should be read from when uploading.
CURLOPT_STDERR | An alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADER | The file that the header part of the transfer is written to.

value should be a string that is the name of a valid callback function for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_HEADERFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. Using this callback function, it becomes your responsibility to write the header data. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_READFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. Using this callback function, it becomes your responsibility to read the data. Return the number of bytes read. Return 0 to signal EOF.
CURLOPT_WRITEFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. Using this callback function, it becomes your responsibility to write the data. Must return the exact number of bytes written or this will fail.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Initializing a new cURL session and fetching a webpage

&#60;?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);
?&#62;

See Also

curl_setopt_array()

Prev | Home | Next
curl_setopt_array | Up | curl_version


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_number | cURL 24 bit version number
version | cURL version number, as a string
ssl_version_number | OpenSSL 24 bit version number
ssl_version | OpenSSL version number, as a string
libz_version | zlib version number, as a string
host | Information about the host where cURL was built
age |
features | A bitmask of the CURL_VERSION_XXX constants
protocols | An array of protocols names supported by cURL

Prev | Home | Next
curl_setopt | Up | Cybercash Payment Functions


Cybercash Payment Functions

PHP Manual
Prev Next

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

Prev | Home | Next
curl_version | Up | cybercash_base64_decode


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.

Prev | Home | Next
Cybercash Payment Functions | Up | cybercash_base64_encode


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.

Prev | Home | Next
cybercash_base64_decode | Up | cybercash_decr


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).

Prev | Home | Next
cybercash_base64_encode | Up | cybercash_encr


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).

Prev | Home | Next
cybercash_decr | Up | Credit Mutuel CyberMUT functions


Cyrus IMAP administration Functions

PHP Manual
Prev Next

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.

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

Prev | Home | Next
cybermut_testmac | Up | cyrus_authenticate


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.

Prev | Home | Next
Cyrus IMAP administration Functions | Up | cyrus_bind


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.

Prev | Home | Next
cyrus_authenticate | Up | cyrus_close


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.

Prev | Home | Next
cyrus_bind | Up | cyrus_connect


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.

Prev | Home | Next
cyrus_close | Up | cyrus_query


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.

Prev | Home | Next
cyrus_connect | Up | cyrus_unbind


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.

Prev | Home | Next
cyrus_query | Up | Date and Time Functions


Date and Time Functions

PHP Manual
Prev Next

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 H.

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

Name | Default | Changeable | Changelog
date.default_latitude | "31.7667" | PHP_INI_ALL | Available since PHP 5.0.0.
date.default_longitude | "35.2333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunrise_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunset_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0.
date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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 H 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

Prev | Home | Next
cyrus_unbind | Up | checkdate


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

&#60;?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?&#62;

The above example will output:

bool(true)
bool(false)

See Also

mktime()
strtotime()

Prev | Home | Next
Date and Time Functions | Up | date_create


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

constant | description | example
SUNFUNCS_RET_STRING | returns the result as string | 16:46
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
SUNFUNCS_RET_TIMESTAMP | returns 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

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. date_sunrise() example

&#60;?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);

?&#62;

The above example will output something similar to:

Mon Dec 20 2004, sunrise time : 08:54

See Also

date_sunset()

Prev | Home | Next
date_sun_info | Up | 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

constant | description | example
SUNFUNCS_RET_STRING | returns the result as string | 16:46
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
SUNFUNCS_RET_TIMESTAMP | returns 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

Version | Description
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

&#60;?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);

?&#62;

The above example will output something similar to:

Mon Dec 20 2004, sunset time : 18:13

See Also

date_sunrise()

Prev | Home | Next
date_sunrise | Up | date_time_set


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 character | Description | Example returned values
Day --- ---
d | Day of the month, 2 digits with leading zeros | 01 to 31
D | A textual representation of a day, three letters | Mon through Sun
j | Day of the month without leading zeros | 1 to 31
l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday
N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday)
S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
z | The day of the year (starting from 0) | 0 through 365
Week --- ---
W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year)
Month --- ---
F | A full textual representation of a month, such as January or March | January through December
m | Numeric representation of a month, with leading zeros | 01 through 12
M | A short textual representation of a month, three letters | Jan through Dec
n | Numeric representation of a month, without leading zeros | 1 through 12
t | Number of days in the given month | 28 through 31
Year --- ---
L | Whether it's a leap year | 1 if it is a leap year, 0 otherwise.
o | ISO-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
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year | Examples: 99 or 03
Time --- ---
a | Lowercase Ante meridiem and Post meridiem | am or pm
A | Uppercase Ante meridiem and Post meridiem | AM or PM
B | Swatch Internet time | 000 through 999
g | 12-hour format of an hour without leading zeros | 1 through 12
G | 24-hour format of an hour without leading zeros | 0 through 23
h | 12-hour format of an hour with leading zeros | 01 through 12
H | 24-hour format of an hour with leading zeros | 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds, with leading zeros | 00 through 59
Timezone --- ---
e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise.
O | Difference to Greenwich time (GMT) in hours | Example: +0200
P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00
T | Timezone abbreviation | Examples: EST, MDT ...
Z | Timezone 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 --- ---
c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00
r | RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200
U | Seconds 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

Version | Description
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

&#60;?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));
?&#62;

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()

&#60;?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?&#62;

It is possible to use date() and mktime() together to find dates in the future or the past.

Example 3. date() and mktime()example

&#60;?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);
?&#62;

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

&#60;?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
?&#62;

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.

See Also

getlastmod()
gmdate()
mktime()
strftime()
time()

Prev | Home | Next
date_timezone_set | Up | getdate


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

Key | Description | Example returned values
"seconds" | Numeric representation of seconds | 0 to 59
"minutes" | Numeric representation of minutes | 0 to 59
"hours" | Numeric representation of hours | 0 to 23
"mday" | Numeric representation of the day of the month | 1 to 31
"wday" | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
"mon" | Numeric representation of a month | 1 through 12
"year" | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
"yday" | Numeric representation of the day of the year | 0 through 365
"weekday" | A full textual representation of the day of the week | Sunday through Saturday
"month" | A full textual representation of a month, such as January or March | January 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

&#60;?php
$today = getdate();
print_r($today);
?&#62;

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
)

See Also

date()
time()
setlocale()

Prev | Home | Next
date | Up | gettimeofday


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

Version | Description
5.1.0 | The return_float parameter was added.

Examples

Example 1. gettimeofday() example

&#60;?php
print_r(gettimeofday());

echo gettimeofday(true);
?&#62;

The above example will output something similar to:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

Prev | Home | Next
getdate | Up | gmdate


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

Version | Description
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".

&#60;?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));
?&#62;

See Also

date()
mktime()
gmmktime()
strftime()

Prev | Home | Next
gettimeofday | Up | gmmktime


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

Version | Description
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

&#60;?php
gmmktime(0, 0, 0, 1, 1, 1970); // valid in GMT and west, invalid in east
?&#62;

See Also

mktime()
date()
time()

Prev | Home | Next
gmdate | Up | gmstrftime


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

&#60;?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";
?&#62;

See Also

strftime()

Prev | Home | Next
gmmktime | Up | idate


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 character | Description
B | Swatch Beat/Internet Time
d | Day of the month
h | Hour (12 hour format)
H | Hour (24 hour format)
i | Minutes
I | returns 1 if DST is activated, 0 otherwise
L | returns 1 for leap year, 0 otherwise
m | Month number
s | Seconds
t | Days in current month
U | Seconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time()
w | Day of the week (0 on Sunday)
W | ISO-8601 week number of year, weeks starting on Monday
y | Year (1 or 2 digits - check note below)
Y | Year (4 digits)
z | Day of the year
Z | Timezone 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

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. idate() example

&#60;?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);
?&#62;

See Also

date()
time()

Prev | Home | Next
gmstrftime | Up | localtime


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

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example 1. localtime() example

&#60;?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?&#62;

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
)

Prev | Home | Next
idate | Up | microtime


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

Version | Description
5.0.0 | The get_as_float parameter was added.

Examples

Example 1. Timing script execution with microtime()

&#60;?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";
?&#62;

Example 2. Timing script execution in PHP 5

&#60;?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";
?&#62;

See Also

time()

Prev | Home | Next
localtime | Up | mktime


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

Version | Description
3.0.10 | Added 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".

&#60;?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));
?&#62;

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".

&#60;?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);
?&#62;

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.

See Also

gmmktime()
date()
time()

Prev | Home | Next
microtime | Up | strftime


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

Version | Description
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

&#60;?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");
?&#62;

Example 2. ISO 8601:1988 week number example

&#60;?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";

?&#62;

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.

See Also

setlocale()
mktime()
strptime()
Open Group specification of strftime()

Prev | Home | Next
mktime | Up | strptime


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

parameters | Description
tm_sec | Seconds after the minute (0-61)
tm_min | Minutes after the hour (0-59)
tm_hour | Hour since midnight (0-23)
tm_mday | Day of the month (1-31)
tm_mon | Months since January (0-11)
tm_year | Years since 1900
tm_wday | Days since Sunday (0-6)
tm_yday | Days since January 1 (0-365)
unparsed | the date part which was not recognized using the specified format

Examples

Example 1. strptime() example

&#60;?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?&#62;

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()

Prev | Home | Next
strftime | Up | strtotime


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 0-69 are mapped to 2000-2069 and 70-100 to 1970-2000.

Parameters

time

The string to parse, according to the GNU Date Input Formats syntax. Before PHP 5.0, microseconds weren't allowed in the time, since PHP 5.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

Version | Description
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

&#60;?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";
?&#62;

Example 2. Checking for failure

&#60;?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);
}
?&#62;

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, "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()

Prev | Home | Next
strptime | Up | time


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

&#60;?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";
?&#62;

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.

See Also

date()
microtime()

Prev | Home | Next
strtotime | Up | timezone_abbreviations_list


Database (dbm-style) Abstraction Layer Functions

PHP Manual
Prev Next

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

Handler | Notes
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm | Gdbm is the GNU database manager.
db2 | DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 | DB3 is Sleepycat Software's DB3.
db4 | DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2.
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE.
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

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 malfaunctioning single handlers but not combinations.

Table 2. Supported DBA handlers

Handler | Configure Switch
dbm To enable support for dbm add --with-dbm[=DIR].

Note: dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm To enable support for ndbm add --with-ndbm[=DIR].

Note: ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm | To enable support for gdbm add --with-gdbm[=DIR].
db2 To enable support for 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

&#60;?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);
?&#62;

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

&#60;?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);
}

?&#62;

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

Prev | Home | Next
dbplus_xunlockrel | Up | dba_close


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.

See Also

dba_open()
dba_popen()

Prev | Home | Next
Database (dbm-style) Abstraction Layer Functions | Up | dba_delete


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.

See Also

dba_exists()
dba_fetch()
dba_insert()
dba_replace()

Prev | Home | Next
dba_close | Up | dba_exists


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.

See Also

dba_delete()
dba_fetch()
dba_insert()
dba_replace()

Prev | Home | Next
dba_delete | Up | dba_fetch


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

Version | Description
4.3 | The skip parameter is available to support cdb's capability of multiple keys having the same name.

See Also

dba_exists()
dba_delete()
dba_insert()
dba_replace()
dba_key_split()

Prev | Home | Next
dba_exists | Up | dba_firstkey


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

Prev | Home | Next
dba_fetch | Up | dba_handlers


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

&#60;?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name =&#62; $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?&#62;

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

Prev | Home | Next
dba_firstkey | Up | dba_insert


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.

See Also

dba_exists()
dba_delete()
dba_fetch()
dba_replace()

Prev | Home | Next
dba_handlers | Up | dba_key_split


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.

See Also

dba_firstkey()
dba_nextkey()
dba_fetch()

Prev | Home | Next
dba_insert | Up | dba_list


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.

Prev | Home | Next
dba_key_split | Up | dba_nextkey


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.

See Also

dba_firstkey()
dba_key_split()
Example 2 in the DBA examples

Prev | Home | Next
dba_list | Up | dba_open


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 webserver and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

Table 1. DBA locking

already open | mode = "rl" | mode = "rlt" | mode = "wl" | mode = "wlt" | mode = "rd" | mode = "rdt" | mode = "wd" | mode = "wdt"
not open | ok | ok | ok | ok | ok | ok | ok | ok
mode = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
mode = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
mode = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
mode = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false

ok: the second call will be successfull.
wait: the second call waits until dba_close() is called for the first.
false: the second call returns false.
illegal: you must not mix "l" and "d" modifiers for mode parameter.

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

Version | Description
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).

See Also

dba_popen()
dba_close()

Prev | Home | Next
dba_nextkey | Up | dba_optimize


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()

Prev | Home | Next
dba_open | Up | dba_popen


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.

See Also

dba_open()
dba_close()

Prev | Home | Next
dba_optimize | Up | dba_replace


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.

See Also

dba_exists()
dba_delete()
dba_fetch()
dba_insert()

Prev | Home | Next
dba_popen | Up | dba_sync


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()

Prev | Home | Next
dba_replace | Up | dBase Functions


dBase Functions

PHP Manual
Prev Next

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

Field | dBase Type | Format | Additional information
M | Memo | n/a | This type is not supported by PHP, such field will be ignored
D | Date | YYYYMMDD | The field length is limited to 8
N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point)
C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length.
L | Boolean | T or Y for TRUE, F or N for FALSE | Stored and returned as an integer (1 or 0)
F | Float | A float number | Support 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 webserver processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

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

Prev | Home | Next
dba_sync | Up | dbase_add_record


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

&#60;?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);
}

?&#62;

See Also

dbase_delete_record()
dbase_replace_record()

Prev | Home | Next
dBase Functions | Up | dbase_close


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

&#60;?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?&#62;

See Also

dbase_open()
dbase_create()

Prev | Home | Next
dbase_add_record | Up | dbase_create


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

&#60;?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";
}

?&#62;

See Also

dbase_open()
dbase_close()

Prev | Home | Next
dbase_close | Up | dbase_delete_record


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.

See Also

dbase_add_record()
dbase_replace_record()

Prev | Home | Next
dbase_create | Up | dbase_get_header_info


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

&#60;?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);
?&#62;

Prev | Home | Next
dbase_delete_record | Up | dbase_get_record_with_names


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

&#60;?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i &#60;= $record_numbers; $i++) {
      $row = dbase_get_record_with_names($db, $i);
      if ($row['ismember'] == 1) {
          echo "Member #$i: " . trim($row['name']) . "\n";
      }
  }
}
?&#62;

See Also

dbase_get_record()

Prev | Home | Next
dbase_get_header_info | Up | dbase_get_record


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.

See Also

dbase_get_record_with_names()

Prev | Home | Next
dbase_get_record_with_names | Up | dbase_numfields


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

&#60;?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i = 0; $i &#60; $nf; $i++) {
  echo $rec[$i], "\n";
}

?&#62;

See Also

dbase_numrecords()

Prev | Home | Next
dbase_get_record | Up | dbase_numrecords


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

&#60;?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i &#60;= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?&#62;

See Also

dbase_num_fields()

Prev | Home | Next
dbase_numfields | Up | dbase_open


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

&#60;?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?&#62;

Return Values

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

See Also

dbase_create()
dbase_close()

Prev | Home | Next
dbase_numrecords | Up | dbase_pack


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

&#60;?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i &#60;= $record_numbers; $i++) {
      dbase_delete_record($db, $i);
  }
  // expunge the database
  dbase_pack($db);
}

?&#62;

See Also

dbase_delete_record()

Prev | Home | Next
dbase_open | Up | dbase_replace_record


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

&#60;?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);
}

?&#62;

See Also

dbase_add_record()
dbase_delete_record()

Prev | Home | Next
dbase_pack | Up | DBM Functions [deprecated]


DBM Functions [deprecated]

PHP Manual
Prev Next

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

&#60;?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);

?&#62;

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

Prev | Home | Next
dbase_replace_record | Up | dblist


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.

Prev | Home | Next
DBM Functions [deprecated] | Up | dbmclose


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()

Prev | Home | Next
dblist | Up | dbmdelete


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()

Prev | Home | Next
dbmclose | Up | dbmexists


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()

Prev | Home | Next
dbmdelete | Up | 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.

Prev | Home | Next
dbmexists | Up | dbmfirstkey


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()

Prev | Home | Next
dbmfetch | Up | dbminsert


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().)

See Also

dbmreplace()
dbmdelete()

Prev | Home | Next
dbmfirstkey | Up | dbmnextkey


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

&#60;?php

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}

?&#62;

See Also

dbmfirstkey()

Prev | Home | Next
dbminsert | Up | dbmopen


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()

Prev | Home | Next
dbmnextkey | Up | dbmreplace


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()

Prev | Home | Next
dbmopen | Up | dbx Functions


DB++ Functions

PHP Manual
Prev Next

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 Constant | db++ constant | meaning
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget()
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server)
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek()
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |

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

Prev | Home | Next
timezone_transitions_get | Up | dbplus_add


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 )

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.

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

Prev | Home | Next
DB++ Functions | Up | dbplus_aql


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]] )

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() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

Prev | Home | Next
dbplus_add | Up | dbplus_chdir


dbplus_chdir

(4.1.0 - 4.2.3 only, PECL)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir] )

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() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

Prev | Home | Next
dbplus_aql | Up | dbplus_close


dbplus_close

(4.1.0 - 4.2.3 only, PECL)

dbplus_close -- Close a relation

Description

mixed dbplus_close ( resource relation )

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.

Calling dbplus_close() will close a relation previously opened by dbplus_open().

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Prev | Home | Next
dbplus_chdir | Up | dbplus_curr


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 )

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() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_prev(),
dbplus_next(), and
dbplus_last().

Prev | Home | Next
dbplus_close | Up | dbplus_errcode


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] )

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() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

Prev | Home | Next
dbplus_curr | Up | dbplus_errno


dbplus_errno

(4.1.0 - 4.2.3 only, PECL)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void )

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() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

Prev | Home | Next
dbplus_errcode | Up | dbplus_find


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 )

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() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

See also dbplus_unselect().

Prev | Home | Next
dbplus_errno | Up | dbplus_first


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 )

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() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(),
dbplus_prev(),
dbplus_next(), and
dbplus_last().

Prev | Home | Next
dbplus_find | Up | dbplus_flush


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 )

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() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

Prev | Home | Next
dbplus_first | Up | dbplus_freealllocks


dbplus_freealllocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void )

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() will free all tuple locks held by this client.

See also dbplus_getlock(),
dbplus_freelock(), and
dbplus_freerlocks().

Prev | Home | Next
dbplus_flush | Up | dbplus_freelock


dbplus_freelock

(4.1.0 - 4.2.3 only, PECL)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname )

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() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(),
dbplus_freerlocks(), and
dbplus_freealllocks().

Prev | Home | Next
dbplus_freealllocks | Up | dbplus_freerlocks


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 )

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() will free all tuple locks held on the given relation.

See also dbplus_getlock(),
dbplus_freelock(), and
dbplus_freealllocks().

Prev | Home | Next
dbplus_freelock | Up | dbplus_getlock


dbplus_getlock

(4.1.0 - 4.2.3 only, PECL)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname )

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() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(),
dbplus_freerlocks(), and
dbplus_freealllocks().

Prev | Home | Next
dbplus_freerlocks | Up | dbplus_getunique


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 )

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() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

Prev | Home | Next
dbplus_getlock | Up | dbplus_info


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

Prev | Home | Next
dbplus_getunique | Up | dbplus_last


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 )

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() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_prev(), and
dbplus_next().

Prev | Home | Next
dbplus_info | Up | dbplus_lockrel


dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation )

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() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

Prev | Home | Next
dbplus_last | Up | dbplus_next


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 )

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() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_prev(), and
dbplus_last().

Prev | Home | Next
dbplus_lockrel | Up | dbplus_open


dbplus_open

(4.1.0 - 4.2.3 only, PECL)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name )

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.

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

Prev | Home | Next
dbplus_next | Up | dbplus_prev


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 )

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() will read the data for the previous tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_next(), and
dbplus_last().

Prev | Home | Next
dbplus_open | Up | dbplus_rchperm


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 )

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() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

Prev | Home | Next
dbplus_prev | Up | dbplus_rcreate


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] )

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() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Prev | Home | Next
dbplus_rchperm | Up | dbplus_rcrtexact


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] )

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() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Prev | Home | Next
dbplus_rcreate | Up | dbplus_rcrtlike


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] )

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() will create an empty copy of the given relation under a new name, but with default indices. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Prev | Home | Next
dbplus_rcrtexact | Up | dbplus_resolve


dbplus_resolve

(4.1.0 - 4.2.3 only, PECL)

dbplus_resolve -- Resolve host information for relation

Description

array dbplus_resolve ( string relation_name )

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() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

Prev | Home | Next
dbplus_rcrtlike | Up | dbplus_restorepos


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

Prev | Home | Next
dbplus_resolve | Up | dbplus_rkeys


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 )

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() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Prev | Home | Next
dbplus_restorepos | Up | dbplus_ropen


dbplus_ropen

(4.1.0 - 4.2.3 only, PECL)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name )

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() 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.

Prev | Home | Next
dbplus_rkeys | Up | dbplus_rquery


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] )

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() 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.

Prev | Home | Next
dbplus_ropen | Up | dbplus_rrename


dbplus_rrename

(4.1.0 - 4.2.3 only, PECL)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name )

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() will change the name of relation to name.

Prev | Home | Next
dbplus_rquery | Up | dbplus_rsecindex


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 )

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() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Prev | Home | Next
dbplus_rrename | Up | dbplus_runlink


dbplus_runlink

(4.1.0 - 4.2.3 only, PECL)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation )

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_unlink() will close and remove the relation.

Prev | Home | Next
dbplus_rsecindex | Up | dbplus_rzap


dbplus_rzap

(4.1.0 - 4.2.3 only, PECL)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation )

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() will remove all tuples from relation.

Prev | Home | Next
dbplus_runlink | Up | dbplus_savepos


dbplus_savepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_savepos -- Save position

Description

int dbplus_savepos ( resource relation )

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.

Prev | Home | Next
dbplus_rzap | Up | dbplus_setindex


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

Prev | Home | Next
dbplus_savepos | Up | dbplus_setindexbynumber


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

Prev | Home | Next
dbplus_setindex | Up | dbplus_sql


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

Prev | Home | Next
dbplus_setindexbynumber | Up | dbplus_tcl


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 )

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.

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

See also dbplus_resolve().

Prev | Home | Next
dbplus_sql | Up | dbplus_tremove


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] )

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() 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().

Prev | Home | Next
dbplus_tcl | Up | dbplus_undo


dbplus_undo

(4.1.0 - 4.2.3 only, PECL)

dbplus_undo -- Undo

Description

int dbplus_undo ( resource relation )

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.

Prev | Home | Next
dbplus_tremove | Up | dbplus_undoprepare


dbplus_undoprepare

(4.1.0 - 4.2.3 only, PECL)

dbplus_undoprepare -- Prepare undo

Description

int dbplus_undoprepare ( resource relation )

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.

Prev | Home | Next
dbplus_undo | Up | dbplus_unlockrel


dbplus_unlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation )

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() will release a write lock previously obtained by dbplus_lockrel().

Prev | Home | Next
dbplus_undoprepare | Up | dbplus_unselect


dbplus_unselect

(4.1.0 - 4.2.3 only, PECL)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation )

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.

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Prev | Home | Next
dbplus_unlockrel | Up | dbplus_update


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 )

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() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

Prev | Home | Next
dbplus_unselect | Up | dbplus_xlockrel


dbplus_xlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation )

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() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

Prev | Home | Next
dbplus_update | Up | dbplus_xunlockrel


dbplus_xunlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation )

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() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

Prev | Home | Next
dbplus_xlockrel | Up | Database (dbm-style) Abstraction Layer Functions


dbx Functions

PHP Manual
Prev Next

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:

  • FrontBase (available from PHP 4.1.0).

  • Microsoft SQL Server

  • MySQL

  • ODBC

  • PostgreSQL

  • Sybase-CT (available from PHP 4.2.0).

  • Oracle (oci8) (available from PHP 4.3.0).

  • SQLite (PHP 5).

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.

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

Name | Default | Changeable | Changelog
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Prev | Home | Next
dbmreplace | Up | dbx_close


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

&#60;?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?&#62;

Notes

Note: Always refer to the module-specific documentation as well.

See Also

dbx_connect()

Prev | Home | Next
dbx Functions | Up | dbx_compare


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

&#60;?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);
?&#62;

See Also

dbx_sort()

Prev | Home | Next
dbx_close | Up | dbx_connect


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).

&#60;?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link-&#62;handle); // dbx_close($link) would be better here
?&#62;

module

It is used internally by dbx only, and is actually the module number mentioned above.

Examples

Example 1. dbx_connect() example

&#60;?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?&#62;

Notes

Note: Always refer to the module-specific documentation as well.

See Also

dbx_close()

Prev | Home | Next
dbx_compare | Up | dbx_error


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

&#60;?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);
?&#62;

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.

Prev | Home | Next
dbx_connect | Up | dbx_escape_string


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

&#60;?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);
?&#62;

See Also

dbx_query()

Prev | Home | Next
dbx_error | Up | dbx_fetch_row


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

&#60;?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "&#60;table&#62;\n";
while ($row = dbx_fetch_row($result)) {
    echo "&#60;tr&#62;\n";
    foreach ($row as $field) {
        echo "&#60;td&#62;$field&#60;/td&#62;";
    }
    echo "&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";
?&#62;

See Also

dbx_query()

Prev | Home | Next
dbx_escape_string | Up | 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).

&#60;?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result-&#62;handle, 0);
?&#62;

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

&#60;?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result-&#62;rows; // number of records
echo $result-&#62;cols; // number of fields
?&#62;

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

&#60;?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i &#60; $result-&#62;cols; $i++ ) {
    echo $result-&#62;info['name'][$i] . "\n";
    echo $result-&#62;info['type'][$i] . "\n";
}
?&#62;
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

&#60;?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "&#60;table&#62;\n";
foreach ($result-&#62;data as $row) {
    echo "&#60;tr&#62;\n";
    foreach ($row as $field) {
        echo "&#60;td&#62;$field&#60;/td&#62;";
    }
    echo "&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";
?&#62;

Example 3. How to handle UNBUFFERED queries

&#60;?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "&#60;table&#62;\n";
while ($row = dbx_fetch_row($result)) {
    echo "&#60;tr&#62;\n";
    foreach ($row as $field) {
        echo "&#60;td&#62;$field&#60;/td&#62;";
    }
    echo "&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

?&#62;

Examples

Example 4. How to handle the returned value

&#60;?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);
?&#62;

Notes

Note: Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See Also

dbx_escape_string()
dbx_fetch_row()
dbx_connect()

Prev | Home | Next
dbx_fetch_row | Up | dbx_sort


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

&#60;?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);
?&#62;

Notes

Note: It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

See Also

dbx_compare()

Prev | Home | Next
dbx_query | Up | Direct IO Functions


Direct IO Functions

PHP Manual
Prev Next

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

Prev | Home | Next
dbx_sort | Up | dio_close


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

&#60;?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?&#62;

See Also

dio_open()

Prev | Home | Next
Direct IO Functions | Up | dio_fcntl


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

&#60;?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=&#62;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);
?&#62;

Prev | Home | Next
dio_close | Up | dio_open


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

&#60;?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?&#62;

See Also

dio_close()

Prev | Home | Next
dio_fcntl | Up | dio_read


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()

Prev | Home | Next
dio_open | Up | dio_seek


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

&#60;?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);
?&#62;

Prev | Home | Next
dio_read | Up | dio_stat


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.

Prev | Home | Next
dio_seek | Up | dio_tcsetattr


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

&#60;?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' =&#62; 9600,
  'bits' =&#62; 8,
  'stop'  =&#62; 1,
  'parity' =&#62; 0
));

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
}

?&#62;

Prev | Home | Next
dio_stat | Up | dio_truncate


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.

Prev | Home | Next
dio_tcsetattr | Up | dio_write


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()

Prev | Home | Next
dio_truncate | Up | Directory Functions


Directory Functions

PHP Manual
Prev Next

XXIX. Directory Functions

Introduction

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

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

Prev | Home | Next
dio_write | Up | chdir


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

&#60;?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?&#62;

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()

Prev | Home | Next
Directory Functions | Up | chroot


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.

Prev | Home | Next
chdir | Up | dir


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.

&#60;?php
$d = dir("/etc/php5");
echo "Handle: " . $d-&#62;handle . "\n";
echo "Path: " . $d-&#62;path . "\n";
while (false !== ($entry = $d-&#62;read())) {
   echo $entry."\n";
}
$d-&#62;close();
?&#62;

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.

Prev | Home | Next
chroot | Up | closedir


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

&#60;?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);
    }
}
?&#62;

Prev | Home | Next
dir | Up | getcwd


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

&#60;?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?&#62;

The above example will output something similar to:

/home/didou
/home/didou/cvs

See Also

chdir()
chmod()

Prev | Home | Next
closedir | Up | opendir


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

Version | Description
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

&#60;?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);
    }
}
?&#62;

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

See Also

is_dir()
readdir()
Dir

Prev | Home | Next
getcwd | Up | readdir


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.

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").

&#60;?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);
}
?&#62;

Example 2. List all files in the current directory and strip out . and ..

&#60;?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." &#38;&#38; $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?&#62;

See Also

is_dir()
glob()

Prev | Home | Next
opendir | Up | rewinddir


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().

Prev | Home | Next
readdir | Up | scandir


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

&#60;?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?&#62;

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()

&#60;?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?&#62;

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 M for a list of supported URL protocols.

See Also

opendir()
readdir()
glob()
is_dir()
sort()

Prev | Home | Next
rewinddir | Up | DOM Functions


DOM Functions

PHP Manual
Prev Next

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

  • DOMAttr->__construct() - construct a new DOMAttr object

Methods

  • DOMAttr->isId() - Checks if attribute is a defined ID

Properties

Table 1.

Name | Type | Read-only | Description
name | string | yes | The name of the attribute
ownerElement | DOMElement | yes | The element which contains the attribute
schemaTypeInfo | bool | yes | Not implemented yet, always return NULL
specified | bool | yes | Not implemented yet, always return NULL
value | string | no | The value of the attribute

DOMCharacterData

Extends DOMNode.

Methods

  • DOMCharacterData->appendData() - Append a string to the end of the character data of the node

  • DOMCharacterData->deleteData() - Remove a range of characters from the node

  • DOMCharacterData->insertData() - Insert a string at the specified 16-bit unit offset

  • DOMCharacterData->replaceData() - Replace a substring within the DOMCharacterData node

  • DOMCharacterData->substringData() - Extracts a range of data from the node

Properties

Table 2.

Name | Type | Read-only | Description
data | string | no | The contents of the node
length | int | yes | The length of the contents

DOMComment

Extends DOMCharacterData.

Constructor

  • DOMComment->__construct() - construct a new DOMComment object

DOMDocument

Extends DOMNode.

Constructor

  • DOMDocument->__construct() - construct a new DOMDocument object

Methods

  • 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->relaxNGValidate() - Performs relaxNG validation on the document

  • DOMDocument->relaxNGValidateSource() - Performs relaxNG validation on the document

  • DOMDocument->registerNodeClass() - Register extended class used to create base node type (not DOM standard)

  • DOMDocument->save() - Dumps the internal XML tree back into a file

  • DOMDocument->saveHTML() - Dumps the internal document into a string using HTML formatting

  • DOMDocument->saveHTMLFile() - Dumps the internal document back into a file using HTML formatting

  • DOMDocument->saveXML() - Dumps the internal XML tree back into a string

  • DOMDocument->schemaValidate() - Validates a document based on a schema

  • DOMDocument->schemaValidateSource() - Validates a document based on a schema

  • DOMDocument->validate() - Validates the document based on its DTD

  • DOMDocument->xinclude() - Substitutes XIncludes in a DOMDocument Object

Properties

Table 3.

Name | Type | Read-only | Description
actualEncoding | string | yes |
config | DOMConfiguration | yes |
doctype | DOMDocumentType | yes | The Document Type Declaration associated with this document.
documentElement | DOMElement | yes | This is a convenience attribute that allows direct access to the child node that is the document element of the document.
documentURI | string | no | The location of the document or NULL if undefined.
encoding | string | no |
formatOutput | bool | no |
implementation | DOMImplementation | yes | The DOMImplementation object that handles this document.
preserveWhiteSpace | bool | no | Do not remove redundant white space. Default to TRUE.
recover | bool | no |
resolveExternals | bool | no | Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.
standalone | bool | no |
strictErrorChecking | bool | no | Throws DOMException on errors. Default to TRUE.
substituteEntities | bool | no |
validateOnParse | bool | no | Loads and validates against the DTD. Default to FALSE.
version | string | no |
xmlEncoding | string | yes | An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.
xmlStandalone | bool | no | An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.
xmlVersion | string | no | An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

DOMDocumentFragment

Extends DOMNode.

Methods

  • DOMDocumentFragment->appendXML() - Append raw XML data (not DOM standard)

DOMDocumentType

Extends DOMNode

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.

Properties

Table 4.

Name | Type | Read-only | Description
publicId | string | yes | The public identifier of the external subset.
systemId | string | yes | The system identifier of the external subset. This may be an absolute URI or not.
name | string | yes | The name of DTD; i.e., the name immediately following the DOCTYPE keyword.
entities | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.
notations | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the notations declared in the DTD.
internalSubset | string | yes | The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.

DOMElement

Extends DOMNode.

Constructor

  • DOMElement->__construct() - construct a new DOMElement object

Methods

  • 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 ID attribute

  • DOMElement->setIdAttributeNode() - Declares the ID attribute

  • DOMElement->setIdAttributeNS() - Declares the ID attribute

Properties

Table 5.

Name | Type | Read-only | Description
schemaTypeInfo | bool | yes | Not implemented yet, always return NULL
tagName | string | yes | The element name

DOMEntity

Extends DOMNode

This interface represents a known entity, either parsed or unparsed, in an XML document.

Properties

Table 6.

Name | Type | Read-only | Description
publicId | string | yes | The public identifier associated with the entity if specified, and NULL otherwise.
systemId | string | yes | The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.
notationName | string | yes | For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.
actualEncoding | string | no | An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.
encoding | string | yes | An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.
version | string | yes | An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.

DOMEntityReference

Extends DOMNode.

Constructor

  • DOMEntityReference->__construct() - construct a new DOMEntityReference object

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.

Name | Type | Read-only | Description
code | int | yes | An 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

  • DOMImplementation->__construct() - construct a new DOMImplementation object

Methods

  • DOMImplementation->createDocument() - Creates a DOM Document object of the specified type with its document element

  • DOMImplementation->createDocumentType() - Creates an empty DOMDocumentType object

  • DOMImplementation->hasFeature() - Test if the DOM implementation implements a specific feature

DOMNode

Methods

  • 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

  • DOMNode->isSameNode() - Indicates if two nodes are the same node

  • DOMNode->isSupported() - Checks if feature is supported for specified version

  • DOMNode->lookupNamespaceURI() - Returns namespace URI of the node based on the prefix

  • DOMNode->lookupPrefix() - Returns name space prefix of the node based on namespaceURI

  • DOMNode->normalize() - Normalizes the node

  • DOMNode->removeChild() - Removes child from list of children

  • DOMNode->replaceChild() - Replaces a child

Properties

Table 8.

Name | Type | Read-only | Description
nodeName | string | yes | Returns the most accurate name for the current node type
nodeValue | string | no | The value of this node, depending on its type.
nodeType | int | yes | Gets the type of the node. One of the predefined XML_xxx_NODE constants
parentNode | DOMNode | yes | The parent of this node.
childNodes | DOMNodeList | yes | A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.
firstChild | DOMNode | yes | The first child of this node. If there is no such node, this returns NULL.
lastChild | DOMNode | yes | The last child of this node. If there is no such node, this returns NULL.
previousSibling | DOMNode | yes | The node immediately preceding this node. If there is no such node, this returns NULL.
nextSibling | DOMNode | yes | The node immediately following this node. If there is no such node, this returns NULL.
attributes | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.
ownerDocument | DOMDocument | yes | The DOMDocument object associated with this node.
namespaceURI | string | yes | The namespace URI of this node, or NULL if it is unspecified.
prefix | string | no | The namespace prefix of this node, or NULL if it is unspecified.
localName | string | yes | Returns the local part of the qualified name of this node.
baseURI | string | yes | The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.
textContent | string | no | This attribute returns the text content of this node and its descendants.

DOMNodeList

Methods

  • DOMNodelist->item() - Retrieves a node specified by index

Properties

Table 9.

Name | Type | Read-only | Description
length | int | yes | 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.

Name | Type | Read-only | Description
publicId | string | yes |
systemId | string | yes |

DOMProcessingInstruction

Extends DOMNode.

Constructor

  • DOMProcessingInstruction->__construct() - construct a new DOMProcessingInstruction object

Properties

Table 11.

Name | Type | Read-only | Description
target | string | yes |
data | string | no |

DOMText

Extends DOMCharacterData.

Constructor

  • DOMText->__construct() - construct a new DOMText object

Methods

  • DOMText->isWhitespaceInElementContent() - Indicates whether this text node contains whitespace

  • DOMText->splitText() - Breaks the node into two nodes at the specified offset

Properties

Table 12.

Name | Type | Read-only | Description
wholeText | string | yes |

DOMXPath

Constructor

  • DOMXPath->__construct() - construct a new DOMXPath object

Methods

  • DOMXPath->registerNamespace() - Registers the namespace with the DOMXpath object

  • DOMXPath->evaluate() - Evaluates the given XPath expression and returns a typed result if possible

  • DOMXPath->query() - Evaluates the given XPath expression

Properties

Table 13.

Name | Type | Read-only | Description
document | DOMDocument |  |

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

Constant | Value | Description
XML_ELEMENT_NODE (integer) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) | 2 | Node is a DOMAttr
XML_TEXT_NODE (integer) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (integer) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (integer) | 6 | Node is a DOMEntity
XML_PI_NODE (integer) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (integer) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) | 13 |
XML_DTD_NODE (integer) | 14 |
XML_ELEMENT_DECL_NODE (integer) | 15 |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 |
XML_ENTITY_DECL_NODE (integer) | 17 |
XML_NAMESPACE_DECL_NODE (integer) | 18 |
XML_ATTRIBUTE_CDATA (integer) | 1 |
XML_ATTRIBUTE_ID (integer) | 2 |
XML_ATTRIBUTE_IDREF (integer) | 3 |
XML_ATTRIBUTE_IDREFS (integer) | 4 |
XML_ATTRIBUTE_ENTITY (integer) | 5 |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 |
XML_ATTRIBUTE_NOTATION (integer) | 10 |

Table 15. DOMException constants

Constant | Value | Description
DOM_INDEX_SIZE_ERR (integer) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
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

Prev | Home | Next
scandir | Up | DOMAttr->__construct()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom-&#62;appendChild(new DOMElement('root'));
$attr = $element-&#62;setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62;&#60;root attr="attrvalue" /&#62; */

?&#62;

See Also

DOMDocument->createAttribute()

Prev | Home | Next
DOM Functions | Up | DOMAttr->isId()


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

&#60;?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc-&#62;validateOnParse = true;
$doc-&#62;Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc-&#62;getElementsByTagName('chapter')-&#62;item(0)-&#62;getAttributeNode('id');

var_dump($attr-&#62;isId()); // bool(true)

?&#62;

Prev | Home | Next
DOMAttr->__construct() | Up | DOMCharacterData->appendData()


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.

See Also

DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()

Prev | Home | Next
DOMAttr->isId() | Up | DOMCharacterData->deleteData()


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.

See Also

DOMCharacterData->appendData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()

Prev | Home | Next
DOMCharacterData->appendData() | Up | DOMCharacterData->insertData()


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.

See Also

DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()

Prev | Home | Next
DOMCharacterData->deleteData() | Up | DOMCharacterData->replaceData()


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.

See Also

DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->substringData()

Prev | Home | Next
DOMCharacterData->insertData() | Up | DOMCharacterData->substringData()


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.

See Also

DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()

Prev | Home | Next
DOMCharacterData->replaceData() | Up | DOMComment->__construct()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom-&#62;appendChild(new DOMElement('root'));
$comment = $element-&#62;appendChild(new DOMComment('root comment'));
echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62;&#60;root&#62;&#60;!--root comment--&#62;&#60;/root&#62; */

?&#62;

See Also

DOMDocument->createComment()

Prev | Home | Next
DOMCharacterData->substringData() | Up | DOMDocument->__construct()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62; */

?&#62;

See Also

DOMImplementation->createDocument()

Prev | Home | Next
DOMComment->__construct() | Up | DOMDocument->createAttribute()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->__construct() | Up | DOMDocument->createAttributeNS()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createAttribute() | Up | DOMDocument->createCDATASection()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createAttributeNS() | Up | DOMDocument->createComment()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createCDATASection() | Up | DOMDocument->createDocumentFragment()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createComment() | Up | DOMDocument->createElement()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom-&#62;createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom-&#62;appendChild($element);

echo $dom-&#62;saveXML();
?&#62;

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<test>This is the root element!</test>

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createDocumentFragment() | Up | DOMDocument->createElementNS()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom-&#62;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-&#62;appendChild($element);

echo $dom-&#62;saveXML();
?&#62;

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>

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createElement() | Up | DOMDocument->createEntityReference()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createElementNS() | Up | DOMDocument->createProcessingInstruction()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createTextNode()

Prev | Home | Next
DOMDocument->createEntityReference() | Up | DOMDocument->createTextNode()


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.

See Also

DOMNode->appendChild()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()

Prev | Home | Next
DOMDocument->createProcessingInstruction() | Up | DOMDocument->getElementById()


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

&#60;?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc-&#62;validateOnParse = true;
$doc-&#62;Load('book.xml');

echo "The element whose id is books is: " . $doc-&#62;getElementById('books')-&#62;tagName . "\n";

?&#62;

The above example will output:

The element whose id is books is: chapter

See Also

DOMDocument->getElementsByTagName()

Prev | Home | Next
DOMDocument->createTextNode() | Up | DOMDocument->getElementsByTagName()


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.

See Also

DOMDocument->getElementsByTagNameNS()

Prev | Home | Next
DOMDocument->getElementById() | Up | DOMDocument->getElementsByTagNameNS()


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

&#60;?php

$xml = &#60;&#60;&#60;EOD
&#60;?xml version="1.0" ?&#62;
&#60;chapter xmlns:xi="http://www.w3.org/2001/XInclude"&#62;
&#60;title&#62;Books of the other guy..&#60;/title&#62;
&#60;para&#62;
 &#60;xi:include href="book.xml"&#62;
  &#60;xi:fallback&#62;
   &#60;error&#62;xinclude: book.xml not found&#60;/error&#62;
  &#60;/xi:fallback&#62;
 &#60;/xi:include&#62;
 &#60;include&#62;
  This is another namespace
 &#60;/include&#62;
&#60;/para&#62;
&#60;/chapter&#62;
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom-&#62;loadXML($xml);

foreach ($dom-&#62;getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element-&#62;localName, ', prefix: ', $element-&#62;prefix, "\n";
}
?&#62;

The above example will output:

local name: include, prefix: xi
local name: fallback, prefix: xi

See Also

DOMDocument->getElementsByTagName()

Prev | Home | Next
DOMDocument->getElementsByTagName() | Up | DOMDocument->importNode()


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.

Prev | Home | Next
DOMDocument->getElementsByTagNameNS() | Up | DOMDocument->load()


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

&#60;?php
$doc = new DOMDocument();
$doc-&#62;load('book.xml');
echo $doc-&#62;saveXML();
?&#62;

See Also

DOMDocument->loadXML()
DOMDocument->save()
DOMDocument->saveXML()

Prev | Home | Next
DOMDocument->importNode() | Up | DOMDocument->loadHTML()


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

&#60;?php
$doc = new DOMDocument();
$doc-&#62;loadHTML("&#60;html&#62;&#60;body&#62;Test&#60;br&#62;&#60;/body&#62;&#60;/html&#62;");
echo $doc-&#62;saveHTML();
?&#62;

See Also

DOMDocument->loadHTMLFile()
DOMDocument->saveHTML()
DOMDocument->saveHTMLFile()

Prev | Home | Next
DOMDocument->load() | Up | DOMDocument->loadHTMLFile()


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

&#60;?php
$doc = new DOMDocument();
$doc-&#62;loadHTMLFile("filename.html");
echo $doc-&#62;saveHTML();
?&#62;

See Also

DOMDocument->loadHTML()
DOMDocument->saveHTML()
DOMDocument->saveHTMLFile()

Prev | Home | Next
DOMDocument->loadHTML() | Up | DOMDocument->loadXML()


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

&#60;?php
$doc = new DOMDocument();
$doc-&#62;loadXML('&#60;root&#62;&#60;node/&#62;&#60;/root&#62;');
echo $doc-&#62;saveXML();
?&#62;

Example 2. Static invocation of loadXML

&#60;?php
$doc = DOMDocument::loadXML('&#60;root&#62;&#60;node/&#62;&#60;/root&#62;');
echo $doc-&#62;saveXML();
?&#62;

See Also

DOMDocument->load()
DOMDocument->save()
DOMDocument->saveXML()

Prev | Home | Next
DOMDocument->loadHTMLFile() | Up | DOMDocument->normalizeDocument()


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.

See Also

DOMDocument->relaxNGValidateSource()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()

Prev | Home | Next
DOMDocument->registerNodeClass() | Up | DOMDocument->relaxNGValidateSource()


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.

See Also

DOMDocument->relaxNGValidate()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()

Prev | Home | Next
DOMDocument->relaxNGValidate() | Up | DOMDocument->save()


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

Version | Description
5.1.0 | Added the options parameter

Examples

Example 1. Saving a DOM tree into a file

&#60;?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc-&#62;formatOutput = true;

$root = $doc-&#62;createElement('book');
$root = $doc-&#62;appendChild($root);

$title = $doc-&#62;createElement('title');
$title = $root-&#62;appendChild($title);

$text = $doc-&#62;createTextNode('This is the title');
$text = $title-&#62;appendChild($text);

echo 'Wrote: ' . $doc-&#62;save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?&#62;

See Also

DOMDocument->saveXML()
DOMDocument->load()
DOMDocument->loadXML()

Prev | Home | Next
DOMDocument->relaxNGValidateSource() | Up | DOMDocument->saveHTML()


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

&#60;?php

$doc = new DOMDocument('1.0');

$root = $doc-&#62;createElement('html');
$root = $doc-&#62;appendChild($root);

$head = $doc-&#62;createElement('head');
$head = $root-&#62;appendChild($head);

$title = $doc-&#62;createElement('title');
$title = $head-&#62;appendChild($title);

$text = $doc-&#62;createTextNode('This is the title');
$text = $title-&#62;appendChild($text);

echo $doc-&#62;saveHTML();

?&#62;

See Also

DOMDocument->saveHTMLFile()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()

Prev | Home | Next
DOMDocument->save() | Up | DOMDocument->saveHTMLFile()


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

&#60;?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc-&#62;formatOutput = true;

$root = $doc-&#62;createElement('html');
$root = $doc-&#62;appendChild($root);

$head = $doc-&#62;createElement('head');
$head = $root-&#62;appendChild($head);

$title = $doc-&#62;createElement('title');
$title = $head-&#62;appendChild($title);

$text = $doc-&#62;createTextNode('This is the title');
$text = $title-&#62;appendChild($text);

echo 'Wrote: ' . $doc-&#62;saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?&#62;

See Also

DOMDocument->saveHTML()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()

Prev | Home | Next
DOMDocument->saveHTML() | Up | DOMDocument->saveXML()


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

Version | Description
5.1.0 | Added the options parameter

Examples

Example 1. Saving a DOM tree into a string

&#60;?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc-&#62;formatOutput = true;

$root = $doc-&#62;createElement('book');
$root = $doc-&#62;appendChild($root);

$title = $doc-&#62;createElement('title');
$title = $root-&#62;appendChild($title);

$text = $doc-&#62;createTextNode('This is the title');
$text = $title-&#62;appendChild($text);

echo "Saving all the document:\n";
echo $doc-&#62;saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc-&#62;saveXML($title);

?&#62;

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>

See Also

DOMDocument->save()
DOMDocument->load()
DOMDocument->loadXML()

Prev | Home | Next
DOMDocument->saveHTMLFile() | Up | DOMDocument->schemaValidate()


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.

See Also

DOMDocument->schemaValidateSource()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->validate()

Prev | Home | Next
DOMDocument->saveXML() | Up | DOMDocument->schemaValidateSource()


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.

See Also

DOMDocument->schemaValidate()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->validate()

Prev | Home | Next
DOMDocument->schemaValidate() | Up | DOMDocument->validate()


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

&#60;?php
$dom = new DOMDocument;
$dom-&#62;Load('book.xml');
if ($dom-&#62;validate()) {
    echo "This document is valid!\n";
}
?&#62;

You can also validate your XML file while loading it:

&#60;?php
$dom = new DOMDocument;
$dom-&#62;validateOnParse = true;
$dom-&#62;Load('book.xml');
?&#62;

See Also

DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()

Prev | Home | Next
DOMDocument->schemaValidateSource() | Up | DOMDocument->xinclude()


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

&#60;?php

$xml = &#60;&#60;&#60;EOD
&#60;?xml version="1.0" ?&#62;
&#60;chapter xmlns:xi="http://www.w3.org/2001/XInclude"&#62;
 &#60;title&#62;Books of the other guy..&#60;/title&#62;
 &#60;para&#62;
  &#60;xi:include href="book.xml"&#62;
   &#60;xi:fallback&#62;
    &#60;error&#62;xinclude: book.xml not found&#60;/error&#62;
   &#60;/xi:fallback&#62;
  &#60;/xi:include&#62;
 &#60;/para&#62;
&#60;/chapter&#62;
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom-&#62;preserveWhiteSpace = false;
$dom-&#62;formatOutput = true;

// load the XML string defined above
$dom-&#62;loadXML($xml);

// substitute xincludes
$dom-&#62;xinclude();

echo $dom-&#62;saveXML();

?&#62;

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>

Prev | Home | Next
DOMDocument->validate() | Up | DOMDocumentFragment->appendXML()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom-&#62;appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element-&#62;appendChild($element_ns);
echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62;
&#60;root&#62;&#60;pr:node1 xmlns:pr="http://xyz"&#62;thisvalue&#60;/pr:node1&#62;&#60;/root&#62; */

?&#62;

See Also

DOMDocument->createElement()
DOMDocument->createElementNS()

Prev | Home | Next
DOMDocumentFragment->appendXML() | Up | DOMElement->getAttribute()


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.

See Also

DOMElement->hasAttribute()
DOMElement->setAttribute()
DOMElement->removeAttribute()

Prev | Home | Next
DOMElement->__construct() | Up | DOMElement->getAttributeNode()


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.

See Also

DOMElement->hasAttribute()
DOMElement->setAttributeNode()
DOMElement->removeAttributeNode()

Prev | Home | Next
DOMElement->getAttribute() | Up | DOMElement->getAttributeNodeNS()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->setAttributeNodeNS()
DOMElement->removeAttributeNode()

Prev | Home | Next
DOMElement->getAttributeNode() | Up | DOMElement->getAttributeNS()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->setAttributeNS()
DOMElement->removeAttributeNS()

Prev | Home | Next
DOMElement->getAttributeNodeNS() | Up | DOMElement->getElementsByTagName()


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.

See Also

DOMElement->getElementsByTagNameNS()

Prev | Home | Next
DOMElement->getAttributeNS() | Up | DOMElement->getElementsByTagNameNS()


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.

See Also

DOMElement->getElementsByTagName()

Prev | Home | Next
DOMElement->getElementsByTagName() | Up | DOMElement->hasAttribute()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->getAttribute()
DOMElement->setAttribute()
DOMElement->removeAttribute()

Prev | Home | Next
DOMElement->getElementsByTagNameNS() | Up | DOMElement->hasAttributeNS()


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.

See Also

DOMElement->hasAttribute()
DOMElement->getAttributeNS()
DOMElement->setAttributeNS()
DOMElement->removeAttributeNS()

Prev | Home | Next
DOMElement->hasAttribute() | Up | DOMElement->removeAttribute()


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.

See Also

DOMElement->hasAttribute()
DOMElement->getAttribute()
DOMElement->setAttribute()

Prev | Home | Next
DOMElement->hasAttributeNS() | Up | DOMElement->removeAttributeNode()


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.

See Also

DOMElement->hasAttribute()
DOMElement->getAttributeNode()
DOMElement->setAttributeNode()

Prev | Home | Next
DOMElement->removeAttribute() | Up | DOMElement->removeAttributeNS()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->getAttributeNS()
DOMElement->setAttributeNS()

Prev | Home | Next
DOMElement->removeAttributeNode() | Up | DOMElement->setAttribute()


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

&#60;?php
$doc = new DOMDocument("1.0");
$node = $doc-&#62;createElement("para");
$newnode = $doc-&#62;appendChild($node);
$newnode-&#62;setAttribute("align", "left");
?&#62;

See Also

DOMElement->hasAttribute()
DOMElement->getAttribute()
DOMElement->removeAttribute()

Prev | Home | Next
DOMElement->removeAttributeNS() | Up | DOMElement->setAttributeNode()


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.

See Also

DOMElement->hasAttribute()
DOMElement->getAttributeNode()
DOMElement->removeAttributeNode()

Prev | Home | Next
DOMElement->setAttribute() | Up | DOMElement->setAttributeNodeNS()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->getAttributeNodeNS()
DOMElement->removeAttributeNode()

Prev | Home | Next
DOMElement->setAttributeNode() | Up | DOMElement->setAttributeNS()


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.

See Also

DOMElement->hasAttributeNS()
DOMElement->getAttributeNS()
DOMElement->removeAttributeNS()

Prev | Home | Next
DOMElement->setAttributeNodeNS() | Up | DOMElement->setIdAttribute()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom-&#62;appendChild(new DOMElement('root'));
$entity = $element-&#62;appendChild(new DOMEntityReference('nbsp'));
echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62;&#60;root&#62;&#38;nbsp;&#60;/root&#62; */

?&#62;

See Also

DOMDocument->createEntityReference()

Prev | Home | Next
DOMElement->setIdAttributeNS() | Up | DOMImplementation->__construct()


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.

Prev | Home | Next
DOMEntityReference->__construct() | Up | DOMImplementation->createDocument()


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.

See Also

DOMDocument->__construct()
DOMImplementation->createDocumentType()

Prev | Home | Next
DOMImplementation->__construct() | Up | DOMImplementation->createDocumentType()


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

&#60;?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp-&#62;createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp-&#62;createDocument("", "", $dtd);

// Set other properties
$dom-&#62;encoding = 'UTF-8';
$dom-&#62;standalone = false;

// Create an empty element
$element = $dom-&#62;createElement('graph');

// Append the element
$dom-&#62;appendChild($element);

// Retrieve and print the document
echo $dom-&#62;saveXML();

?&#62;

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.

See Also

DOMImplementation->createDocument()

Prev | Home | Next
DOMImplementation->createDocument() | Up | DOMImplementation->hasFeature()


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

&#60;?php

$features = array(
  'Core'           =&#62; 'Core module',
  'XML'            =&#62; 'XML module',
  'HTML'           =&#62; 'HTML module',
  'Views'          =&#62; 'Views module',
  'Stylesheets'    =&#62; 'Style Sheets module',
  'CSS'            =&#62; 'CSS module',
  'CSS2'           =&#62; 'CSS2 module',
  'Events'         =&#62; 'Events module',
  'UIEvents'       =&#62; 'User interface Events module',
  'MouseEvents'    =&#62; 'Mouse Events module',
  'MutationEvents' =&#62; 'Mutation Events module',
  'HTMLEvents'     =&#62; 'HTML Events module',
  'Range'          =&#62; 'Range module',
  'Traversal'      =&#62; 'Traversal module'
);

foreach ($features as $key =&#62; $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?&#62;

See Also

DOMNode->isSupported()

Prev | Home | Next
DOMImplementation->createDocumentType() | Up | DOMNamedNodeMap->getNamedItem()


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.

See Also

DOMNamedNodeMap->getNamedItemNS()

Prev | Home | Next
DOMImplementation->hasFeature() | Up | DOMNamedNodeMap->getNamedItemNS()


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.

See Also

DOMNamedNodeMap->getNamedItem()

Prev | Home | Next
DOMNamedNodeMap->getNamedItem() | Up | DOMNamedNodeMap->item()


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).

Prev | Home | Next
DOMNamedNodeMap->getNamedItemNS() | Up | DOMNode->appendChild()


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

&#60;?php

$doc = new DOMDocument;

$node = $doc-&#62;createElement("para");
$newnode = $doc-&#62;appendChild($node);

echo $doc-&#62;saveXML();
?&#62;

See Also

DOMNode->removeChild()
DOMNode->replaceChild()

Prev | Home | Next
DOMNamedNodeMap->item() | Up | DOMNode->cloneNode()


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.

Prev | Home | Next
DOMNode->appendChild() | Up | DOMNode->hasAttributes()


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.

See Also

DOMNode->hasChildNodes()

Prev | Home | Next
DOMNode->cloneNode() | Up | DOMNode->hasChildNodes()


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.

See Also

DOMNode->hasAttributes()

Prev | Home | Next
DOMNode->hasAttributes() | Up | DOMNode->insertBefore()


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.

Prev | Home | Next
DOMNode->hasChildNodes() | Up | DOMNode->isDefaultNamespace()


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.

Prev | Home | Next
DOMNode->isDefaultNamespace() | Up | DOMNode->isSupported()


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.

See Also

DOMImplementation->hasFeature()

Prev | Home | Next
DOMNode->isSameNode() | Up | DOMNode->lookupNamespaceURI()


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.

See Also

DOMNode->lookupPrefix()

Prev | Home | Next
DOMNode->isSupported() | Up | DOMNode->lookupPrefix()


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.

See Also

DOMNode->lookupNamespaceURI()

Prev | Home | Next
DOMNode->lookupNamespaceURI() | Up | DOMNode->normalize()


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.

See Also

The DOM Specification
DOMDocument->normalizeDocument()

Prev | Home | Next
DOMNode->lookupPrefix() | Up | DOMNode->removeChild()


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

&#60;?php

$doc = new DOMDocument;
$doc-&#62;load('book.xml');

$book = $doc-&#62;documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book-&#62;getElementsByTagName('chapter')-&#62;item(0);
$oldchapter = $book-&#62;removeChild($chapter);

echo $doc-&#62;saveXML();
?&#62;

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>

See Also

DOMNode->appendChild()
DOMNode->replaceChild()

Prev | Home | Next
DOMNode->normalize() | Up | DOMNode->replaceChild()


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.

See Also

DOMNode->appendChild()
DOMNode->removeChild()

Prev | Home | Next
DOMNode->removeChild() | Up | DOMNodelist->item()


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

&#60;?php

$doc = new DOMDocument;
$doc-&#62;load('book.xml');

$items = $doc-&#62;getElementsByTagName('entry');

for ($i = 0; $i &#60; $items-&#62;length; $i++) {
    echo $items-&#62;item($i)-&#62;nodeValue . "\n";
}

?&#62;

Alternatively, you can use foreach, which is a much more convenient way:

&#60;?php

foreach ($items as $item) {
    echo $item-&#62;nodeValue . "\n";
}

?&#62;

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

Prev | Home | Next
DOMNode->replaceChild() | Up | DOMProcessingInstruction->__construct()


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

&#60;?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom-&#62;appendChild(new DOMElement('html'));
$body = $html-&#62;appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body-&#62;appendChild($pinode);
echo $dom-&#62;saveXML();

?&#62;

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

See Also

DOMDocument->createProcessingInstruction()

Prev | Home | Next
DOMNodelist->item() | Up | DOMText->__construct()


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

&#60;?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom-&#62;appendChild(new DOMElement('root'));
$text = $element-&#62;appendChild(new DOMText('root value'));
echo $dom-&#62;saveXML(); /* &#60;?xml version="1.0" encoding="iso-8859-1"?&#62;&#60;root&#62;root value&#60;/root&#62; */

?&#62;

See Also

DOMDocument->createTextNode()

Prev | Home | Next
DOMProcessingInstruction->__construct() | Up | DOMText->isWhitespaceInElementContent()


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.

Prev | Home | Next
DOMText->__construct() | Up | DOMText->splitText()


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.

Prev | Home | Next
DOMText->isWhitespaceInElementContent() | Up | DOMXPath->__construct()


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.

Prev | Home | Next
DOMText->splitText() | Up | DOMXPath->evaluate()


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

&#60;?php

$doc = new DOMDocument;

$doc-&#62;load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc-&#62;getElementsByTagName('tbody')-&#62;item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath-&#62;evaluate($query, $tbody);
echo "There are $entries english books\n";

?&#62;

The above example will output:

There are 2 english books

See Also

DOMXPath->query()

Prev | Home | Next
DOMXPath->__construct() | Up | DOMXPath->query()


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

&#60;?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc-&#62;preserveWhiteSpace = false;

$doc-&#62;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-&#62;query($query);

foreach ($entries as $entry) {
    echo "Found {$entry-&#62;previousSibling-&#62;previousSibling-&#62;nodeValue}," .
         " by {$entry-&#62;previousSibling-&#62;nodeValue}\n";
}
?&#62;

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:

&#60;?php

$doc = new DOMDocument;
$doc-&#62;preserveWhiteSpace = false;

$doc-&#62;load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc-&#62;getElementsByTagName('tbody')-&#62;item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath-&#62;query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry-&#62;previousSibling-&#62;previousSibling-&#62;nodeValue}," .
         " by {$entry-&#62;previousSibling-&#62;nodeValue}\n";
}
?&#62;

See Also

DOMXPath->evaluate()

Prev | Home | Next
DOMXPath->evaluate() | Up | DOMXPath->registerNamespace()


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.

Prev | Home | Next
DOMXPath->query() | Up | dom_import_simplexml


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()

&#60;?php

$sxe = simplexml_load_string('&#60;books&#62;&#60;book&#62;&#60;title&#62;blah&#60;/title&#62;&#60;/book&#62;&#60;/books&#62;');

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-&#62;importNode($dom_sxe, true);
$dom_sxe = $dom-&#62;appendChild($dom_sxe);

echo $dom-&#62;saveXML();

?&#62;

See Also

simplexml_import_dom()

Prev | Home | Next
DOMXPath->registerNamespace() | Up | DOM XML Functions


DOM XML Functions

PHP Manual
Prev Next

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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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 function | New function
xmldoc | domxml_open_mem()
xmldocfile | domxml_open_file()
domxml_new_xmldoc | domxml_new_doc()
domxml_dump_mem | DomDocument_dump_mem()
domxml_dump_mem_file | DomDocument_dump_file()
DomDocument_dump_mem_file | DomDocument_dump_file()
DomDocument_add_root | DomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtd | DomDocument_doctype()
DomDocument_root | DomDocument_document_element()
DomDocument_children | DomNode_child_nodes()
DomDocument_imported_node | No replacement.
DomNode_add_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_children | DomNode_child_nodes()
DomNode_parent | DomNode_parent_node()
DomNode_new_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_content | Create a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_content | Content is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_content | Content is just a text node and can be added with DomNode_append_child().

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

Constant | Value | Description
XML_ELEMENT_NODE (integer) | 1 | Node is an element
XML_ATTRIBUTE_NODE (integer) | 2 | Node is an attribute
XML_TEXT_NODE (integer) | 3 | Node is a piece of text
XML_CDATA_SECTION_NODE (integer) | 4 |
XML_ENTITY_REF_NODE (integer) | 5 |
XML_ENTITY_NODE (integer) | 6 | Node is an entity like &nbsp;
XML_PI_NODE (integer) | 7 | Node is a processing instruction
XML_COMMENT_NODE (integer) | 8 | Node is a comment
XML_DOCUMENT_NODE (integer) | 9 | Node is a document
XML_DOCUMENT_TYPE_NODE (integer) | 10 |
XML_DOCUMENT_FRAG_NODE (integer) | 11 |
XML_NOTATION_NODE (integer) | 12 |
XML_GLOBAL_NAMESPACE (integer) | 1 |
XML_LOCAL_NAMESPACE (integer) | 2 |
XML_HTML_DOCUMENT_NODE (integer) |  |
XML_DTD_NODE (integer) |  |
XML_ELEMENT_DECL_NODE (integer) |  |
XML_ATTRIBUTE_DECL_NODE (integer) |  |
XML_ENTITY_DECL_NODE (integer) |  |
XML_NAMESPACE_DECL_NODE (integer) |  |
XML_ATTRIBUTE_CDATA (integer) |  |
XML_ATTRIBUTE_ID (integer) |  |
XML_ATTRIBUTE_IDREF (integer) |  |
XML_ATTRIBUTE_IDREFS (integer) |  |
XML_ATTRIBUTE_ENTITY (integer) |  |
XML_ATTRIBUTE_NMTOKEN (integer) |  |
XML_ATTRIBUTE_NMTOKENS (integer) |  |
XML_ATTRIBUTE_ENUMERATION (integer) |  |
XML_ATTRIBUTE_NOTATION (integer) |  |
XPATH_UNDEFINED (integer) |  |
XPATH_NODESET (integer) |  |
XPATH_BOOLEAN (integer) |  |
XPATH_NUMBER (integer) |  |
XPATH_STRING (integer) |  |
XPATH_POINT (integer) |  |
XPATH_RANGE (integer) |  |
XPATH_LOCATIONSET (integer) |  |
XPATH_USERS (integer) |  |
XPATH_NUMBER (integer) |  |

Classes

The API of the module follows the DOM Level 2 standard as 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 name | Parent classes
DomAttribute | DomNode
DomCData | DomNode
DomComment | DomCData : DomNode
DomDocument | DomNode
DomDocumentType | DomNode
DomElement | DomNode
DomEntity | DomNode
DomEntityReference | DomNode
DomProcessingInstruction | DomNode
DomText | DomCData : DomNode
Parser | Currently still called DomParser
XPathContext |

Table 4. DomDocument class (DomDocument : DomNode)

Method name | Function name | Remark
doctype | DomDocument_doctype() |
document_element | DomDocument_document_element() |
create_element | DomDocument_create_element() |
create_text_node | DomDocument_create_text_node() |
create_comment | DomDocument_create_comment() |
create_cdata_section | DomDocument_create_cdata_section() |
create_processing_instruction | DomDocument_create_processing_instruction() |
create_attribute | DomDocument_create_attribute() |
create_entity_reference | DomDocument_create_entity_reference() |
get_elements_by_tagname | DomDocument_get_elements_by_tagname() |
get_element_by_id | DomDocument_get_element_by_id() |
dump_mem | DomDocument_dump_mem() | not DOM standard
dump_file | DomDocument_dump_file() | not DOM standard
html_dump_mem | DomDocument_html_dump_mem() | not DOM standard
xpath_init | xpath_init | not DOM standard
xpath_new_context | xpath_new_context | not DOM standard
xptr_new_context | xptr_new_context | not DOM standard

Table 5. DomElement class (DomElement : DomNode)

Method name | Function name | Remark
tagname | DomElement_tagname() |
get_attribute | DomElement_get_attribute() |
set_attribute | DomElement_set_attribute() |
remove_attribute | DomElement_remove_attribute() |
get_attribute_node | DomElement_get_attribute_node() |
set_attribute_node | DomElement_set_attribute_node() |
get_elements_by_tagname | DomElement_get_elements_by_tagname() |
has_attribute | DomElement_has_attribute() |

Table 6. DomNode class

Method name | Remark
DomNode_node_name() |
DomNode_node_value() |
DomNode_node_type() |
DomNode_last_child() |
DomNode_first_child() |
DomNode_child_nodes() |
DomNode_previous_sibling() |
DomNode_next_sibling() |
DomNode_parent_node() |
DomNode_owner_document() |
DomNode_insert_before() |
DomNode_append_child() |
DomNode_append_sibling() | Not in DOM standard. This function emulates the former behaviour of DomNode_append_child().
DomNode_remove_child() |
DomNode_has_child_nodes() |
DomNode_has_attributes() |
DomNode_clone_node() |
DomNode_attributes() |
DomNode_unlink_node() | Not in DOM standard
DomNode_replace_node() | Not in DOM standard
DomNode_set_content() | Not in DOM standard, deprecated
DomNode_get_content() | Not in DOM standard, deprecated
DomNode_dump_node() | Not in DOM standard
DomNode_is_blank_node() | Not in DOM standard

Table 7. DomAttribute class (DomAttribute : DomNode)

Method name |  | Remark
name | DomAttribute_name() |
value | DomAttribute_value() |
specified | DomAttribute_specified() |

Table 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)

Method name | Function name | Remark
target | DomProcessingInstruction_target() |
data | DomProcessingInstruction_data() |

Table 9. Parser class

Method name | Function name | Remark
add_chunk | Parser_add_chunk() |
end | Parser_end() |

Table 10. XPathContext class

Method name | Function name | Remark
eval | XPathContext_eval() |
eval_expression | XPathContext_eval_expression() |
register_ns | XPathContext_register_ns() |

Table 11. DomDocumentType class (DomDocumentType : DomNode)

Method name | Function name | Remark
name | DomDocumentType_name() |
entities | DomDocumentType_entities() |
notations | DomDocumentType_notations() |
public_id | DomDocumentType_public_id() |
system_id | DomDocumentType_system_id() |
internal_subset | DomDocumentType_internal_subset() |

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.

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

&#60;?php
$xmlstr = "&#60;?xml version='1.0' standalone='yes'?&#62;
&#60;!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ &#60;!ENTITY sp \"spanish\"&#62;
]&#62;
&#60;!-- lsfj  --&#62;
&#60;chapter language='en'&#62;&#60;title language='en'&#62;Title&#60;/title&#62;
 &#60;para language='ge'&#62;
  &#38;sp;
  &#60;!-- comment --&#62;
  &#60;informaltable ID='findme' language='&#38;sp;'&#62;
   &#60;tgroup cols='3'&#62;
    &#60;tbody&#62;
     &#60;row&#62;&#60;entry&#62;a1&#60;/entry&#62;&#60;entry
morerows='1'&#62;b1&#60;/entry&#62;&#60;entry&#62;c1&#60;/entry&#62;&#60;/row&#62;
&#60;row&#62;&#60;entry&#62;a2&#60;/entry&#62;&#60;entry&#62;c2&#60;/entry&#62;&#60;/row&#62;
     &#60;row&#62;&#60;entry&#62;a3&#60;/entry&#62;&#60;entry&#62;b3&#60;/entry&#62;&#60;entry&#62;c3&#60;/entry&#62;&#60;/row&#62;
    &#60;/tbody&#62;
   &#60;/tgroup&#62;
  &#60;/informaltable&#62;
 &#60;/para&#62;
&#60;/chapter&#62;";
?&#62;

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

Prev | Home | Next
dom_import_simplexml | Up | DomAttribute->name


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

Prev | Home | Next
DOM XML Functions | Up | DomAttribute->set_value


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

Prev | Home | Next
DomAttribute->set_value | Up | DomAttribute->value


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Error while parsing the document\n";
     exit;
}

$root = $dom-&#62;document_element();
$attrs = $root-&#62;attributes();

echo 'Attributes of ' . $root-&#62;node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute-&#62;name . ' : ' . $attribute-&#62;value . "\n";
}

?&#62;

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.

See Also

DomAttribute->set_value
DomAttribute->name

Prev | Home | Next
DomAttribute->specified | Up | DomDocument->add_root


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

&#60;?php
$doc = domxml_new_doc("1.0");
$root = $doc-&#62;add_root("html");
$head = $root-&#62;new_child("head", "");
$head-&#62;new_child("title", "Hier der Titel");
echo htmlentities($doc-&#62;dump_mem());
?&#62;

Prev | Home | Next
DomAttribute->value | Up | DomDocument->create_attribute


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().

Prev | Home | Next
DomDocument->add_root | Up | DomDocument->create_cdata_section


DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

Description

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().

Prev | Home | Next
DomDocument->create_attribute | Up | DomDocument->create_comment


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().

Prev | Home | Next
DomDocument->create_cdata_section | Up | DomDocument->create_element_ns


DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns -- Create new element node with an associated namespace

Description

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().

Prev | Home | Next
DomDocument->create_comment | Up | DomDocument->create_element


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().

Prev | Home | Next
DomDocument->create_element_ns | Up | DomDocument->create_entity_reference


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().

Prev | Home | Next
DomDocument->create_element | Up | DomDocument->create_processing_instruction


DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

Description

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().

Prev | Home | Next
DomDocument->create_entity_reference | Up | DomDocument->create_text_node


DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

Description

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().

Prev | Home | Next
DomDocument->create_processing_instruction | Up | DomDocument->doctype


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.

Prev | Home | Next
DomDocument->create_text_node | Up | DomDocument->document_element


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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom-&#62;document_element();
print_r($root);
?&#62;

The above example will output:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

Prev | Home | Next
DomDocument->doctype | Up | DomDocument->dump_file


DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file -- Dumps the internal XML tree back into a file

Description

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

Example 1. Creating a simple HTML document header

&#60;?php
$doc = domxml_new_doc("1.0");
$root = $doc-&#62;create_element("HTML");
$root = $doc-&#62;append_child($root);
$head = $doc-&#62;create_element("HEAD");
$head = $root-&#62;append_child($head);
$title = $doc-&#62;create_element("TITLE");
$title = $head-&#62;append_child($title);
$text = $doc-&#62;create_text_node("This is the title");
$text = $title-&#62;append_child($text);
$doc-&#62;dump_file("/tmp/test.xml", false, true);
?&#62;

See also domdocument_dump_mem(), and domdocument_html_dump_mem().

Prev | Home | Next
DomDocument->document_element | Up | DomDocument->dump_mem


DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem -- Dumps the internal XML tree back into a string

Description

string DomDocument->dump_mem ( [bool format [, string encoding]] )

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

&#60;?php
$doc = domxml_new_doc("1.0");
$root = $doc-&#62;create_element("HTML");
$root = $doc-&#62;append_child($root);
$head = $doc-&#62;create_element("HEAD");
$head = $root-&#62;append_child($head);
$title = $doc-&#62;create_element("TITLE");
$title = $head-&#62;append_child($title);
$text = $doc-&#62;create_text_node("This is the title");
$text = $title-&#62;append_child($text);
echo "&#60;PRE&#62;";
echo htmlentities($doc-&#62;dump_mem(true));
echo "&#60;/PRE&#62;";
?&#62;

Note: The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), and domdocument_html_dump_mem().

Prev | Home | Next
DomDocument->dump_file | Up | DomDocument->get_element_by_id


DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id -- Searches for an element with a certain id

Description

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()

Prev | Home | Next
DomDocument->dump_mem | Up | 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()

Prev | Home | Next
DomDocument->get_element_by_id | Up | DomDocument->html_dump_mem


DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem -- Dumps the internal XML tree back into a string as HTML

Description

string DomDocument->html_dump_mem ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Example 1. Creating a simple HTML document header

&#60;?php

// Creates the document
$doc = domxml_new_doc("1.0");

$root = $doc-&#62;create_element("html");
$root = $doc-&#62;append_child($root);

$head = $doc-&#62;create_element("head");
$head = $root-&#62;append_child($head);

$title = $doc-&#62;create_element("title");
$title = $head-&#62;append_child($title);

$text = $doc-&#62;create_text_node("This is the title");
$text = $title-&#62;append_child($text);

echo $doc-&#62;html_dump_mem();
?&#62;

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().

Prev | Home | Next
DomDocument->get_elements_by_tagname | Up | DomDocument->xinclude


DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude -- Substitutes XIncludes in a DomDocument Object

Description

int DomDocument->xinclude ( void )

This function substitutes XIncludes in a DomDocument object.

Example 1. Substituting Xincludes

&#60;?php

// include.xml contains :
// &#60;child&#62;test&#60;/child&#62;

$xml = '&#60;?xml version="1.0"?&#62;
&#60;root xmlns:xi="http://www.w3.org/2001/XInclude"&#62;
  &#60;xi:include href="include.xml"&#62;
    &#60;xi:fallback&#62;
      &#60;error&#62;xinclude: include.xml not found&#60;/error&#62;
    &#60;/xi:fallback&#62;
  &#60;/xi:include&#62;
&#60;/root&#62;';

$domxml = domxml_open_mem($xml);
$domxml-&#62;xinclude();

echo $domxml-&#62;dump_mem();

?&#62;

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>

Prev | Home | Next
DomDocument->html_dump_mem | Up | DomDocumentType->entities()


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.

Prev | Home | Next
DomDocument->xinclude | Up | DomDocumentType->internal_subset()


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.

Prev | Home | Next
DomDocumentType->entities() | Up | DomDocumentType->name()


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$doctype = $dom-&#62;doctype();
echo $doctype-&#62;name(); // chapter

?&#62;

Migrating to PHP 5

Use the name property of the DOMDocumentType object.

Prev | Home | Next
DomDocumentType->internal_subset() | Up | DomDocumentType->notations()


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.

Prev | Home | Next
DomDocumentType->name() | Up | DomDocumentType->public_id()


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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom-&#62;doctype();
echo $doctype-&#62;public_id();
?&#62;

Migrating to PHP 5

Use the publicId property of the DOMDocumentType object.

Prev | Home | Next
DomDocumentType->notations() | Up | DomDocumentType->system_id()


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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom-&#62;doctype();
echo $doctype-&#62;system_id();
?&#62;

The above example will output:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

Migrating to PHP 5

Use the systemId property of the DOMDocumentType object.

Prev | Home | Next
DomDocumentType->public_id() | Up | DomElement->get_attribute_node()


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom-&#62;document_element();
if ($attribute = $root-&#62;get_attribute_node('language')) {
    echo 'Language is: ' . $attribute-&#62;value() . "\n";
}

?&#62;

Migrating to PHP 5

Use DOMElement->getAttributeNode().

See Also

DomElement->get_attribute()
DomElement->set_attribute()

Prev | Home | Next
DomDocumentType->system_id() | Up | DomElement->get_attribute()


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

// get chapter
$root = $dom-&#62;document_element();
echo $root-&#62;get_attribute('language'); // en

?&#62;

Migrating to PHP 5

Use DOMElement->getAttribute().

See Also

DomElement->get_attribute_node()
DomElement->set_attribute()

Prev | Home | Next
DomElement->get_attribute_node() | Up | DomElement->get_elements_by_tagname()


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

&#60;?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom-&#62;document_element();

$node_array = $root-&#62;get_elements_by_tagname('element');

foreach ($node_array as $node) {
    echo ' - ' . $node-&#62;get_content() . "\n";
}

?&#62;

Migrating to PHP 5

Use DOMElement->getElementsByTagName().

Prev | Home | Next
DomElement->get_attribute() | Up | DomElement->has_attribute()


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom-&#62;document_element();

$buffer = '&#60;html';
if ($root-&#62;has_attribute('language')) {
    $buffer .= 'lang="' . $root-&#62;get_attribute('language') . '"';
}
$buffer .= '&#62;';

?&#62;

Migrating to PHP 5

Use DOMElement->hasAttribute().

Prev | Home | Next
DomElement->get_elements_by_tagname() | Up | DomElement->remove_attribute()


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().

Prev | Home | Next
DomElement->has_attribute() | Up | DomElement->set_attribute_node()


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

&#60;?php
$doc = domxml_new_doc("1.0");
$node = $doc-&#62;create_element("para");
$newnode = $doc-&#62;append_child($node);
$newnode-&#62;set_attribute("align", "left");
?&#62;

Migrating to PHP 5

Use DOMElement->setAttribute().

See Also

DomElement->get_attribute_node()
DomElement->get_attribute()

Prev | Home | Next
DomElement->set_attribute_node() | Up | DomElement->tagname()


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

&#60;?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom-&#62;document_element();
echo $root-&#62;tagname();   // chapter
echo $root-&#62;tagname;     // chapter
echo $root-&#62;node_name(); // chapter

?&#62;

Migrating to PHP 5

Use the tagName property of the DOMElement object.

Prev | Home | Next
DomElement->set_attribute() | Up | DomNode->add_namespace


DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace -- Adds a namespace declaration to a node

Description

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.

See Also

DomDocument->create_element_ns
DomNode->set_namespace

Prev | Home | Next
DomElement->tagname() | Up | DomNode->append_child


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

Version | Description
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

&#60;?php
$doc = domxml_new_doc("1.0");
$node = $doc-&#62;create_element("para");
$newnode = $doc-&#62;append_child($node);
$newnode-&#62;set_attribute("align", "left");
?&#62;

The above example could also be written as the following:

Example 2. Adding a child

&#60;?php
$doc = domxml_new_doc("1.0");
$node = $doc-&#62;create_element("para");
$node-&#62;set_attribute("align", "left");
$newnode = $doc-&#62;append_child($node);
?&#62;

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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom-&#62;get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element-&#62;parent_node();
$newnode = $parent-&#62;append_child($element);
$children = $newnode-&#62;children();
$attr = $children[1]-&#62;set_attribute("align", "left");

$xmlfile = $dom-&#62;dump_mem();
echo htmlentities($xmlfile);
?&#62;

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().

See Also

DomNode->insert_before
DomNode->clone_node

Prev | Home | Next
DomNode->add_namespace | Up | DomNode->append_sibling


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().

Prev | Home | Next
DomNode->append_child | Up | DomNode->attributes


DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes -- Returns list of attributes

Description

array DomNode->attributes ( void )

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

Prev | Home | Next
DomNode->append_sibling | Up | DomNode->child_nodes


DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes -- Returns children of node

Description

array DomNode->child_nodes ( void )

Returns all children of the node.

See also domnode_next_sibling(), and domnode_previous_sibling().

Prev | Home | Next
DomNode->attributes | Up | DomNode->clone_node


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.

Prev | Home | Next
DomNode->child_nodes | Up | DomNode->dump_node


DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node -- Dumps a single node

Description

string DomNode->dump_node ( void )

Warning

This function is currently not documented; only the argument list is available.

See also domdocument_dump_mem().

Prev | Home | Next
DomNode->clone_node | Up | DomNode->first_child


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().

Prev | Home | Next
DomNode->dump_node | Up | DomNode->get_content


DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content -- Gets content of node

Description

string DomNode->get_content ( void )

This function returns the content of the actual node.

Example 1. Getting a content

&#60;?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom-&#62;document_element();

$node_array = $root-&#62;get_elements_by_tagname("element");

for ($i = 0; $i&#60;count($node_array); $i++) {
    $node = $node_array[$i];
    echo "The element[$i] is: " . $node-&#62;get_content();
}

?&#62;

Prev | Home | Next
DomNode->first_child | Up | DomNode->has_attributes


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().

Prev | Home | Next
DomNode->get_content | Up | 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().

Prev | Home | Next
DomNode->has_attributes | Up | DomNode->insert_before


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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom-&#62;get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element-&#62;insert_before($element, $element);
$children = $newnode-&#62;children();
$attr = $children[1]-&#62;set_attribute("align", "left");

echo "&#60;pre&#62;";
$xmlfile = $dom-&#62;dump_mem();
echo htmlentities($xmlfile);
echo "&#60;/pre&#62;";
?&#62;

See also domnode_append_child().

Prev | Home | Next
DomNode->has_child_nodes | Up | DomNode->is_blank_node


DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node -- Checks if node is blank

Description

bool DomNode->is_blank_node ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DomNode->insert_before | Up | DomNode->last_child


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().

Prev | Home | Next
DomNode->is_blank_node | Up | DomNode->next_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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom-&#62;get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element-&#62;first_child();

while ($child) {
   print_r($child);
   $child = $child-&#62;next_sibling();
}
?&#62;

See also domnode_previous_sibling().

Prev | Home | Next
DomNode->last_child | Up | DomNode->node_name


DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name -- Returns name of node

Description

string DomNode->node_name ( void )

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

Table 1. Meaning of value

Type | Meaning
DomAttribute | value of attribute
DomAttribute |
DomCDataSection | #cdata-section
DomComment | #comment
DomDocument | #document
DomDocumentType | document type name
DomElement | tag name
DomEntity | name of entity
DomEntityReference | name of entity reference
DomNotation | notation name
DomProcessingInstruction | target
DomText | #text

Prev | Home | Next
DomNode->next_sibling | Up | DomNode->node_type


DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type -- Returns type of node

Description

int DomNode->node_type ( void )

Returns the type of the node. All possible types are listed in the table in the introduction.

Example 1.

&#60;?php

include 'example.inc';

$dom = domxml_open_mem($xmlstr);

$chapter = $dom-&#62;document_element();

// Let's see the elements contained in chapter
foreach($chapter-&#62;child_nodes() as $node) {
  if ($node-&#62;node_type() == XML_ELEMENT_NODE) {
    echo $node-&#62;node_name() . "\n";
  }
}

?&#62;

The above example will output:

title
para

Prev | Home | Next
DomNode->node_name | Up | DomNode->node_value


DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value -- Returns value of a node

Description

string DomNode->node_value ( void )

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

Table 1. Meaning of value

Type | Meaning
DomAttribute | value of attribute
DomAttribute |
DomCDataSection | content
DomComment | content of comment
DomDocument | null
DomDocumentType | null
DomElement | null
DomEntity | null
DomEntityReference | null
DomNotation | null
DomProcessingInstruction | entire content without target
DomText | content of text

Prev | Home | Next
DomNode->node_type | Up | DomNode->owner_document


DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document -- Returns the document this node belongs to

Description

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

&#60;?php
$doc = domxml_new_doc("1.0");
$node = $doc-&#62;create_element("para");
$node = $doc-&#62;append_child($node);
$children = $doc-&#62;children();
print_r($children);

$doc2 = $node-&#62;owner_document();
$children = $doc2-&#62;children();
print_r($children);
?&#62;

See also domnode_insert_before().

Prev | Home | Next
DomNode->node_value | Up | DomNode->parent_node


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

&#60;?php
$doc = domxml_new_doc("1.0");
$node = $doc-&#62;create_element("para");
$node = $doc-&#62;append_child($node);
$children = $doc-&#62;children();
print_r($children);

$doc2 = $node-&#62;parent_node();
$children = $doc2-&#62;children();
print_r($children);
?&#62;

Prev | Home | Next
DomNode->owner_document | Up | DomNode->prefix


DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix -- Returns name space prefix of node

Description

string DomNode->prefix ( void )

Returns the name space prefix of the node.

Prev | Home | Next
DomNode->parent_node | Up | DomNode->previous_sibling


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().

Prev | Home | Next
DomNode->prefix | Up | DomNode->remove_child


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

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom-&#62;get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element-&#62;child_nodes();
$child = $element-&#62;remove_child($children[0]);

echo "&#60;PRE&#62;";
$xmlfile = $dom-&#62;dump_mem(true);
echo htmlentities($xmlfile);
echo "&#60;/PRE&#62;";
?&#62;

See also domnode_append_child().

Prev | Home | Next
DomNode->previous_sibling | Up | DomNode->replace_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()

Prev | Home | Next
DomNode->remove_child | Up | DomNode->replace_node


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()

Prev | Home | Next
DomNode->replace_child | Up | DomNode->set_content


DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content -- Sets content of node

Description

bool DomNode->set_content ( string content )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DomNode->replace_node | Up | DomNode->set_name


DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name -- Sets name of node

Description

bool DomNode->set_name ( void )

Sets name of node.

See also domnode_node_name().

Prev | Home | Next
DomNode->set_content | Up | DomNode->set_namespace


DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace -- Sets namespace of a node

Description

void DomNode->set_namespace ( string uri [, string prefix] )

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), and domnode_add_namespace()

Prev | Home | Next
DomNode->set_name | Up | DomNode->unlink_node


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.

Prev | Home | Next
DomNode->set_namespace | Up | DomProcessingInstruction->data


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.

Prev | Home | Next
DomNode->unlink_node | Up | DomProcessingInstruction->target


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.

Prev | Home | Next
DomProcessingInstruction->data | Up | DomXsltStylesheet->process()


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.

Migrating to PHP 5

Use XSLTProcessor::setParameter and XSLTProcessor::transformToDoc.

ChangeLog

Version | Description
4.3.0 | The profile_filename parameter was added.

See Also

domxml_xslt_stylesheet()
domxml_xslt_stylesheet_file()
domxml_xslt_stylesheet_doc()

Prev | Home | Next
DomProcessingInstruction->target | Up | DomXsltStylesheet->result_dump_file()


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

&#60;?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc-&#62;process($xmldoc);
echo $xsldoc-&#62;result_dump_file($result, "filename");
?&#62;

See Also

DomXsltStylesheet->result_dump_mem()
DomXsltStylesheet->process()

Prev | Home | Next
DomXsltStylesheet->process() | Up | DomXsltStylesheet->result_dump_mem()


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

&#60;?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc-&#62;process($xmldoc);
echo $xsldoc-&#62;result_dump_mem($result);
?&#62;

See Also

DomXsltStylesheet->result_dump_file()
DomXsltStylesheet->process()

Prev | Home | Next
DomXsltStylesheet->result_dump_file() | Up | domxml_new_doc


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.

Prev | Home | Next
DomXsltStylesheet->result_dump_mem() | Up | domxml_open_file


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

&#60;?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom-&#62;document_element();
?&#62;

ChangeLog

Version | Description
4.3.0 | The parameters mode and error were added.

See Also

domxml_open_mem()
domxml_new_doc()

Prev | Home | Next
domxml_new_doc | Up | domxml_open_mem


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.

Examples

Example 1. Opening an XML document in a string

&#60;?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom-&#62;document_element();
?&#62;

See Also

domxml_open_file()
domxml_new_doc()

Prev | Home | Next
domxml_open_file | Up | domxml_version


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

&#60;?php

echo domxml_version();

?&#62;

The above example will output something similar to:

20607

Prev | Home | Next
domxml_open_mem | Up | domxml_xmltree


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.

Prev | Home | Next
domxml_version | Up | domxml_xslt_stylesheet_doc


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.

See Also

DomXsltStylesheet->process()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_file()

Prev | Home | Next
domxml_xmltree | Up | domxml_xslt_stylesheet_file


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.

See Also

DomXsltStylesheet->process()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_doc()

Prev | Home | Next
domxml_xslt_stylesheet_doc | Up | domxml_xslt_stylesheet


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.

See Also

DomXsltStylesheet->process()
domxml_xslt_stylesheet_file()
domxml_xslt_stylesheet_doc()

Prev | Home | Next
domxml_xslt_stylesheet_file | Up | domxml_xslt_version


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

&#60;?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'));

?&#62;

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().

Prev | Home | Next
domxml_xslt_version | Up | 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().

Prev | Home | Next
xpath_eval_expression | Up | 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().

Prev | Home | Next
xpath_eval | Up | xpath_register_ns_auto


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.

Prev | Home | Next
xpath_register_ns | Up | xptr_new_context


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.

Prev | Home | Next
xptr_eval | Up | enchant Functions


.NET Functions

PHP Manual
Prev Next

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

Prev | Home | Next
Function Reference | Up | dotnet_load


dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]] )

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.

Prev | Home | Next
.NET Functions | Up | Apache-specific Functions


Error Handling and Logging Functions

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
error_reporting | NULL | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Available since PHP 4.0.3.
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
track_errors | "0" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2.
docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0.
docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2.
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
warn_plus_overloading | NULL | PHP_INI?? |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

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

Value | Constant | Description | Note
1 | E_ERROR (integer) | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. |
2 | E_WARNING (integer) | Run-time warnings (non-fatal errors). Execution of the script is not halted. |
4 | E_PARSE (integer) | Compile-time parse errors. Parse errors should only be generated by the parser. |
8 | E_NOTICE (integer) | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. |
16 | E_CORE_ERROR (integer) | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. | since PHP 4
32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. | since PHP 4
64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. | since PHP 4
128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. | since PHP 4
256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
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
8191 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT in PHP < 6. | 6143 in PHP 5.2 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

&#60;?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              =&#62; 'Error',
                E_WARNING            =&#62; 'Warning',
                E_PARSE              =&#62; 'Parsing Error',
                E_NOTICE             =&#62; 'Notice',
                E_CORE_ERROR         =&#62; 'Core Error',
                E_CORE_WARNING       =&#62; 'Core Warning',
                E_COMPILE_ERROR      =&#62; 'Compile Error',
                E_COMPILE_WARNING    =&#62; 'Compile Warning',
                E_USER_ERROR         =&#62; 'User Error',
                E_USER_WARNING       =&#62; 'User Warning',
                E_USER_NOTICE        =&#62; 'User Notice',
                E_STRICT             =&#62; 'Runtime Notice',
                E_RECOVERABLE_ERROR  =&#62; '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 = "&#60;errorentry&#62;\n";
    $err .= "\t&#60;datetime&#62;" . $dt . "&#60;/datetime&#62;\n";
    $err .= "\t&#60;errornum&#62;" . $errno . "&#60;/errornum&#62;\n";
    $err .= "\t&#60;errortype&#62;" . $errortype[$errno] . "&#60;/errortype&#62;\n";
    $err .= "\t&#60;errormsg&#62;" . $errmsg . "&#60;/errormsg&#62;\n";
    $err .= "\t&#60;scriptname&#62;" . $filename . "&#60;/scriptname&#62;\n";
    $err .= "\t&#60;scriptlinenum&#62;" . $linenum . "&#60;/scriptlinenum&#62;\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t&#60;vartrace&#62;" . wddx_serialize_value($vars, "Variables") . "&#60;/vartrace&#62;\n";
    }
    $err .= "&#60;/errorentry&#62;\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&#60;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";

?&#62;

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()

Prev | Home | Next
enchant_dict_suggest | Up | debug_backtrace


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()

Name | Type | Description
function | string | The current function name. See also __FUNCTION__.
line | integer | The current line number. See also __LINE__.
file | string | The current file name. See also __FILE__.
class | string | The current class name. See also __CLASS__
object | object | The current object.
type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

ChangeLog

Version | Description
5.1.1 | Added the current object as a possible return element.

Examples

Example 1. debug_backtrace() example

&#60;?php
// filename: a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?&#62;

&#60;?php
// filename: b.php
include_once '/tmp/a.php';
?&#62;

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"
  }
}

See Also

trigger_error()
debug_print_backtrace()

Prev | Home | Next
Error Handling and Logging Functions | Up | debug_print_backtrace


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

&#60;?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?&#62;
&#60;?php
// test.php file
// this is the file you should run

include 'include.php';
?&#62;

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]

See Also

debug_backtrace()

Prev | Home | Next
debug_backtrace | Up | error_get_last


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

&#60;?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");
?&#62;

Prev | Home | Next
error_get_last | Up | error_reporting


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

value | constant
1 | E_ERROR
2 | E_WARNING
4 | E_PARSE
8 | E_NOTICE
16 | E_CORE_ERROR
32 | E_CORE_WARNING
64 | E_COMPILE_ERROR
128 | E_COMPILE_WARNING
256 | E_USER_ERROR
512 | E_USER_WARNING
1024 | E_USER_NOTICE
6143 | E_ALL
2048 | E_STRICT
4096 | E_RECOVERABLE_ERROR

Return Values

Returns the old error_reporting level.

ChangeLog

Version | Description
5.0.0 | E_STRICT introduced (not part of E_ALL).
5.2.0 | E_RECOVERABLE_ERROR introduced.
6 | E_STRICT became part of E_ALL.

Examples

Example 1. error_reporting() examples

&#60;?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);

?&#62;

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()

Prev | Home | Next
error_log | Up | restore_error_handler


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.

&#60;?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?&#62;

The above example will output:

Invalid serialized value.

Notes

Note: Calling restore_error_handler() from the error_handler function is ignored.

See Also

error_reporting()
set_error_handler()
restore_exception_handler()
trigger_error()

Prev | Home | Next
error_reporting | Up | restore_exception_handler


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.

See Also

set_exception_handler()
set_error_handler()
restore_error_handler()
error_reporting()

Prev | Home | Next
restore_error_handler | Up | set_error_handler


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

Version | Description
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:

&#60;?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
    case E_USER_ERROR:
        echo "&#60;b&#62;My ERROR&#60;/b&#62; [$errno] $errstr&#60;br /&#62;\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")&#60;br /&#62;\n";
        echo "Aborting...&#60;br /&#62;\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "&#60;b&#62;My WARNING&#60;/b&#62; [$errno] $errstr&#60;br /&#62;\n";
        break;

    case E_USER_NOTICE:
        echo "&#60;b&#62;My NOTICE&#60;/b&#62; [$errno] $errstr&#60;br /&#62;\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr&#60;br /&#62;\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 &#60;= 0) {
        trigger_error("log(x) for x &#60;= 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 =&#62; $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 &#60;= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?&#62;

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 />

See Also

error_reporting()
restore_error_handler()
trigger_error()
error level constants
information about the callback type

Prev | Home | Next
restore_exception_handler | Up | set_exception_handler


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

&#60;?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception-&#62;getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?&#62;

See Also

restore_exception_handler(),
restore_error_handler(),
error_reporting(),
information about the callback type,  and
PHP 5 Exceptions.

Prev | Home | Next
set_error_handler | Up | trigger_error


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.

&#60;?php
if (assert($divisor == 0)) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?&#62;

See Also

error_reporting()
set_error_handler()
restore_error_handler()
The error level constants

Prev | Home | Next
set_exception_handler | Up | user_error


user_error

(PHP 4, PHP 5)

user_error -- Alias of trigger_error()

Description

This function is an alias of: trigger_error().

Prev | Home | Next
trigger_error | Up | Exif Functions


Program Execution Functions

PHP Manual
Prev Next

CXXVIII. Program Execution Functions

Introduction

Those functions provide means to execute commands on the system itself, and means to secure such commands.

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 defines a process resource, returned by proc_open().

Predefined Constants

This extension has no constants defined.

See Also

These functions are also closely related to the backtick operator. Also, while in safe mode you must consider the safe_mode_exec_dir directive.

Table of Contents
escapeshellarg -- Escape a string to be used as a shell argument
escapeshellcmd -- Escape shell metacharacters
exec -- Execute an external program
passthru -- Execute an external program and display raw output
proc_close -- Close a process opened by proc_open() and return the exit code of that process.
proc_get_status -- Get information about a process opened by proc_open()
proc_nice -- Change the priority of the current process
proc_open -- Execute a command and open file pointers for input/output
proc_terminate -- Kills a process opened by proc_open
shell_exec -- Execute command via shell and return the complete output as a string
system -- Execute an external program and display the output

Prev | Home | Next
printer_write | Up | escapeshellarg


escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellarg -- Escape a string to be used as a shell argument

Description

string escapeshellarg ( string arg )

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

Parameters

arg

The argument that will be escaped.

Return Values

The escaped string.

Examples

Example 1. escapeshellarg() example

&#60;?php
system('ls '.escapeshellarg($dir));
?&#62;

See Also

escapeshellcmd()
exec()
popen()
system()
backtick operator

Prev | Home | Next
Program Execution Functions | Up | escapeshellcmd


escapeshellcmd

(PHP 3, PHP 4, PHP 5)

escapeshellcmd -- Escape shell metacharacters

Description

string escapeshellcmd ( string command )

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % are replaced by a space instead.

Parameters

command

The command that will be escaped.

Return Values

The escaped string.

Examples

Example 1. escapeshellcmd() example

&#60;?php
$e = escapeshellcmd($userinput);

// here we don't care if $e has spaces
system("echo $e");
$f = escapeshellcmd($filename);

// and here we do, so we use quotes
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\"");
?&#62;

See Also

escapeshellarg()
exec()
popen()
system()
backtick operator

Prev | Home | Next
escapeshellarg | Up | exec


exec

(PHP 3, PHP 4, PHP 5)

exec -- Execute an external program

Description

string exec ( string command [, array &output [, int &return_var]] )

exec() executes the given command.

Parameters

command

The command that will be executed.

output

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

return_var

If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

To get the output of the executed command, be sure to set and use the output parameter.

Examples

Example 1. An exec() example

&#60;?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?&#62;

Notes

Warning

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Note: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

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

system()
passthru()
escapeshellcmd()
pcntl_exec()
system()
backtick operator

Prev | Home | Next
escapeshellcmd | Up | passthru


passthru

(PHP 3, PHP 4, PHP 5)

passthru -- Execute an external program and display raw output

Description

void passthru ( string command [, int &return_var] )

The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, the return status of the Unix command will be placed here.

Notes

Warning

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Note: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

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

exec()
system()
popen()
escapeshellcmd()
backtick operator

Prev | Home | Next
exec | Up | proc_close


proc_close

(PHP 4 >= 4.3.0, PHP 5)

proc_close -- Close a process opened by proc_open() and return the exit code of that process.

Description

int proc_close ( resource process )

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns its exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

Parameters

process

The proc_open() resource that will be closed.

Prev | Home | Next
passthru | Up | proc_get_status


proc_get_status

(PHP 5)

proc_get_status -- Get information about a process opened by proc_open()

Description

array proc_get_status ( resource process )

proc_get_status() fetches data about a process opened using proc_open().

Parameters

process

The proc_open() resource that will be evaluated.

Return Values

An array of collected information on success, and FALSE on failure. The returned array contains the following elements:

element | type | description
command | string | The command string that was passed to proc_open().
pid | int | process id
running | bool | TRUE if the process is still running, FALSE if it has terminated.
signaled | bool | TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stopped | bool | TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcode | int | The exit code returned by the process (which is only meaningful if running is FALSE). Only first call of this function return real value, next calls return -1.
termsig | int | The number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE).
stopsig | int | The number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE).

See Also

proc_open()

Prev | Home | Next
proc_close | Up | proc_nice


proc_nice

(PHP 5)

proc_nice -- Change the priority of the current process

Description

bool proc_nice ( int increment )

proc_nice() changes the priority of the current process by the amount specified in increment. A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.

proc_nice() is not related to proc_open() and its associated functions in any way.

Parameters

increment

The increment value of the priority change.

Return Values

Returns TRUE on success or FALSE on failure. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Notes

Availability: proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.

Prev | Home | Next
proc_get_status | Up | proc_open


proc_open

(PHP 4 >= 4.3.0, PHP 5)

proc_open -- Execute a command and open file pointers for input/output

Description

resource proc_open ( string cmd, array descriptorspec, array &pipes [, string cwd [, array env [, array other_options]]] )

proc_open() is similar to popen() but provides a much greater degree of control over the program execution.

Parameters

cmd

The command to execute

descriptorspec

An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.

The currently supported pipe types are file and pipe .

The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

pipes

Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.

cwd

The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)

env

An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process

other_options

Allows you to specify additional options. Currently supported options include:

suppress_errors (windows only): suppresses errors generated by this function when it's set to TRUE
bypass_shell (windows only): bypass cmd.exe shell when set to TRUE
context: stream context used when opening files (created with stream_context_create())
binary_pipes: open pipes in binary mode, instead of using the usual stream_encoding

Return Values

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

ChangeLog

Version | Description
6.0.0 | Added the context and binary_pipes options to the other_options parameter.
5.2.1 | Added the bypass_shell option to the other_options parameter.
5.0.0 | Added the cwd, env and other_options parameters.

Examples

Example 1. A proc_open() example

&#60;?php
$descriptorspec = array(
   0 =&#62; array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 =&#62; array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 =&#62; array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' =&#62; 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 =&#62; writeable handle connected to child stdin
    // 1 =&#62; readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '&#60;?php print_r($_ENV); ?&#62;');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?&#62;

The above example will output something similar to:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Notes

Note: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Note: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See Also

popen()
exec()
system()
passthru()
stream_select()
The backtick operator

Prev | Home | Next
proc_nice | Up | proc_terminate


proc_terminate

(PHP 5)

proc_terminate -- Kills a process opened by proc_open

Description

bool proc_terminate ( resource process [, int signal] )

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

The optional signal is only useful on POSIX operating systems; you may specify a signal to send to the process using the kill(2) system call. The default is SIGTERM.

proc_terminate() allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the proc_get_status() function. However this is only possible with PHP 5.2.2 or newer, as previous versions destroyed the given process resource.

See Also

proc_open()
proc_close()
proc_get_status()

Prev | Home | Next
proc_open | Up | shell_exec


shell_exec

(PHP 4, PHP 5)

shell_exec -- Execute command via shell and return the complete output as a string

Description

string shell_exec ( string cmd )

This function is identical to the backtick operator.

Parameters

cmd

The command that will be executed.

Return Values

The output from the executed command.

Examples

Example 1. A shell_exec() example

&#60;?php
$output = shell_exec('ls -lart');
echo "&#60;pre&#62;$output&#60;/pre&#62;";
?&#62;

Notes

Note: This function is disabled in safe mode.

See Also

exec()
escapeshellcmd()

Prev | Home | Next
proc_terminate | Up | system


system

(PHP 3, PHP 4, PHP 5)

system -- Execute an external program and display the output

Description

string system ( string command [, int &return_var] )

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

Return Values

Returns the last line of the command output on success, and FALSE on failure.

Examples

Example 1. system() example

&#60;?php
echo '&#60;pre&#62;';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
&#60;/pre&#62;
&#60;hr /&#62;Last line of the output: ' . $last_line . '
&#60;hr /&#62;Return value: ' . $retval;
?&#62;

Notes

Warning

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Note: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

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

exec()
passthru()
popen()
escapeshellcmd()
pcntl_exec()
backtick operator

Prev | Home | Next
shell_exec | Up | PostScript document creation


Exif Functions

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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()

Prev | Home | Next
user_error | Up | exif_imagetype


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

Version | Description
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0 | Support for SWC

Predefined Constants

The following constants are defined, and represent possible exif_imagetype() return values:

Table 1. Imagetype Constants

Value | Constant
1 | IMAGETYPE_GIF
2 | IMAGETYPE_JPEG
3 | IMAGETYPE_PNG
4 | IMAGETYPE_SWF
5 | IMAGETYPE_PSD
6 | IMAGETYPE_BMP
7 | IMAGETYPE_TIFF_II (intel byte order)
8 | IMAGETYPE_TIFF_MM (motorola byte order)
9 | IMAGETYPE_JPC
10 | IMAGETYPE_JP2
11 | IMAGETYPE_JPX
12 | IMAGETYPE_JB2
13 | IMAGETYPE_SWC
14 | IMAGETYPE_IFF
15 | IMAGETYPE_WBMP
16 | IMAGETYPE_XBM

Examples

Example 1. exif_imagetype() example

&#60;?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?&#62;

See Also

getimagesize()

Prev | Home | Next
Exif Functions | Up | exif_read_data


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.

FILE | FileName, 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_TAG | Any information that has a Tag e.g. IFD0, EXIF, ...
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENT | Comment headers of JPEG images.
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays

Specifies whether or not each section becomes an array. The sections 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

Version | Description
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

&#60;?php
echo "test1.jpg:&#60;br /&#62;\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.&#60;br /&#62;\n" : "Image contains headers&#60;br /&#62;\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:&#60;br /&#62;\n";
foreach ($exif as $key =&#62; $section) {
    foreach ($section as $name =&#62; $val) {
        echo "$key.$name: $val&#60;br /&#62;\n";
    }
}
?&#62;

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

See Also

exif_thumbnail()
getimagesize()

Prev | Home | Next
exif_imagetype | Up | exif_tagname


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.

See Also

exif_imagetype()

Prev | Home | Next
exif_read_data | Up | exif_thumbnail


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

Version | Description
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

&#60;?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';
}
?&#62;

See Also

exif_read_data()
image_type_to_mime_type()

Prev | Home | Next
exif_tagname | Up | read_exif_data


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().

Prev | Home | Next
exif_thumbnail | Up | Expect Functions


File Alteration Monitor Functions

PHP Manual
Prev Next

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

Constant | Description
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) | A file or directory was deleted or renamed.
FAMStartExecuting (integer) | An executable file started executing.
FAMStopExecuting (integer) | An executable file that was running finished.
FAMCreated (integer) | A file was created in a directory.
FAMMoved (integer) | This event never occurs.
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor().
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) | Event after the last FAMEExists event.
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

Prev | Home | Next
expect_popen | Up | fam_cancel_monitor


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.

See Also

fam_monitor_file()
fam_monitor_directory()
fam_monitor_collection()
fam_suspend_monitor()

Prev | Home | Next
File Alteration Monitor Functions | Up | fam_close


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()

Prev | Home | Next
fam_cancel_monitor | Up | fam_monitor_collection


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.

See Also

fam_monitor_file()
fam_monitor_directory()
fam_cancel_monitor()
fam_suspend_monitor()
fam_resume_monitor()

Prev | Home | Next
fam_close | Up | fam_monitor_directory


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.

See Also

fam_monitor_file()
fam_monitor_collection()
fam_cancel_monitor()
fam_suspend_monitor()
fam_resume_monitor()

Prev | Home | Next
fam_monitor_collection | Up | fam_monitor_file


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.

See Also

fam_monitor_directory()
fam_monitor_collection()
fam_cancel_monitor()
fam_suspend_monitor()
fam_resume_monitor()

Prev | Home | Next
fam_monitor_directory | Up | fam_next_event


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()

Prev | Home | Next
fam_monitor_file | Up | fam_open


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()

Prev | Home | Next
fam_next_event | Up | fam_pending


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.

See Also

fam_next_event()

Prev | Home | Next
fam_open | Up | fam_resume_monitor


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.

See Also

fam_suspend_monitor()

Prev | Home | Next
fam_pending | Up | fam_suspend_monitor


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.

See Also

fam_cancel_monitor()
fam_resume_monitor()

Prev | Home | Next
fam_resume_monitor | Up | Forms Data Format Functions


FrontBase Functions

PHP Manual
Prev Next

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

Name | Default | Changeable | Changelog
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

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 --
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

Prev | Home | Next
fribidi_log2vis | Up | fbsql_affected_rows


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.

See Also

fbsql_num_rows()

Prev | Home | Next
FrontBase Functions | Up | fbsql_autocommit


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.

See Also

fbsql_commit()
fbsql_rollback()

Prev | Home | Next
fbsql_affected_rows | Up | fbsql_blob_size


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.

See Also

fbsql_clob_size()

Prev | Home | Next
fbsql_autocommit | Up | fbsql_change_user


fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user -- Change logged in user of the active connection

Description

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.

Prev | Home | Next
fbsql_blob_size | Up | fbsql_clob_size


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.

See Also

fbsql_blob_size()

Prev | Home | Next
fbsql_change_user | Up | fbsql_close


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

&#60;?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?&#62;

See Also

fbsql_connect()
fbsql_pconnect()

Prev | Home | Next
fbsql_clob_size | Up | fbsql_commit


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.

See Also

fbsql_autocommit()
fbsql_rollback()

Prev | Home | Next
fbsql_close | Up | fbsql_connect


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

&#60;?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?&#62;

See Also

fbsql_pconnect()
fbsql_close()

Prev | Home | Next
fbsql_commit | Up | fbsql_create_blob


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

&#60;?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);
?&#62;

See Also

fbsql_create_clob()
fbsql_read_blob()
fbsql_read_clob()
fbsql_set_lob_mode()

Prev | Home | Next
fbsql_connect | Up | fbsql_create_clob


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

&#60;?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);
?&#62;

See Also

fbsql_create_blob()
fbsql_read_blob()
fbsql_read_clob()
fbsql_set_lob_mode()

Prev | Home | Next
fbsql_create_blob | Up | fbsql_create_db


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

&#60;?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());
}
?&#62;

See Also

fbsql_drop_db()

Prev | Home | Next
fbsql_create_clob | Up | fbsql_data_seek


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

&#60;?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 &#62;=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-&#62;last_name . $row-&#62;first_name . "&#60;br /&#62;\n";
}

fbsql_free_result($result);
?&#62;

Prev | Home | Next
fbsql_create_db | Up | fbsql_database_password


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

&#60;?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?&#62;

See Also

fbsql_connect()
fbsql_pconnect()
fbsql_select_db()

Prev | Home | Next
fbsql_data_seek | Up | fbsql_database


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.

Prev | Home | Next
fbsql_database_password | Up | fbsql_db_query


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.

See Also

fbsql_query()
fbsql_connect()

Prev | Home | Next
fbsql_database | Up | fbsql_db_status


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.

See Also

fbsql_start_db()
fbsql_stop_db()

Prev | Home | Next
fbsql_db_query | Up | fbsql_drop_db


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.

See Also

fbsql_create_db()

Prev | Home | Next
fbsql_db_status | Up | fbsql_errno


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

&#60;?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
?&#62;

See Also

fbsql_error()
fbsql_warnings()

Prev | Home | Next
fbsql_drop_db | Up | fbsql_error


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

&#60;?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "&#60;br /&#62;";
?&#62;

See Also

fbsql_errno()
fbsql_warnings()

Prev | Home | Next
fbsql_errno | Up | fbsql_fetch_array


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

&#60;?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"] . "&#60;br /&#62;\n";
    echo "user_id: " . $row[0] . "&#60;br /&#62;\n";
    echo "fullname: " . $row["fullname"] . "&#60;br /&#62;\n";
    echo "fullname: " . $row[1] . "&#60;br /&#62;\n";
}
fbsql_free_result($result);
?&#62;

See Also

fbsql_fetch_row()
fbsql_fetch_assoc()
fbsql_fetch_object()

Prev | Home | Next
fbsql_error | Up | fbsql_fetch_assoc


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

&#60;?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);
?&#62;

See Also

fbsql_fetch_row()
fbsql_fetch_array()
fbsql_fetch_object()

Prev | Home | Next
fbsql_fetch_array | Up | fbsql_fetch_field


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

&#60;?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 &#60; fbsql_num_fields($result)) {
    echo "Information for column $i:&#60;br /&#62;\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available&#60;br /&#62;\n";
    }
    echo "&#60;pre&#62;
max_length:   $meta-&#62;max_length
name:         $meta-&#62;name
not_null:     $meta-&#62;not_null
table:        $meta-&#62;table
type:         $meta-&#62;type
&#60;/pre&#62;";
    $i++;
}
fbsql_free_result($result);
?&#62;

See Also

fbsql_field_seek()

Prev | Home | Next
fbsql_fetch_assoc | Up | fbsql_fetch_lengths


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.

See Also

fbsql_fetch_row()

Prev | Home | Next
fbsql_fetch_field | Up | fbsql_fetch_object


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

&#60;?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row-&#62;user_id;
    echo $row-&#62;fullname;
}
fbsql_free_result($result);
?&#62;

See Also

fbsql_fetch_array()
fbsql_fetch_row()
fbsql_fetch_assoc()

Prev | Home | Next
fbsql_fetch_lengths | Up | fbsql_fetch_row


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.

See Also

fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_object()
fbsql_data_seek()
fbsql_fetch_lengths()
fbsql_result()

Prev | Home | Next
fbsql_fetch_object | Up | fbsql_field_flags


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().

Prev | Home | Next
fbsql_fetch_row | Up | fbsql_field_len


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.

Prev | Home | Next
fbsql_field_flags | Up | fbsql_field_name


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

&#60;?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);
?&#62;

The above example will output:

user_id
password

See Also

fbsql_field_type()

Prev | Home | Next
fbsql_field_len | Up | fbsql_field_seek


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.

See Also

fbsql_fetch_field()

Prev | Home | Next
fbsql_field_name | Up | fbsql_field_table


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.

Prev | Home | Next
fbsql_field_seek | Up | fbsql_field_type


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

&#60;?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 &#60;br /&#62;";
echo "The table has the following fields &#60;br /&#62;";
while ($i &#60; $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 . "&#60;br /&#62;";
    $i++;
}
fbsql_close();

?&#62;

See Also

fbsql_field_name()

Prev | Home | Next
fbsql_field_table | Up | fbsql_free_result


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.

Prev | Home | Next
fbsql_field_type | Up | fbsql_get_autostart_info


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

Prev | Home | Next
fbsql_free_result | Up | fbsql_hostname


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.

See Also

fbsql_username()
fbsql_password()

Prev | Home | Next
fbsql_get_autostart_info | Up | fbsql_insert_id


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.

See Also

fbsql_affected_rows()

Prev | Home | Next
fbsql_hostname | Up | fbsql_list_dbs


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-&#62;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.

See Also

fbsql_list_fields()
fbsql_list_tables()

Prev | Home | Next
fbsql_insert_id | Up | fbsql_list_fields


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

&#60;?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i &#60; $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?&#62;

The above example will output something similar to:

field1
field2
field3
...

See Also

fbsql_field_len()
fbsql_field_name()
fbsql_field_type()
fbsql_field_flags()

Prev | Home | Next
fbsql_list_dbs | Up | fbsql_list_tables


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.

See Also

fbsql_list_fields()
fbsql_list_dbs()

Prev | Home | Next
fbsql_list_fields | Up | fbsql_next_result


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

&#60;?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);
?&#62;

Prev | Home | Next
fbsql_list_tables | Up | fbsql_num_fields


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.

See Also

fbsql_db_query()
fbsql_query()
fbsql_fetch_field()
fbsql_num_rows()

Prev | Home | Next
fbsql_next_result | Up | fbsql_num_rows


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

&#60;?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";

?&#62;

See Also

fbsql_affected_rows()
fbsql_connect()
fbsql_select_db()
fbsql_query()

Prev | Home | Next
fbsql_num_fields | Up | fbsql_password


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.

See Also

fbsql_username()
fbsql_hostname()

Prev | Home | Next
fbsql_num_rows | Up | fbsql_pconnect


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()

Prev | Home | Next
fbsql_password | Up | fbsql_query


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

&#60;?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?&#62;

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

&#60;?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?&#62;

See Also

fbsql_affected_rows()
fbsql_db_query()
fbsql_free_result()
fbsql_result()
fbsql_select_db()
fbsql_connect()

Prev | Home | Next
fbsql_pconnect | Up | fbsql_read_blob


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

&#60;?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);

?&#62;

See Also

fbsql_create_blob()
fbsql_read_clob()
fbsql_set_lob_mode()

Prev | Home | Next
fbsql_query | Up | fbsql_read_clob


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

&#60;?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);

?&#62;

See Also

fbsql_create_clob()
fbsql_read_blob()
fbsql_set_lob_mode()

Prev | Home | Next
fbsql_read_blob | Up | fbsql_result


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()

Prev | Home | Next
fbsql_read_clob | Up | fbsql_rollback


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.

See Also

fbsql_autocommit()
fbsql_commit()

Prev | Home | Next
fbsql_result | Up | fbsql_rows_fetched


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.

See Also

fbsql_connect()
fbsql_pconnect()
fbsql_database_password()
fbsql_query()

Prev | Home | Next
fbsql_rows_fetched | Up | fbsql_set_characterset


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.

See Also

fbsql_create_blob()
fbsql_create_clob()
fbsql_read_blob()
fbsql_read_clob()

Prev | Home | Next
fbsql_set_characterset | Up | fbsql_set_password


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.

Prev | Home | Next
fbsql_set_lob_mode | Up | fbsql_set_transaction


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 )

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

locking

isolation

Return Values

No value is returned.

Prev | Home | Next
fbsql_set_password | Up | fbsql_start_db


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.

See Also

fbsql_db_status()
fbsql_stop_db()

Prev | Home | Next
fbsql_set_transaction | Up | fbsql_stop_db


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.

See Also

fbsql_db_status()
fbsql_start_db()

Prev | Home | Next
fbsql_start_db | Up | fbsql_table_name


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().

Prev | Home | Next
fbsql_table_name | Up | fbsql_username


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.

See Also

fbsql_password()
fbsql_hostname()

Prev | Home | Next
fbsql_tablename | Up | fbsql_warnings


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.

See Also

fbsql_errno()
fbsql_error()

Prev | Home | Next
fbsql_username | Up | FTP Functions


Forms Data Format Functions

PHP Manual
Prev Next

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 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 to enable this module on a Windows environment, you must copy fdftk.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

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

&#60;?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 '&#60;b&#62;$volume&#60;/b&#62;'&#60;br /&#62;";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '&#60;b&#62;$date&#60;/b&#62;'&#60;br /&#62;";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '&#60;b&#62;$comment&#60;/b&#62;'&#60;br /&#62;";

if (fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '&#60;b&#62;$publisher&#60;/b&#62;'&#60;br /&#62;";
} else
  echo "Publisher shall not be shown.&#60;br /&#62;";

if (fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '&#60;b&#62;$preparer&#60;/b&#62;'&#60;br /&#62;";
} else
  echo "Preparer shall not be shown.&#60;br /&#62;";
fdf_close($fdf);
?&#62;

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

Prev | Home | Next
fam_suspend_monitor | Up | fdf_add_doc_javascript


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 fdfdoc, 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. It is strongly suggested to use '\r' for linebreaks within script_code.

Example 1. Adding JavaScript code to a FDF

&#60;?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?&#62;

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

Prev | Home | Next
Forms Data Format Functions | Up | fdf_add_template


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 fdfdoc, int newpage, string filename, string template, int rename )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fdf_add_doc_javascript | Up | fdf_close


fdf_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_close -- Close an FDF document

Description

void fdf_close ( resource fdf_document )

The fdf_close() function closes the FDF document.

See also fdf_open().

Prev | Home | Next
fdf_add_template | Up | fdf_create


fdf_create

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_create -- Create a new FDF document

Description

resource fdf_create ( void )

The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.

Example 1. Populating a PDF document

&#60;?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");
?&#62;

See also fdf_close(),
         fdf_save(),
         fdf_open().

Prev | Home | Next
fdf_close | Up | fdf_enum_values


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 fdfdoc, callback function [, mixed userdata] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fdf_create | Up | fdf_errno


fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno -- Return error code for last fdf operation

Description

int fdf_errno ( void )

fdf_errno() returns the error code set by the last FDF function call. This is zero for a successfull operation or a non-zero error code on failure. A textual description may be obtained using the fdf_error() function.

See also fdf_error().

Prev | Home | Next
fdf_enum_values | Up | 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] )

fdf_error() returns a textual description for the fdf error code given in error_code. The function uses the internal error code set by the last operation if no error_code is given, so fdf_error() is a convenient shortcut for fdf_error(fdf_errno()).

See also fdf_errno().

Prev | Home | Next
fdf_errno | Up | fdf_get_ap


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 )

The fdf_get_ap() function gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file. The possible values of face are FDFNormalAP, FDFRolloverAP and FDFDownAP. The appearance is stored in filename.

Prev | Home | Next
fdf_error | Up | fdf_get_attachment


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. savepath may be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Note: There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

The returned array contains the following fields:

  • path - path were the file got stored

    size - size of the stored file in bytes

    type - mimetype if given in the FDF

Example 1. Storing an uploaded file

&#60;?php
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "The uploaded file is stored in $data[path]";
?&#62;

Prev | Home | Next
fdf_get_ap | Up | fdf_get_encoding


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 )

The fdf_get_encoding() returns the value of the /Encoding key. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

See also fdf_set_encoding().

Prev | Home | Next
fdf_get_attachment | Up | fdf_get_file


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 )

The fdf_get_file() returns the value of the /F key.

See also fdf_set_file().

Prev | Home | Next
fdf_get_encoding | Up | fdf_get_flags


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 fdfdoc, string fieldname, int whichflags )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fdf_get_file | Up | fdf_get_opt


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 fdfdof, string fieldname [, int element] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fdf_get_flags | Up | fdf_get_status


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 )

The fdf_get_status() returns the value of the /STATUS key.

See also fdf_set_status().

Prev | Home | Next
fdf_get_opt | Up | fdf_get_value


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] )

The fdf_get_value() function returns the value for the requested fieldname.

Elements of an array field can be retrieved by passing the optional which, starting at zero. For non-array fields the optional parameter which will be ignored.

Note: Array support and optional which parameter were added in PHP 4.3.

See also fdf_set_value().

Prev | Home | Next
fdf_get_status | Up | fdf_get_version


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] )

This function will return the fdf version for the given fdf_document, or the toolkit API version number if no parameter is given.

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'.

See also fdf_set_version().

Prev | Home | Next
fdf_get_value | Up | fdf_header


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.

Prev | Home | Next
fdf_get_version | Up | fdf_next_field_name


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] )

The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second parameter is NULL.

Example 1. Detecting all fieldnames in a FDF

&#60;?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";
}
?&#62;

See also fdf_get_value().

Prev | Home | Next
fdf_header | Up | fdf_open_string


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 )

The fdf_open_string() function reads form data from a string. fdf_data must contain the data as returned from a PDF form or created using fdf_create() and fdf_save_string().

You can fdf_open_string() together with $HTTP_FDF_DATA to process fdf form input from a remote client.

Example 1. Accessing the form data

&#60;?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?&#62;

See also
fdf_open(),
fdf_close(),
fdf_create() and
fdf_save_string().

Prev | Home | Next
fdf_next_field_name | Up | fdf_open


fdf_open

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_open -- Open a FDF document

Description

resource fdf_open ( string filename )

The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

You can process the results of a PDF form POST request by writing the data received in $HTTP_FDF_DATA to a file and open it using fdf_open(). Starting with PHP 4.3 you can also use fdf_open_string() which handles temporary file creation and cleanup for you.

Example 1. Accessing the form data

&#60;?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);
?&#62;

See also
fdf_open_string(),
fdf_close(),
fdf_create() and
fdf_save().

Prev | Home | Next
fdf_open_string | Up | fdf_remove_item


fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item -- Sets target frame for form

Description

bool fdf_remove_item ( resource fdfdoc, string fieldname, int item )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fdf_open | Up | fdf_save_string


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 )

The fdf_save_string() function returns the FDF document as a string.

Example 1. Retrieving FDF as a string

&#60;?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?&#62;

will output something like

%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

See also fdf_save(),
fdf_open_string(),
fdf_create() and
fdf_close().

Prev | Home | Next
fdf_remove_item | Up | fdf_save


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] )

The fdf_save() function saves a FDF document. The resulting FDF will be written to filename. Without a filename fdf_save() will write the FDF to the default PHP output stream.

See also fdf_save_string(),
fdf_create() and
fdf_close().

Prev | Home | Next
fdf_save_string | Up | fdf_set_ap


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 )

The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are FDFNormalAP, FDFRolloverAP and FDFDownAP.

Prev | Home | Next
fdf_save | Up | fdf_set_encoding


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 )

fdf_set_encoding() sets the character encoding in FDF document fdf_document. encoding should be the valid encoding name. Currently the following values are supported: "Shift-JIS", "UHC", "GBK","BigFive". An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

Prev | Home | Next
fdf_set_ap | Up | fdf_set_file


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] )

The fdf_set_file() selects a different PDF document to display the form results in then the form it originated from. The url needs to be given as an absolute URL.

The frame to display the document in may be selected using the optional parameter target_frame or the function fdf_set_target_frame().

Example 1. Passing FDF data to a second form

&#60;?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);
?&#62;

See also fdf_get_file() and fdf_set_target_frame().

Prev | Home | Next
fdf_set_encoding | Up | fdf_set_flags


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 )

The fdf_set_flags() sets certain flags of the given field fieldname.

See also fdf_set_opt().

Prev | Home | Next
fdf_set_file | Up | fdf_set_javascript_action


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 )

fdf_set_javascript_action() sets a javascript action for the given field fieldname.

See also fdf_set_submit_form_action().

Prev | Home | Next
fdf_set_flags | Up | fdf_set_on_import_javascript


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 fdfdoc, string script, bool before_data_import )

Warning

This function is currently not documented; only the argument list is available.

See also fdf_add_doc_javascript() and fdf_set_javascript_action().

Prev | Home | Next
fdf_set_javascript_action | Up | fdf_set_opt


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 )

The fdf_set_opt() sets options of the given field fieldname.

See also fdf_set_flags().

Prev | Home | Next
fdf_set_on_import_javascript | Up | fdf_set_status


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 )

The fdf_set_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.

See also fdf_get_status().

Prev | Home | Next
fdf_set_opt | Up | fdf_set_submit_form_action


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 )

The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.

See also fdf_set_javascript_action().

Prev | Home | Next
fdf_set_status | Up | fdf_set_target_frame


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.

See also fdf_save_file().

Prev | Home | Next
fdf_set_submit_form_action | Up | fdf_set_value


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] )

The fdf_set_value() function sets the value for a field named fieldname. The value will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

Note: In older versions of the fdf toolkit last parameter determined if the field value was to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 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.

Support for value arrays was added in PHP 4.3.

See also fdf_get_value() and fdf_remove_item().

Prev | Home | Next
fdf_set_target_frame | Up | fdf_set_version


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 )

This function will set the fdf version for the given fdf_document. Some features supported by this extension are only available in newer fdf versions. For the current FDF toolkit 5.0 version may be either '1.2', '1.3' or '1.4'.

See also fdf_get_version().

Prev | Home | Next
fdf_set_value | Up | Fileinfo Functions


filePro Functions

PHP Manual
Prev Next

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

Prev | Home | Next
finfo_set_flags | Up | filepro_fieldcount


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()

Prev | Home | Next
filePro Functions | Up | filepro_fieldname


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.

Prev | Home | Next
filepro_fieldcount | Up | filepro_fieldtype


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.

Prev | Home | Next
filepro_fieldname | Up | filepro_fieldwidth


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.

Prev | Home | Next
filepro_fieldtype | Up | filepro_retrieve


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.

Prev | Home | Next
filepro_fieldwidth | Up | filepro_rowcount


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()

Prev | Home | Next
filepro_retrieve | Up | 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.

Prev | Home | Next
filepro_rowcount | Up | Filesystem Functions


Filesystem Functions

PHP Manual
Prev Next

XL. Filesystem Functions

Introduction

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

Name | Default | Changeable | Changelog
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. Available since PHP 4.0.4.
allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0.
from | "" | PHP_INI_ALL |
auto_detect_line_endings | "0" | PHP_INI_ALL | Available 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 LXIII, 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

Resource Types

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)

FILE_APPEND (integer)

FILE_IGNORE_NEW_LINES (integer)

FILE_SKIP_EMPTY_LINES (integer)

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 M.

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

Prev | Home | Next
filepro | Up | basename


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

&#60;?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"
?&#62;

Note: The suffix parameter was added in PHP 4.1.0.

See also dirname().

Prev | Home | Next
Filesystem Functions | Up | chgrp


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 (specified by name or number). Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Returns TRUE on success or FALSE on failure.

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() and chmod().

Prev | Home | Next
basename | Up | 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):

&#60;?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
?&#62;

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'.

&#60;?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);
?&#62;

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().

Prev | Home | Next
chgrp | Up | chown


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 (specified by name or number). Only the superuser may change the owner of a file.

Returns TRUE on success or FALSE on failure.

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().

Prev | Home | Next
chmod | Up | clearstatcache


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().

Prev | Home | Next
chown | Up | copy


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. Returns TRUE on success or FALSE on failure.

Example 1. copy() example

&#60;?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?&#62;

If you wish to move a file, use the rename() function.

Note: As of PHP 4.3.0, both source and dest may be URLs if the "fopen wrappers" have been enabled. See fopen() for more details. If 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.

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(), and the section of the manual about handling file uploads.

Prev | Home | Next
clearstatcache | Up | delete


delete

(no version information, might be only in CVS)

delete -- See unlink() or unset()

Description

void delete ( string file )

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

See also unlink() to delete files, unset() to delete variables.

Prev | Home | Next
copy | Up | dirname


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

&#60;?php
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
?&#62;

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:

&#60;?php

//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/'); // returns 'c:'

?&#62;

dirname() has been binary safe since PHP 5.0.0

See also basename(), pathinfo(), and realpath().

Prev | Home | Next
delete | Up | disk_free_space


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.

Example 1. disk_free_space() example

&#60;?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
disk_free_space("C:");
disk_free_space("D:");
?&#62;

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

See also disk_total_space()

Prev | Home | Next
dirname | Up | disk_total_space


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.

Example 1. disk_total_space() example

&#60;?php
// $df contains the total number of bytes available on "/"
$df = disk_total_space("/");

// On Windows:
disk_total_space("C:");
disk_total_space("D:");
?&#62;

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

See also disk_free_space()

Prev | Home | Next
disk_free_space | Up | diskfreespace


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().

Prev | Home | Next
disk_total_space | Up | fclose


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.

Returns TRUE on success or FALSE on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Example 1. A simple fclose() example

&#60;?php

  $handle = fopen('somefile.txt', 'r');

  fclose($handle);

?&#62;

Prev | Home | Next
diskfreespace | Up | feof


feof

(PHP 3, PHP 4, PHP 5)

feof -- Tests for end-of-file on a file pointer

Description

bool feof ( resource handle )

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

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.

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

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

&#60;?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);
?&#62;

Prev | Home | Next
fclose | Up | fflush


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 handle. Returns TRUE on success or FALSE on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Prev | Home | Next
feof | Up | fgetc


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

&#60;?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?&#62;

Note: This function is binary-safe.

See also fread(), fopen(),
popen(), fsockopen(), and
fgets().

Prev | Home | Next
fflush | Up | fgetcsv


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]]] )

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length (Optional)

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 (Optional)

Set the field delimiter (one character only). Defaults as a comma.

enclosure (Optional)

Set the field enclosure character (one character only). Defaults as a double quotation mark. Added in PHP 4.3.0.

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

fgetcsv() returns FALSE on error, including end of file.

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.

Example 1. Read and print the entire contents of a CSV file

&#60;?php
$row = 1;
$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "&#60;p&#62; $num fields in line $row: &#60;br /&#62;&#60;/p&#62;\n";
    $row++;
    for ($c=0; $c &#60; $num; $c++) {
        echo $data[$c] . "&#60;br /&#62;\n";
    }
}
fclose($handle);
?&#62;

fgetcsv() has been binary safe since PHP 4.3.5

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.

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 explode(), file(), pack() and fputcsv().

Prev | Home | Next
fgetc | Up | fgets


fgets

(PHP 3, PHP 4, PHP 5)

fgets -- Gets line from file pointer

Description

string fgets ( resource handle [, int length] )

Returns a string of up to length - 1 bytes read from the file pointed to by handle. 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.

If an error occurs, returns FALSE.

Common Pitfalls:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

A simple example follows:

Example 1. Reading a file line by line

&#60;?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?&#62;

Note: The length parameter became optional in PHP 4.2.0. 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.

Note: This function is binary safe as of PHP 4.3. Earlier versions were not binary safe.

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 fgetss()
fread(),
fgetc(),
stream_get_line(),
fopen(),
popen(),
fsockopen(), and
stream_set_timeout().

Prev | Home | Next
fgetcsv | Up | fgetss


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().

Prev | Home | Next
fgets | Up | file_exists


file_exists

(PHP 3, PHP 4, PHP 5)

file_exists -- Checks whether a file or directory exists

Description

bool file_exists ( string filename )

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Example 1. Testing whether a file exists

&#60;?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?&#62;

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 M for a listing of which wrappers support stat() family of functionality.

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.

See also is_readable(), is_writable(), is_file() and file().

Prev | Home | Next
fgetss | Up | file_get_contents


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

Version | Description
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 M 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 CLVIII, 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.

See Also

file()
fgets()
fread()
readfile()
file_put_contents()
stream_get_contents()
stream_context_create()

Prev | Home | Next
file_exists | Up | file_put_contents


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)).

As of PHP 5.1.0, you may also pass a stream resource to the data parameter. In result, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

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).

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.

context

A context resource

Return Values

The function returns the amount of bytes that were written to the file, or FALSE on failure.

ChangeLog

Version | Description
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

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 CLVIII, 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 M for a list of supported URL protocols.

See Also

fopen()
fwrite()
file_get_contents()
stream_context_create()

Prev | Home | Next
file_get_contents | Up | file


file

(PHP 3, PHP 4, PHP 5)

file -- Reads entire file into an array

Description

array file ( string filename [, int use_include_path [, resource context]] )

Identical to file_get_contents(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

You can use the optional use_include_path parameter and set it to "1", if you want to search for the file in the include_path, too.

&#60;?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 =&#62; $line) {
    echo "Line #&#60;b&#62;{$line_num}&#60;/b&#62; : " . htmlspecialchars($line) . "&#60;br /&#62;\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
?&#62;

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 M for a list of supported URL protocols.

Note: Each line in the resulting array will include the line ending, 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.

Note: As of PHP 4.3.0 you can use file_get_contents() to return the contents of a file as a string.

In PHP 4.3.0 file() became binary safe.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, 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.

See also readfile(),
fopen(), fsockopen(),
popen(), file_get_contents(),
include(), and
stream_context_create()

Prev | Home | Next
file_put_contents | Up | fileatime


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 M for a listing of which wrappers support stat() family of functionality.

Example 1. fileatime() example

&#60;?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));
}

?&#62;

See also filemtime(),
fileinode(), and
date().

Prev | Home | Next
file | Up | filectime


filectime

(PHP 3, PHP 4, PHP 5)

filectime -- Gets inode change time of file

Description

int filectime ( string filename )

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

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 M for a listing of which wrappers support stat() family of functionality.

Example 1. A filectime() example

&#60;?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));
}

?&#62;

See also filemtime()

Prev | Home | Next
fileatime | Up | filegroup


filegroup

(PHP 3, PHP 4, PHP 5)

filegroup -- Gets file group

Description

int filegroup ( string filename )

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 along with an error of level E_WARNING.

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 M for a listing of which wrappers support stat() family of functionality.

See also fileowner(), and safe_mode_gid.

Prev | Home | Next
filectime | Up | fileinode


fileinode

(PHP 3, PHP 4, PHP 5)

fileinode -- Gets file inode

Description

int fileinode ( string filename )

Returns the inode number of the file, or FALSE in case of an error.

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 M for a listing of which wrappers support stat() family of functionality.

See also stat()

Prev | Home | Next
filegroup | Up | filemtime


filemtime

(PHP 3, PHP 4, PHP 5)

filemtime -- Gets file modification time

Description

int filemtime ( string filename )

Returns the time the file was last modified, or FALSE in case of an error. The time is returned as a Unix timestamp, which is suitable for the date() function.

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 M for a listing of which wrappers support stat() family of functionality.

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.

Example 1. filemtime() example

&#60;?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));
}
?&#62;

See also filectime(), stat(), touch(), and getlastmod().

Prev | Home | Next
fileinode | Up | fileowner


fileowner

(PHP 3, PHP 4, PHP 5)

fileowner -- Gets file owner

Description

int fileowner ( string filename )

Returns the user ID of the owner of the file, or FALSE in case of an error. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

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 M for a listing of which wrappers support stat() family of functionality.

See also stat()

Prev | Home | Next
filemtime | Up | fileperms


fileperms

(PHP 3, PHP 4, PHP 5)

fileperms -- Gets file permissions

Description

int fileperms ( string filename )

Returns the permissions on the file, or FALSE in case of an error.

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 M for a listing of which wrappers support stat() family of functionality.

Example 1. Display permissions as an octal value

&#60;?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?&#62;

This would produce the output:

1777
0644

Example 2. Display full permissions

&#60;?php
$perms = fileperms('/etc/passwd');

if (($perms &#38; 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms &#38; 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms &#38; 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms &#38; 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms &#38; 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms &#38; 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms &#38; 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}

// Owner
$info .= (($perms &#38; 0x0100) ? 'r' : '-');
$info .= (($perms &#38; 0x0080) ? 'w' : '-');
$info .= (($perms &#38; 0x0040) ?
            (($perms &#38; 0x0800) ? 's' : 'x' ) :
            (($perms &#38; 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms &#38; 0x0020) ? 'r' : '-');
$info .= (($perms &#38; 0x0010) ? 'w' : '-');
$info .= (($perms &#38; 0x0008) ?
            (($perms &#38; 0x0400) ? 's' : 'x' ) :
            (($perms &#38; 0x0400) ? 'S' : '-'));

// World
$info .= (($perms &#38; 0x0004) ? 'r' : '-');
$info .= (($perms &#38; 0x0002) ? 'w' : '-');
$info .= (($perms &#38; 0x0001) ?
            (($perms &#38; 0x0200) ? 't' : 'x' ) :
            (($perms &#38; 0x0200) ? 'T' : '-'));

echo $info;
?&#62;

This would produce the output:

-rw-r--r--

See also is_readable(), and stat()

Prev | Home | Next
fileowner | Up | filesize


filesize

(PHP 3, PHP 4, PHP 5)

filesize -- Gets file size

Description

int filesize ( string filename )

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)).

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 M for a listing of which wrappers support stat() family of functionality.

Example 1. filesize() example

&#60;?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?&#62;

See also file_exists()

Prev | Home | Next
fileperms | Up | filetype


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 M for a listing of which wrappers support stat() family of functionality.

Example 1. filetype() example

&#60;?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?&#62;

See also is_dir(), is_file(),
is_link(), file_exists(),
stat(), and mime_content_type().

Prev | Home | Next
filesize | Up | flock


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

&#60;?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);

?&#62;

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).

Prev | Home | Next
filetype | Up | fnmatch


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.

&#60;?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?&#62;

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 ).

Prev | Home | Next
flock | Up | fopen


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. 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 M. 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).

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, Stream Functions.

Note: 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.

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

mode | Description
'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. This option is supported in PHP 4.3.2 and later, and only works for local files.
'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. This option is supported in PHP 4.3.2 and later, and only works for local files.

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.

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.

If the open fails, the function returns FALSE and an error of level E_WARNING is generated. You may use @ to suppress this warning.

Example 1. fopen() examples

&#60;?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");
?&#62;

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

&#60;?php
$handle = fopen("c:\\data\\info.txt", "r");
?&#62;

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.

See also Appendix M,
fclose(),
fgets(),
fread(),
fwrite(),
fsockopen(),
file(),
file_exists(),
is_readable(),
stream_set_timeout(),
popen(), and
stream_context_create().

Prev | Home | Next
fnmatch | Up | fpassthru


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

&#60;?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;

?&#62;

See also readfile(),
fopen(), popen(), and
fsockopen()

Prev | Home | Next
fopen | Up | fputcsv


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

&#60;?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);
?&#62;

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().

Prev | Home | Next
fpassthru | Up | fputs


fputs

(PHP 3, PHP 4, PHP 5)

fputs -- Alias of fwrite()

Description

This function is an alias of: fwrite().

Prev | Home | Next
fputcsv | Up | fread


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.

&#60;?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);
?&#62;

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.

&#60;?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?&#62;

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.

&#60;?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?&#62;

&#60;?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?&#62;

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().

Prev | Home | Next
fputs | Up | fscanf


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

&#60;?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);
?&#62;

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().

Prev | Home | Next
fread | Up | fseek


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

&#60;?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);

?&#62;

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().

Prev | Home | Next
fscanf | Up | fstat


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

&#60;?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));

?&#62;

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.

Prev | Home | Next
fseek | Up | ftell


ftell

(PHP 3, PHP 4, PHP 5)

ftell -- Tells file pointer read/write position

Description

int ftell ( resource handle )

Returns the position of the file pointer referenced by handle; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Example 1. ftell() example

&#60;?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);

?&#62;

See also fopen(), popen(), fseek(), and rewind().

Prev | Home | Next
fstat | Up | ftruncate


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().

Prev | Home | Next
ftell | Up | fwrite


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.

Example 1. A simple fwrite() example

&#60;?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";
}
?&#62;

See also fread(),
fopen(),
fsockopen(),
popen(), and
file_put_contents().

Prev | Home | Next
ftruncate | Up | glob


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. No tilde expansion or parameter substitution is done.

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

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'

    Note: This flag is not available on some non GNU systems, like Solaris.

  • GLOB_ONLYDIR - Return only directory entries which match the pattern

    Note: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.

  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored. Added in PHP 5.1.0.

Example 1. Convenient way how glob() can replace opendir() and friends.

&#60;?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?&#62;

The above example will output something similar to:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

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).

See also opendir(),
readdir(),
closedir(), and fnmatch().

Prev | Home | Next
fwrite | Up | is_dir


is_dir

(PHP 3, PHP 4, PHP 5)

is_dir -- Tells whether the filename is a directory

Description

bool is_dir ( string filename )

Returns TRUE if the filename exists and is a directory. If filename is a relative filename, it will be checked relative to the current working directory.

Note: The results of this function are cached. See clearstatcache() for more details.

Example 1. is_dir() example

&#60;?php
var_dump(is_dir('a_file.txt')) . "\n";
var_dump(is_dir('bogus_dir/abc')) . "\n";

var_dump(is_dir('..')); //one dir up
?&#62;

The above example will output:

bool(false)
bool(false)
bool(true)

Tip: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to Appendix M for a listing of which wrappers support stat() family of functionality.

See also chdir(), dir,
opendir(), is_file() and
is_link().

Prev | Home | Next
glob | Up | is_executable


is_executable

(PHP 3, PHP 4, PHP 5)

is_executable -- Tells whether the filename is executable

Description

bool is_executable ( string filename )

Returns TRUE if the filename exists and is executable.

is_executable() became available with Windows in PHP version 5.0.0.

Example 1. is_executable() example

&#60;?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?&#62;

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 M for a listing of which wrappers support stat() family of functionality.

See also is_file() and is_link().

Prev | Home | Next
is_dir | Up | is_file


is_file

(PHP 3, PHP 4, PHP 5)

is_file -- Tells whether the filename is a regular file

Description

bool is_file ( string filename )

Returns TRUE if the filename exists and is a regular file.

Example 1. is_file() example

&#60;?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?&#62;

The above example will output:

bool(true)
bool(false)

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 M for a listing of which wrappers support stat() family of functionality.

See also is_dir() and is_link().

Prev | Home | Next
is_executable | Up | is_link


is_link

(PHP 3, PHP 4, PHP 5)

is_link -- Tells whether the filename is a symbolic link

Description

bool is_link ( string filename )

Returns TRUE if the filename exists and is a symbolic link.

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 M for a listing of which wrappers support stat() family of functionality.

See also is_dir(), is_file(), and readlink().

Prev | Home | Next
is_file | Up | is_readable


is_readable

(PHP 3, PHP 4, PHP 5)

is_readable -- Tells whether the filename is readable

Description

bool is_readable ( string filename )

Returns TRUE if the file or directory specified by filename exists and is readable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Example 1. is_readable() example

&#60;?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?&#62;

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 M for a listing of which wrappers support stat() family of functionality.

See also is_writable(),
file_exists(), and
fgets().

Prev | Home | Next
is_link | Up | is_uploaded_file


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

&#60;?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'] . "'.";
}

?&#62;

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

&#60;?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]'.";
}
?&#62;

See also move_uploaded_file(), and the section Handling file uploads for a simple usage example.

Prev | Home | Next
is_readable | Up | is_writable


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

&#60;?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?&#62;

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 M for a listing of which wrappers support stat() family of functionality.

See also is_readable(),
file_exists(), and
fwrite().

Prev | Home | Next
is_uploaded_file | Up | is_writeable


is_writeable

(PHP 3, PHP 4, PHP 5)

is_writeable -- Alias of is_writable()

Description

This function is an alias of: is_writable().

Prev | Home | Next
is_writable | Up | lchgrp


link

(PHP 3, PHP 4, PHP 5)

link -- Create a hard link

Description

bool link ( string target, string link )

link() creates a hard link. Returns TRUE on success or FALSE on failure.

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.

See also the symlink() to create soft links, and readlink() along with linkinfo().

Prev | Home | Next
lchown | Up | linkinfo


linkinfo

(PHP 3, PHP 4, PHP 5)

linkinfo -- Gets information about a link

Description

int linkinfo ( string path )

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.

Example 1. linkinfo() example

&#60;?php

echo linkinfo('/vmlinuz'); // 835

?&#62;

Note: This function is not implemented on Windows platforms.

See also symlink(), link(), and readlink().

Prev | Home | Next
link | Up | lstat


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

See the manual page for stat() for information on the structure of the array that lstat() returns.

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 M for a listing of which wrappers support stat() family of functionality.

See also stat().

Prev | Home | Next
linkinfo | Up | mkdir


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.

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().

Note: Mode is ignored on Windows, and became optional in PHP 4.2.0.

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Example 1. mkdir() example

&#60;?php
mkdir("/path/to/my/dir", 0700);
?&#62;

Returns TRUE on success or FALSE on failure.

Note: As of PHP 5.0.0 mkdir() can also be used with some URL wrappers. Refer to Appendix M for a listing of which wrappers support mkdir().

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, Stream Functions.

Note: The recursive parameter was added as of PHP 5.0.0.

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().

Prev | Home | Next
lstat | Up | move_uploaded_file


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.

Prev | Home | Next
mkdir | Up | parse_ini_file


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 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

&#60;?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);

?&#62;

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.

Prev | Home | Next
move_uploaded_file | Up | pathinfo


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

&#60;?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
?&#62;

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().

Prev | Home | Next
parse_ini_file | Up | pclose


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().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

Prev | Home | Next
pathinfo | Up | 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

&#60;?php
$handle = popen("/bin/ls", "r");
?&#62;

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:

&#60;?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/spooge 2&#62;&#38;1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?&#62;

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().

Prev | Home | Next
pclose | Up | readfile


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 M 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 CLVIII, Stream Functions.

See also fpassthru(),
file(), fopen(),
include(), require(),
virtual(), file_get_contents(),
and Appendix M.

Prev | Home | Next
popen | Up | readlink


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 and returns the contents of the symbolic link path or FALSE in case of error.

Example 1. readlink() example

&#60;?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?&#62;

Note: This function is not implemented on Windows platforms.

See also is_link(),
symlink(), and
linkinfo().

Prev | Home | Next
readfile | Up | realpath


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

&#60;?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?&#62;

The above example will output:

/etc/passwd

See also basename(),
dirname(), and
pathinfo().

Prev | Home | Next
readlink | Up | rename


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.

Returns TRUE on success or FALSE on failure.

Example 1. Example with rename()

&#60;?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?&#62;

Note: Prior to PHP 4.3.3, rename() could not rename files across partitions on *nix based systems.

Note: As of PHP 5.0.0 rename() can also be used with some URL wrappers. Refer to Appendix M for a listing of which wrappers support rename().

Note: The wrapper used in oldname MUST match the wrapper used in newname.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, Stream Functions.

See also copy(),
unlink(), and
move_uploaded_file().

Prev | Home | Next
realpath | Up | rewind


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.

Returns TRUE on success or FALSE on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen().

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 fseek() and ftell().

Prev | Home | Next
rename | Up | rmdir


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. Returns TRUE on success or FALSE on failure.

Note: As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Appendix M for a listing of which wrappers support rmdir().

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, Stream Functions.

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() and unlink().

Prev | Home | Next
rewind | Up | set_file_buffer


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().

Prev | Home | Next
rmdir | Up | stat


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.

In case of error, stat() returns FALSE. It also will throw a warning.

Returns an array with the statistics of the file with the following elements. This array is zero-based. In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter; this is available since PHP 4.0.6:

Table 1. stat() and fstat() result format

Numeric | Associative (since PHP 4.0.6) | Description
0 | dev | device number
1 | ino | inode number
2 | mode | inode protection mode
3 | nlink | number of links
4 | uid | userid of owner
5 | gid | groupid of owner
6 | rdev | device type, if inode device *
7 | size | size in bytes
8 | atime | time of last access (Unix timestamp)
9 | mtime | time of last modification (Unix timestamp)
10 | ctime | time of last inode change (Unix timestamp)
11 | blksize | blocksize of filesystem IO *
12 | blocks | number of blocks allocated
* Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

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 M for a listing of which wrappers support stat() family of functionality.

See also lstat(),
fstat(),
filemtime(), and
filegroup().

Prev | Home | Next
set_file_buffer | Up | symlink


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.

Returns TRUE on success or FALSE on failure.

Note: This function is not implemented on Windows platforms.

See also link() to create hard links, and readlink() along with linkinfo().

Prev | Home | Next
stat | Up | tempnam


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

&#60;?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?&#62;

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().

Prev | Home | Next
symlink | Up | tmpfile


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, returning a file handle similar to the one returned by fopen(). The file is automatically removed when closed (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Example 1. tmpfile() example

&#60;?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?&#62;

The above example will output:

writing to tempfile

See also tempnam(), sys_get_temp_dir().

Prev | Home | Next
tempnam | Up | touch


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

&#60;?php
if (touch($FileName)) {
    echo "$FileName modification time has been changed to present time";
} else {
    echo "Sorry, could not change modification time of $FileName";
}
?&#62;

Prev | Home | Next
tmpfile | Up | umask


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

&#60;?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');
}
?&#62;

Prev | Home | Next
touch | Up | unlink


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. Returns TRUE on success or FALSE on failure.

Note: As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Appendix M for a listing of which wrappers support unlink().

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CLVIII, Stream Functions.

See also rmdir() for removing directories.

Prev | Home | Next
umask | Up | Filter Functions


FriBiDi Functions

PHP Manual
Prev Next

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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Runtime Configuration

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

Prev | Home | Next
PDO_FIREBIRD DSN | Up | fribidi_log2vis


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.

Prev | Home | Next
FriBiDi Functions | Up | FrontBase Functions


FTP Functions

PHP Manual
Prev Next

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

&#60;?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);
?&#62;

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

Prev | Home | Next
fbsql_warnings | Up | ftp_alloc


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

&#60;?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);

?&#62;

See Also

ftp_put()
ftp_fput()

Prev | Home | Next
FTP Functions | Up | ftp_cdup


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

&#60;?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);
?&#62;

See Also

ftp_chdir()
ftp_pwd()

Prev | Home | Next
ftp_alloc | Up | ftp_chdir


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

&#60;?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);
?&#62;

See Also

ftp_cdup()
ftp_pwd()

Prev | Home | Next
ftp_cdup | Up | ftp_chmod


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

&#60;?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);
?&#62;

See Also

chmod()

Prev | Home | Next
ftp_chdir | Up | ftp_close


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

&#60;?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);
?&#62;

See Also

ftp_connect()

Prev | Home | Next
ftp_chmod | Up | 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

&#60;?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");

?&#62;

ChangeLog

Version | Description
4.2.0 | timeout was added.

See Also

ftp_close()
ftp_ssl_connect()

Prev | Home | Next
ftp_close | Up | ftp_delete


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

&#60;?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);
?&#62;

Prev | Home | Next
ftp_connect | Up | ftp_exec


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

&#60;?php

// variable initialization
$command = 'ls -al &#62;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);

?&#62;

See Also

ftp_raw()

Prev | Home | Next
ftp_delete | Up | ftp_fget


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

&#60;?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);
?&#62;

ChangeLog

Version | Description
4.3.0 | resumepos was added.

See Also

ftp_get()
ftp_nb_get()
ftp_nb_fget()

Prev | Home | Next
ftp_exec | Up | ftp_fput


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

&#60;?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);

?&#62;

ChangeLog

Version | Description
4.3.0 | startpos was added.

See Also

ftp_put()
ftp_nb_fput()
ftp_nb_put()

Prev | Home | Next
ftp_fget | Up | ftp_get_option


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

&#60;?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?&#62;

See Also

ftp_set_option()

Prev | Home | Next
ftp_fput | Up | ftp_get


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

&#60;?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);

?&#62;

ChangeLog

Version | Description
4.3.0 | resumepos was added.

See Also

ftp_pasv()
ftp_fget()
ftp_nb_get()
ftp_nb_fget()

Prev | Home | Next
ftp_get_option | Up | ftp_login


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

&#60;?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);
?&#62;

Prev | Home | Next
ftp_get | Up | ftp_mdtm


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

&#60;?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);

?&#62;

Prev | Home | Next
ftp_login | Up | ftp_mkdir


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

&#60;?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);
?&#62;

See Also

ftp_rmdir()

Prev | Home | Next
ftp_mdtm | Up | ftp_nb_continue


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

&#60;?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);
}
?&#62;

Prev | Home | Next
ftp_mkdir | Up | ftp_nb_fget


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

&#60;?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);
?&#62;

See Also

ftp_nb_get()
ftp_nb_continue()
ftp_fget()
ftp_get()

Prev | Home | Next
ftp_nb_continue | Up | ftp_nb_fput


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

&#60;?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);
?&#62;

See Also

ftp_nb_put()
ftp_nb_continue()
ftp_put()
ftp_fput()

Prev | Home | Next
ftp_nb_fget | Up | ftp_nb_get


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

&#60;?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);
}
?&#62;

Example 2. Resuming a download with ftp_nb_get()

&#60;?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);
}
?&#62;

Example 3. Resuming a download at position 100 to a new file with ftp_nb_get()

&#60;?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);
}
?&#62;

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'.

See Also

ftp_nb_fget()
ftp_nb_continue()
ftp_fget()
ftp_get()

Prev | Home | Next
ftp_nb_fput | Up | ftp_nb_put


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

&#60;?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);
}
?&#62;

Example 2. Resuming an upload with ftp_nb_put()

&#60;?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);
}
?&#62;

See Also

ftp_nb_fput()
ftp_nb_continue()
ftp_put()
ftp_fput()

Prev | Home | Next
ftp_nb_get | Up | ftp_nlist


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

&#60;?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);

?&#62;

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()

Prev | Home | Next
ftp_nb_put | Up | ftp_pasv


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

&#60;?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);
?&#62;

Prev | Home | Next
ftp_nlist | Up | ftp_put


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

&#60;?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);
?&#62;

ChangeLog

Version | Description
4.3.0 | startpos was added.

See Also

ftp_pasv()
ftp_fput()
ftp_nb_fput()
ftp_nb_put()

Prev | Home | Next
ftp_pasv | Up | ftp_pwd


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

&#60;?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);
?&#62;

See Also

ftp_chdir()
ftp_cdup()

Prev | Home | Next
ftp_put | Up | ftp_quit


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().

Prev | Home | Next
ftp_pwd | Up | ftp_raw


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.

&#60;?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");
?&#62;

See Also

ftp_exec()

Prev | Home | Next
ftp_quit | Up | ftp_rawlist


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

&#60;?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);
?&#62;

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

Version | Description
4.3.0 | recursive was added.

See Also

ftp_nlist()

Prev | Home | Next
ftp_raw | Up | ftp_rename


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

&#60;?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);
?&#62;

Prev | Home | Next
ftp_rawlist | Up | ftp_rmdir


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

&#60;?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);

?&#62;

See Also

ftp_mkdir()

Prev | Home | Next
ftp_rename | Up | ftp_set_option


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

&#60;?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?&#62;

See Also

ftp_get_option()

Prev | Home | Next
ftp_rmdir | Up | ftp_site


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

&#60;?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.');
}
?&#62;

See Also

ftp_raw()

Prev | Home | Next
ftp_set_option | Up | ftp_size


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

&#60;?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);

?&#62;

See Also

ftp_rawlist()

Prev | Home | Next
ftp_site | Up | ftp_ssl_connect


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

Version | Description
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

&#60;?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);
?&#62;

See Also

ftp_connect()

Prev | Home | Next
ftp_size | Up | ftp_systype


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

&#60;?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";
}

?&#62;

The above example will output something similar to:

Example.com is powered by UNIX

Prev | Home | Next
ftp_ssl_connect | Up | Function Handling Functions


Function Handling Functions

PHP Manual
Prev Next

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

Prev | Home | Next
ftp_systype | Up | call_user_func_array


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 given by function, with the parameters in param_arr. For example:

Example 1. call_user_func_array() example

&#60;?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));
?&#62;

See also call_user_func(), and information about the callback type

Prev | Home | Next
Function Handling Functions | Up | call_user_func


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. Take the following:

&#60;?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?&#62;

Class methods may also be invoked statically using this function by passing array($classname, $methodname) to the function parameter.

&#60;?php
class myclass {
    function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
?&#62;

Note: Note that the parameters for call_user_func() are not passed by reference.

&#60;?php
function increment(&#38;$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a; // 0

call_user_func_array('increment', array(&#38;$a)); // You can use this instead
echo $a; // 1
?&#62;

See also: is_callable(), call_user_func_array(), and information about the callback type.

Prev | Home | Next
call_user_func_array | Up | create_function


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. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

You can use this function, to (for example) create a function from information gathered at run time:

Example 1. Creating an anonymous function with create_function()

&#60;?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
?&#62;

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()

&#60;?php
function process($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a &#62;=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 &#62; 0 &#38;&#38; $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, &#38;$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?&#62;

and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Example 3. Using anonymous functions as callback functions

&#60;?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&#38;$v,$k', '$v = $v . "mango";'));
print_r($av);
?&#62;

outputs:

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

an array of strings ordered from shorter to longer

&#60;?php

$sv = array("small", "larger", "a big string", "it is a string thing");
print_r($sv);

?&#62;

outputs:

Array
(
  [0] => small
  [1] => larger
  [2] => a big string
  [3] => it is a string thing
)

sort it from longer to shorter

&#60;?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?&#62;

outputs:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

Prev | Home | Next
call_user_func | Up | func_get_arg


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 )

Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.

If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.

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.

&#60;?php
function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs&#60;br /&#62;\n";
     if ($numargs &#62;= 2) {
     echo "Second argument is: " . func_get_arg(1) . "&#60;br /&#62;\n";
     }
}

foo (1, 2, 3);
?&#62;

func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Prev | Home | Next
create_function | Up | func_get_args


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 )

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

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.

&#60;?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs&#60;br /&#62;\n";
    if ($numargs &#62;= 2) {
        echo "Second argument is: " . func_get_arg(1) . "&#60;br /&#62;\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i &#60; $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "&#60;br /&#62;\n";
    }
}

foo(1, 2, 3);
?&#62;

func_get_args() may be used in conjunction
with func_num_args() and
func_get_arg() to allow user-defined functions
to accept variable-length argument lists.

Prev | Home | Next
func_get_arg | Up | func_num_args


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 )

Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.

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.

&#60;?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);    // Prints 'Number of arguments: 3'
?&#62;

func_num_args() may be used in conjunction
with func_get_arg() and
func_get_args() to allow user-defined
functions to accept variable-length argument lists.

Prev | Home | Next
func_get_args | Up | function_exists


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. Returns TRUE on success or FALSE on failure.

&#60;?php
if (function_exists('imap_open')) {
    echo "IMAP functions are available.&#60;br /&#62;\n";
} else {
    echo "IMAP functions are not available.&#60;br /&#62;\n";
}
?&#62;

Note that a function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). Also note that function_exists() will return FALSE for constructs, such as include_once() and echo().

See also method_exists(),
is_callable() and
get_defined_functions().

Prev | Home | Next
func_num_args | Up | get_defined_functions


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 )

This function returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

&#60;?php
function myrow($id, $data)
{
    return "&#60;tr&#62;&#60;th&#62;$id&#60;/th&#62;&#60;td&#62;$data&#60;/td&#62;&#60;/tr&#62;\n";
}

$arr = get_defined_functions();

print_r($arr);
?&#62;

Will output something along the lines of:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

See also
function_exists(),
get_defined_vars() and
get_defined_constants().

Prev | Home | Next
function_exists | Up | register_shutdown_function


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().

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.

See also auto_append_file, exit(), and the section on connection handling.

Prev | Home | Next
get_defined_functions | Up | register_tick_function


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 function named by func to be executed when a tick is called. Also, you may pass an array consisting of an object and a method as the func.

Example 1. register_tick_function() example

&#60;?php
// using a function as the callback
register_tick_function('my_function', true);

// using an object-&#62;method
$object = new my_class();
register_tick_function(array(&#38;$object, 'my_method'), true);
?&#62;

Warning

register_tick_function() should not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver.

See also declare and unregister_tick_function().

Prev | Home | Next
register_shutdown_function | Up | unregister_tick_function


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.

Prev | Home | Next
register_tick_function | Up | GeoIP Functions


Gettext

PHP Manual
Prev Next

XLIX. Gettext

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

Prev | Home | Next
geoip_region_by_name | Up | bind_textdomain_codeset


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.

Prev | Home | Next
Gettext | Up | bindtextdomain


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

&#60;?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?&#62;

The above example will output:

/usr/share/myapp/locale

Prev | Home | Next
bind_textdomain_codeset | Up | dcgettext


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()

Prev | Home | Next
bindtextdomain | Up | dcngettext


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()

Prev | Home | Next
dcgettext | Up | dgettext


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()

Prev | Home | Next
dcngettext | Up | dngettext


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()

Prev | Home | Next
dgettext | Up | gettext


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

&#60;?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");
?&#62;

Notes

Note: You may use the underscore character '_' as an alias to this function.

See Also

setlocale()

Prev | Home | Next
dngettext | Up | ngettext


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

&#60;?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

?&#62;

Prev | Home | Next
gettext | Up | textdomain


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.

Prev | Home | Next
ngettext | Up | GMP Functions


GMP Functions

PHP Manual
Prev Next

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

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.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)

Examples

Example 1. Factorial function using GMP

&#60;?php
function fact($x)
{
    $return = 1;
    for ($i=2; $i &#60; $x; $i++) {
        $return = gmp_mul($return, $i);
    }
    return $return;
}

echo gmp_strval(fact(1000)) . "\n";
?&#62;

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_xor -- Logical XOR

Prev | Home | Next
textdomain | Up | gmp_abs


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

&#60;?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?&#62;

The printout of the above program will be:

274982683358
274982683358

Prev | Home | Next
GMP Functions | Up | gmp_add


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

&#60;?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?&#62;

The printout of the above program will be:

200000000000000

Prev | Home | Next
gmp_abs | Up | gmp_and


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

&#60;?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?&#62;

The printout of the above program will be:

4
0

Prev | Home | Next
gmp_add | Up | gmp_clrbit


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

&#60;?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?&#62;

The printout of the above program will be:

254

See also gmp_setbit().

Prev | Home | Next
gmp_and | Up | gmp_cmp


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

&#60;?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";
?&#62;

The printout of the above program will be:

1 -1 0

Prev | Home | Next
gmp_clrbit | Up | gmp_com


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

&#60;?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?&#62;

The printout of the above program will be:

-1235

Prev | Home | Next
gmp_cmp | Up | gmp_div_q


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

&#60;?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";
?&#62;

The printout of the above program will be:

20
0
1
0
-1

See also gmp_div_r(), gmp_div_qr()

Prev | Home | Next
gmp_com | Up | 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

&#60;?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]));
?&#62;

See also gmp_div_q(), gmp_div_r().

Prev | Home | Next
gmp_div_q | Up | 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

&#60;?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?&#62;

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()

Prev | Home | Next
gmp_div_qr | Up | gmp_div


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().

Prev | Home | Next
gmp_div_r | Up | gmp_divexact


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

&#60;?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";

$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?&#62;

The printout of the above program will be:

5
2863311534

Prev | Home | Next
gmp_div | Up | gmp_fact


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

&#60;?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";
?&#62;

The printout of the above program will be:

120
30414093201713378043612608166064768844377641568960512000000000000

Prev | Home | Next
gmp_divexact | Up | gmp_gcd


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

&#60;?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?&#62;

The printout of the above program will be:

3

Prev | Home | Next
gmp_fact | Up | gmp_gcdext


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

&#60;?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 &#38;&#38; $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
?&#62;

Prev | Home | Next
gmp_gcd | Up | gmp_hamdist


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

&#60;?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";
?&#62;

The printout of the above program will be:

6
6

See also gmp_popcount(), gmp_xor()

Prev | Home | Next
gmp_gcdext | Up | gmp_init


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

&#60;?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?&#62;

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().

Prev | Home | Next
gmp_hamdist | Up | gmp_intval


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

&#60;?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";
?&#62;

The printout of the above program will be:

2147483647
2147483647
2147483648

Prev | Home | Next
gmp_init | Up | gmp_invert


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

&#60;?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?&#62;

The printout of the above program will be:

9

Prev | Home | Next
gmp_intval | Up | gmp_jacobi


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

&#60;?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?&#62;

The printout of the above program will be:

1
0

Prev | Home | Next
gmp_invert | Up | gmp_legendre


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

&#60;?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?&#62;

The printout of the above program will be:

1
0

Prev | Home | Next
gmp_jacobi | Up | gmp_mod


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

&#60;?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?&#62;

The printout of the above program will be:

2

Prev | Home | Next
gmp_legendre | Up | gmp_mul


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

&#60;?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?&#62;

The printout of the above program will be:

24691356000

Prev | Home | Next
gmp_mod | Up | gmp_neg


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

&#60;?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?&#62;

The printout of the above program will be:

-1
1

Prev | Home | Next
gmp_mul | Up | gmp_nextprime


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

&#60;?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?&#62;

The printout of the above program will be:

fffffff6
fffffff2

Prev | Home | Next
gmp_nextprime | Up | gmp_perfect_square


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

&#60;?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"));
?&#62;

The printout of the above program will be:

bool(true)
bool(false)
bool(true)

See also: gmp_sqrt(), gmp_sqrtrem().

Prev | Home | Next
gmp_or | Up | gmp_popcount


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

&#60;?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";
?&#62;

The printout of the above program will be:

3
7

Prev | Home | Next
gmp_perfect_square | Up | gmp_pow


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

&#60;?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";
?&#62;

The printout of the above program will be:

2147483648
1

Prev | Home | Next
gmp_popcount | Up | gmp_powm


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

&#60;?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?&#62;

The printout of the above program will be:

2147483648

Prev | Home | Next
gmp_pow | Up | gmp_prob_prime


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

&#60;?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";
?&#62;

The printout of the above program will be:

0
1
2

Prev | Home | Next
gmp_powm | Up | gmp_random


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

&#60;?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";
?&#62;

The printout of the above program might be:

1915834968
8642564075890328087

Prev | Home | Next
gmp_prob_prime | Up | gmp_scan0


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

&#60;?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";
?&#62;

The printout of the above program will be:

3
7

Prev | Home | Next
gmp_random | Up | gmp_scan1


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

&#60;?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";
?&#62;

The printout of the above program will be:

3
9

Prev | Home | Next
gmp_scan0 | Up | gmp_setbit


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

&#60;?php
$a = gmp_init("0xfd");
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a) . "\n";
?&#62;

The printout of the above program will be:

255

See also gmp_clrbit().

Prev | Home | Next
gmp_scan1 | Up | gmp_sign


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

&#60;?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?&#62;

The printout of the above program will be:

1
-1
0

Prev | Home | Next
gmp_setbit | Up | gmp_sqrt


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

&#60;?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";
?&#62;

The printout of the above program will be:

3
2
1234567890

Prev | Home | Next
gmp_sign | Up | gmp_sqrtrem


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

&#60;?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";
?&#62;

The printout of the above program will be:

3, 0
2, 3
1024, 0

Prev | Home | Next
gmp_sqrt | Up | gmp_strval


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

&#60;?php
$a = gmp_init("0x41682179fbf5");
printf("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?&#62;

Prev | Home | Next
gmp_sqrtrem | Up | gmp_sub


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

&#60;?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?&#62;

The printout of the above program will be:

281470681743360

Prev | Home | Next
gmp_strval | Up | gmp_xor


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

&#60;?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);

$xor3 = gmp_xor($xor1, $xor2);

echo gmp_strval($xor3, 2) . "\n";
?&#62;

The printout of the above program will be:

1011110111000100

Prev | Home | Next
gmp_sub | Up | gnupg Functions


HTTP

PHP Manual
Prev Next

LIV. 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

Classes

HttpMessage
HttpQueryString
HttpDeflateStream
HttpInflateStream
HttpRequest
HttpRequestPool
HttpResponse

Functions

Builtin Functions

Builtin HTTP related functions previously listed on this page can be found in the networking category.

The following functions do not need the HTTP module to be present: header(), headers_list(), headers_sent(), setcookie() and setrawcookie().

Caching

http_cache_etag()
http_cache_last_modified()

Encodings

http_chunked_decode()
http_deflate()
http_inflate()

Miscellaneous

http_build_cookie()
http_date()
http_get_request_body_stream()
http_get_request_body()
http_get_request_headers()
http_match_etag()
http_match_modified()
http_match_request_header()
http_support()

Negotiation

http_negotiate_charset()
http_negotiate_ctype()
http_negotiate_language()

Outputhandlers

ob_deflatehandler()
ob_etaghandler()
ob_inflatehandler()

Parsers

http_parse_cookie()
http_parse_headers()
http_parse_message()
http_parse_params()

Requests

http_get()
http_head()
http_post_data()
http_post_fields()
http_put_data()
http_put_file()
http_put_stream()
http_request_body_encode()
http_request_method_exists()
http_request_method_name()
http_request_method_register()
http_request_method_unregister()
http_request()

Responses

http_redirect()
http_send_content_disposition()
http_send_content_type()
http_send_data()
http_send_file()
http_send_last_modified()
http_send_status()
http_send_stream()
http_throttle()

URLs

http_build_str()
http_build_url()

Table of Contents
Installation -- Installing and configuring the HTTP extension
Configuration -- http module configuration directives
Constants -- predefined http module constants
HttpMessage -- HTTP Message Class
HttpMessage::__construct -- HttpMessage constructor
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::__construct -- HttpDeflateStream class constructor
HttpDeflateStream::update -- Update deflate stream
HttpDeflateStream::flush -- Flush deflate stream
HttpDeflateStream::finish -- Finalize deflate stream
HttpInflateStream -- HTTP Inflate Stream
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::guessContentType -- Guess content type
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
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 builtin 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_ctype -- 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 the HTTP message
http_parse_params -- Parse parameter list
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 status
http_send_stream -- Send stream
http_throttle -- HTTP throttling
http_build_str -- Build query string
http_build_url -- Build an URL

Prev | Home | Next
hash | Up | Installation


header

(PHP 3, PHP 4, PHP 5)

header -- Send a raw HTTP header

Description

void header ( string string [, bool replace [, int http_response_code]] )

header() is used to send a raw HTTP header. See the HTTP/1.1 specification for more information on HTTP headers.

Note: Since PHP 4.4.2 and PHP 5.1.2 this function prevents more than one header to be sent at once as a protection against header injection attacks.

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

&#60;?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?&#62;

The second optional http_response_code force the HTTP response code to the specified value. (This parameter is available in PHP 4.3.0 and higher.)

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

&#60;?php
header("HTTP/1.0 404 Not Found");
?&#62;

Note: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.

&#60;?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?&#62;

Note: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

&#60;?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?&#62;

Note: Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

&#60;?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?&#62;

Note: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

&#60;html&#62;
&#60;?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
?&#62;

Note: As of PHP 4, you can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

&#60;?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?&#62;

Note: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

Note: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

See also headers_sent(), setcookie(), and the section on HTTP authentication.

Prev | Home | Next
getservbyport | Up | headers_list


headers_list

(PHP 5)

headers_list -- Returns a list of response headers sent (or ready to send)

Description

array headers_list ( void )

headers_list() will return a numerically indexed array of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().

Example 1. Examples using headers_list()

&#60;?php

/* setcookie() will add a response header on its own */
setcookie('foo', 'bar');

/* Define a custom response header
   This will be ignored by most clients */
header("X-Sample-Test: foo");

/* Specify plain text content in our response */
header('Content-type: text/plain');

/* What headers are going to be sent? */
var_dump(headers_list());

?&#62;

this will output :

array(4) {
  [0]=>
  string(23) "X-Powered-By: PHP/5.1.3"
  [1]=>
  string(19) "Set-Cookie: foo=bar"
  [2]=>
  string(18) "X-Sample-Test: foo"
  [3]=>
  string(24) "Content-type: text/plain"
}

See Also:
headers_sent(),
header(), and
setcookie().

Prev | Home | Next
header | Up | headers_sent


headers_sent

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

headers_sent -- Checks if or where headers have been sent

Description

bool headers_sent ( [string &file [, int &line]] )

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise. If the optional file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables.

You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering.

Note: The optional file and line parameters were added in PHP 4.3.0.

Example 1. Examples using headers_sent()

&#60;?php

// If no headers are sent, send one
if (!headers_sent()) {
    header('Location: http://www.example.com/');
    exit;
}

// An example using the optional file and line parameters, as of PHP 4.3.0
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    echo "Headers already sent in $filename on line $linenum\n" .
          "Cannot redirect, for now please click this &#60;a " .
          "href=\"http://www.example.com\"&#62;link&#60;/a&#62; instead\n";
    exit;
}

?&#62;

See also ob_start(), trigger_error(), and header() for a more detailed discussion of the matters involved.

Prev | Home | Next
headers_list | Up | inet_ntop


setcookie

(PHP 3, PHP 4, PHP 5)

setcookie -- Send a cookie

Description

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Note: As of PHP 4, you can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead. The following table explains each parameter of the setcookie() function, be sure to read the Netscape cookie specification for specifics on how each setcookie() parameter works and RFC 2965 for additional information on how HTTP cookies work.

Table 1. setcookie() parameters explained

Parameter | Description | Examples
name | The name of the cookie. | 'cookiename' is called as $_COOKIE['cookiename']
value | The value of the cookie. This value is stored on the clients computer; do not store sensitive information. | Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
expire | The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). | time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
path | The path on the server in which the cookie will be available on. | If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
domain | The domain that the cookie is available. | To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.
secure | Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to TRUE, the cookie will only be set if a secure connection exists. The default is FALSE. | TRUE or FALSE
httponly | When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectly help to reduce identity theft through XSS attacks (although it is not supported by all browsers). Added in PHP 5.2.0. | TRUE or FALSE

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. $HTTP_COOKIE_VARS has existed since PHP 3. Cookie values also exist in $_REQUEST.

Note: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TestCookie will exist. It's recommended to use $_COOKIE.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

  • Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.

  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the users system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

In PHP 3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. As of PHP 4, multiple calls to setcookie() are performed in the order called.

Some examples follow how to send cookies:

Example 1. setcookie() send example

&#60;?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
?&#62;

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:

&#60;?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?&#62;

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

Example 2. setcookie() delete example

&#60;?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
?&#62;

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

Example 3. setcookie() and arrays

&#60;?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name =&#62; $value) {
        echo "$name : $value &#60;br /&#62;\n";
    }
}
?&#62;

which prints

three : cookiethree
two : cookietwo
one : cookieone

Note: The following RFC's may also be useful: RFC 2109 and RFC 2695

You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally.

expire is compared to the client's time which can differ from server's time.

Note: Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.

Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.

See also header(), setrawcookie() and the cookies section.

Prev | Home | Next
pfsockopen | Up | setrawcookie


setrawcookie

(PHP 5)

setrawcookie -- Send a cookie without urlencoding the cookie value

Description

bool setrawcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

Note: The httponly parameter was added in PHP 5.2.0.

See also header(), setcookie() and the cookies section.

Prev | Home | Next
setcookie | Up | socket_get_status


Hyperwave Functions

PHP Manual
Prev Next

LV. 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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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

Name | Default | Changeable | Changelog
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available 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 G.

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

Prev | Home | Next
http_build_url | Up | hw_Array2Objrec


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().

Prev | Home | Next
Hyperwave Functions | Up | hw_changeobject


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.

Prev | Home | Next
hw_Array2Objrec | Up | hw_Children


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.

Prev | Home | Next
hw_changeobject | Up | hw_ChildrenObj


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.

Prev | Home | Next
hw_Children | Up | hw_Close


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.

Prev | Home | Next
hw_ChildrenObj | Up | hw_Connect


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().

Prev | Home | Next
hw_Close | Up | hw_connection_info


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.

Prev | Home | Next
hw_Connect | Up | hw_cp


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().

Prev | Home | Next
hw_connection_info | Up | hw_Deleteobject


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().

Prev | Home | Next
hw_cp | Up | hw_DocByAnchor


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.

Prev | Home | Next
hw_Deleteobject | Up | hw_DocByAnchorObj


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.

Prev | Home | Next
hw_DocByAnchor | Up | hw_Document_Attributes


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().

Prev | Home | Next
hw_DocByAnchorObj | Up | hw_Document_BodyTag


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.

Prev | Home | Next
hw_Document_Attributes | Up | hw_Document_Content


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().

Prev | Home | Next
hw_Document_BodyTag | Up | 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().

Prev | Home | Next
hw_Document_Content | Up | hw_Document_Size


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.

Prev | Home | Next
hw_Document_SetContent | Up | hw_dummy


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.

Prev | Home | Next
hw_Document_Size | Up | hw_EditText


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().

Prev | Home | Next
hw_dummy | Up | hw_Error


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.

Prev | Home | Next
hw_EditText | Up | hw_ErrorMsg


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.

Prev | Home | Next
hw_Error | Up | hw_Free_Document


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.

Prev | Home | Next
hw_ErrorMsg | Up | hw_GetAnchors


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.

Prev | Home | Next
hw_Free_Document | Up | hw_GetAnchorsObj


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.

Prev | Home | Next
hw_GetAnchors | Up | hw_GetAndLock


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().

Prev | Home | Next
hw_GetAnchorsObj | Up | hw_GetChildColl


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().

Prev | Home | Next
hw_GetAndLock | Up | hw_GetChildCollObj


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().

Prev | Home | Next
hw_GetChildColl | Up | hw_GetChildDocColl


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().

Prev | Home | Next
hw_GetChildCollObj | Up | hw_GetChildDocCollObj


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().

Prev | Home | Next
hw_GetChildDocColl | Up | hw_GetObject


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().

Prev | Home | Next
hw_GetChildDocCollObj | Up | 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().

Prev | Home | Next
hw_GetObject | Up | hw_GetObjectByQueryColl


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().

Prev | Home | Next
hw_GetObjectByQuery | Up | 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().

Prev | Home | Next
hw_GetObjectByQueryColl | Up | hw_GetObjectByQueryObj


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().

Prev | Home | Next
hw_GetObjectByQueryCollObj | Up | hw_GetParents


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.

Prev | Home | Next
hw_GetObjectByQueryObj | Up | hw_GetParentsObj


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.

Prev | Home | Next
hw_GetParents | Up | hw_getrellink


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.

Prev | Home | Next
hw_GetParentsObj | Up | hw_GetRemote


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().

Prev | Home | Next
hw_getrellink | Up | 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().

Prev | Home | Next
hw_GetRemote | Up | hw_GetSrcByDestObj


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().

Prev | Home | Next
hw_getremotechildren | Up | hw_GetText


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().

Prev | Home | Next
hw_GetSrcByDestObj | Up | hw_getusername


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.

Prev | Home | Next
hw_GetText | Up | hw_Identify


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().

Prev | Home | Next
hw_getusername | Up | hw_InCollections


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.

Prev | Home | Next
hw_Identify | Up | hw_Info


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>

Prev | Home | Next
hw_InCollections | Up | hw_InsColl


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.

Prev | Home | Next
hw_Info | Up | hw_InsDoc


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().

Prev | Home | Next
hw_InsColl | Up | hw_insertanchors


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.

Prev | Home | Next
hw_InsDoc | Up | hw_InsertDocument


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().

Prev | Home | Next
hw_insertanchors | Up | hw_InsertObject


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().

Prev | Home | Next
hw_InsertDocument | Up | hw_mapid


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

Prev | Home | Next
hw_InsertObject | Up | hw_Modifyobject


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

&#60;?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" =&#62; "books");
       $addarr = array("Name" =&#62; "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?&#62;
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

&#60;?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" =&#62; 0);
       $addarr = array("Name" =&#62; "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?&#62;

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

&#60;?php
       $remarr = array("Title" =&#62; "en:Books");
       $addarr = array("Title" =&#62; "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?&#62;
or

Example 4. modifying Title attribute

&#60;?php
       $remarr = array("Title" =&#62; array("en" =&#62; "Books"));
       $addarr = array("Title" =&#62; array("en" =&#62; "Articles", "ge"=&#62;"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?&#62;
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Example 5. removing attribute

&#60;?php
       $remarr = array("Title" =&#62; "");
       $addarr = array("Title" =&#62; "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?&#62;

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.

Prev | Home | Next
hw_mapid | Up | hw_mv


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().

Prev | Home | Next
hw_Modifyobject | Up | hw_New_Document


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().

Prev | Home | Next
hw_mv | Up | hw_objrec2array


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().

Prev | Home | Next
hw_New_Document | Up | hw_Output_Document


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.

Prev | Home | Next
hw_objrec2array | Up | hw_pConnect


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().

Prev | Home | Next
hw_Output_Document | Up | hw_PipeDocument


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().

Prev | Home | Next
hw_pConnect | Up | hw_Root


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.

Prev | Home | Next
hw_PipeDocument | Up | hw_setlinkroot


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.

Prev | Home | Next
hw_Root | Up | hw_stat


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.

Prev | Home | Next
hw_setlinkroot | Up | hw_Unlock


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().

Prev | Home | Next
hw_stat | Up | hw_Who


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.

Prev | Home | Next
hw_Unlock | Up | Hyperwave API Functions


Hyperwave API Functions

PHP Manual
Prev Next

LVI. 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

Name | Default | Changeable | Changelog
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Prev | Home | Next
hw_Who | Up | hw_api_attribute->key


hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string hw_api_attribute->key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

Prev | Home | Next
Hyperwave API Functions | Up | hw_api_attribute->langdepvalue


hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string hw_api_attribute->langdepvalue ( string language )

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

Prev | Home | Next
hw_api_attribute->key | Up | hw_api_attribute->value


hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string hw_api_attribute->value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

Prev | Home | Next
hw_api_attribute->langdepvalue | Up | hw_api_attribute->values


hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array hw_api_attribute->values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

Prev | Home | Next
hw_api_attribute->value | Up | hw_api_attribute


hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

HW_API_Attribute hw_api_attribute ( [string name [, string value]] )

Creates a new instance of hw_api_attribute with the given name and value.

Prev | Home | Next
hw_api_attribute->values | Up | hw_api->checkin


hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

bool hw_api->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.

See also hwapi_checkout().

Prev | Home | Next
hw_api_attribute | Up | hw_api->checkout


hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

bool hw_api->checkout ( array parameter )

This function checks out an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

See also hwapi_checkin().

Prev | Home | Next
hw_api->checkin | Up | hw_api->children


hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array hw_api->children ( array parameter )

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

Prev | Home | Next
hw_api->checkout | Up | hw_api_content->mimetype


hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string hw_api_content->mimetype ( void )

Returns the mimetype of the content.

Prev | Home | Next
hw_api->children | Up | hw_api_content->read


hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string hw_api_content->read ( string buffer, int len )

Reads len bytes from the content into the given buffer.

Prev | Home | Next
hw_api_content->mimetype | Up | hw_api->content


hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

HW_API_Content hw_api->content ( array parameter )

This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

Prev | Home | Next
hw_api_content->read | Up | hw_api->copy


hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

hw_api_object hw_api->copy ( array parameter )

This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

Prev | Home | Next
hw_api->content | Up | hw_api->dbstat


hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

hw_api_object hw_api->dbstat ( array parameter )

See also hwapi_dcstat(),
         hwapi_hwstat(),
         hwapi_ftstat().

Prev | Home | Next
hw_api->copy | Up | hw_api->dcstat


hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

hw_api_object hw_api->dcstat ( array parameter )

See also hwapi_hwstat(),
         hwapi_dbstat(),
         hwapi_ftstat().

Prev | Home | Next
hw_api->dbstat | Up | hw_api->dstanchors


hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

array hw_api->dstanchors ( array parameter )

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

Prev | Home | Next
hw_api->dcstat | Up | hw_api->dstofsrcanchor


hw_api->dstofsrcanchor

(no version information, might be only in CVS)

hw_api->dstofsrcanchor -- Returns destination of a source anchor

Description

hw_api_object hw_api->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. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(),
         hwapi_dstanchors(),
         hwapi_objectbyanchor().

Prev | Home | Next
hw_api->dstanchors | Up | hw_api_error->count


hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int hw_api_error->count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

Prev | Home | Next
hw_api->dstofsrcanchor | Up | hw_api_error->reason


hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

HW_API_Reason hw_api_error->reason ( void )

Returns the first error reason.

See also hwapi_error_count().

Prev | Home | Next
hw_api_error->count | Up | hw_api->find


hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

array hw_api->find ( array parameter )

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

Prev | Home | Next
hw_api_error->reason | Up | hw_api->ftstat


hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

hw_api_object hw_api->ftstat ( array parameter )

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_hwstat().

Prev | Home | Next
hw_api->find | Up | hwapi_hgcsp


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. If you do not pass a port number, 418 is used.

See also hwapi_hwtp().

Prev | Home | Next
hw_api->ftstat | Up | hw_api->hwstat


hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

hw_api_object hw_api->hwstat ( array parameter )

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_ftstat().

Prev | Home | Next
hwapi_hgcsp | Up | hw_api->identify


hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

bool hw_api->identify ( array parameter )

Logs into the Hyperwave Server. The parameter array must contain the elements 'username' and 'password'.

The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.

Prev | Home | Next
hw_api->hwstat | Up | hw_api->info


hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

array hw_api->info ( array parameter )

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_ftstat(),
         hwapi_hwstat().

Prev | Home | Next
hw_api->identify | Up | hw_api->insert


hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

hw_api_object hw_api->insert ( array parameter )

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding 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

See also hwapi_replace().

Prev | Home | Next
hw_api->info | Up | hw_api->insertanchor


hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

hw_api_object hw_api->insertanchor ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

See also hwapi_insertdocument(),
         hwapi_insertcollection(),
         hwapi_insert().

Prev | Home | Next
hw_api->insert | Up | hw_api->insertcollection


hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

hw_api_object hw_api->insertcollection ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insertdocument(),
         hwapi_insertanchor(),
         hwapi_insert().

Prev | Home | Next
hw_api->insertanchor | Up | hw_api->insertdocument


hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

hw_api_object hw_api->insertdocument ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insert()
         hwapi_insertanchor(),
         hwapi_insertcollection().

Prev | Home | Next
hw_api->insertcollection | Up | hw_api->link


hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

bool hw_api->link ( array parameter )

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns TRUE on success or an error object.

See also hwapi_copy().

Prev | Home | Next
hw_api->insertdocument | Up | hw_api->lock


hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

bool hw_api->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. 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.

See also hwapi_unlock().

Prev | Home | Next
hw_api->link | Up | hw_api->move


hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

bool hw_api->move ( array parameter )

See also hw_objrec2array().

Prev | Home | Next
hw_api->lock | Up | hw_api_content


hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

HW_API_Content hw_api_content ( string content, string mimetype )

Creates a new content object from the string content. The mimetype is set to mimetype.

Prev | Home | Next
hw_api->move | Up | hw_api_object->assign


hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

bool hw_api_object->assign ( array parameter )

Clones the attributes of an object.

Prev | Home | Next
hw_api_content | Up | hw_api_object->attreditable


hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool hw_api_object->attreditable ( array parameter )

Prev | Home | Next
hw_api_object->assign | Up | hw_api_object->count


hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int hw_api_object->count ( array parameter )

Prev | Home | Next
hw_api_object->attreditable | Up | hw_api_object->insert


hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool hw_api_object->insert ( HW_API_Attribute attribute )

Adds an attribute to the object. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_remove().

Prev | Home | Next
hw_api_object->count | Up | hw_api_object


hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

hw_api_object hw_api_object ( array parameter )

See also hwapi_lock().

Prev | Home | Next
hw_api_object->insert | Up | hw_api_object->remove


hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool hw_api_object->remove ( string name )

Removes the attribute with the given name. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_insert().

Prev | Home | Next
hw_api_object | Up | hw_api_object->title


hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string hw_api_object->title ( array parameter )

Prev | Home | Next
hw_api_object->remove | Up | hw_api_object->value


hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string hw_api_object->value ( string name )

Returns the value of the attribute with the given name or FALSE if an error occurred.

Prev | Home | Next
hw_api_object->title | Up | hw_api->object


hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

hw_api_object hw_api->object ( array parameter )

This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

This simple example retrieves an object and checks for errors.

Example 1. Retrieve an object

&#60;?php
function handle_error($error)
{
  $reason = $error-&#62;reason(0);
  echo "Type: &#60;b&#62;";
  switch ($reason-&#62;type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "&#60;/b&#62;&#60;br /&#62;\n";
  echo "Description: " . $reason-&#62;description("en") . "&#60;br /&#62;\n";
}

function list_attr($obj)
{
  echo "&#60;table&#62;\n";
  $count = $obj-&#62;count();
  for ($i=0; $i&#60;$count; $i++) {
    $attr = $obj-&#62;attribute($i);
    printf("&#60;tr&#62;&#60;td align=\"right\" bgcolor=\"#c0c0c0\"&#62;&#60;b&#62;%s&#60;/b&#62;&#60;/td&#62;&#60;td bgcolor=\"#F0F0F0\"&#62;%s&#60;/td&#62;&#60;/tr&#62;\n",
             $attr-&#62;key(), $attr-&#62;value());
  }
  echo "&#60;/table&#62;\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=&#62;"rootcollection", "attributeSelector"=&#62;array("Title", "Name", "DocumentType"));
$root = $hwapi-&#62;object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?&#62;

See also hwapi_content().

Prev | Home | Next
hw_api_object->value | Up | hw_api->objectbyanchor


hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

hw_api_object hw_api->objectbyanchor ( array parameter )

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(),
         hwapi_srcanchors(),
         hwapi_dstanchors().

Prev | Home | Next
hw_api->object | Up | hw_api->parents


hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array hw_api->parents ( array parameter )

Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

Prev | Home | Next
hw_api->objectbyanchor | Up | hw_api_reason->description


hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string hw_api_reason->description ( void )

Returns the description of a reason

Prev | Home | Next
hw_api->parents | Up | hw_api_reason->type


hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

HW_API_Reason hw_api_reason->type ( void )

Returns the type of a reason.

Prev | Home | Next
hw_api_reason->description | Up | hw_api->remove


hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

bool hw_api->remove ( array parameter )

Removes an object from the specified parent. Collections will be removed recursively. You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance. The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be 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.

See also hwapi_move().

Prev | Home | Next
hw_api_reason->type | Up | hw_api->replace


hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

hw_api_object hw_api->replace ( array parameter )

Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

See also hwapi_insert().

Prev | Home | Next
hw_api->remove | Up | hw_api->setcommittedversion


hw_api->setcommittedversion

(no version information, might be only in CVS)

hw_api->setcommittedversion -- Commits version other than last version

Description

hw_api_object hw_api->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.

See also hwapi_checkin(),
         hwapi_checkout(),
         hwapi_revert().

Prev | Home | Next
hw_api->replace | Up | hw_api->srcanchors


hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

array hw_api->srcanchors ( array parameter )

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

Prev | Home | Next
hw_api->setcommittedversion | Up | hw_api->srcsofdst


hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

array hw_api->srcsofdst ( array parameter )

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

See also hwapi_dstofsrcanchor().

Prev | Home | Next
hw_api->srcanchors | Up | hw_api->unlock


hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

bool hw_api->unlock ( array parameter )

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Returns TRUE on success or an object of class HW_API_Error.

See also hwapi_lock().

Prev | Home | Next
hw_api->srcsofdst | Up | hw_api->user


hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

hw_api_object hw_api->user ( array parameter )

See also hwapi_userlist().

Prev | Home | Next
hw_api->unlock | Up | hw_api->userlist


hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

array hw_api->userlist ( array parameter )

See also hwapi_user().

Prev | Home | Next
hw_api->user | Up | IBM Functions (PDO_IBM)


Firebird/InterBase Functions

PHP Manual
Prev Next

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

Requirements

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 to enable this module on a Windows environment, you must copy gds32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therefore you don't need to copy gds32.dll from the DLL folder.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. InterBase configuration options

Name | Default | Changeable | Changelog
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM | Available since PHP 5.0.0.
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

Resource Types

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

Constant | Description
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Table 3. Firebird/InterBase fetch flags

Constant | Description
IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service
API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore()
and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.

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

Prev | Home | Next
filter_var | Up | ibase_add_user


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.

See also ibase_modify_user() and ibase_delete_user().

Prev | Home | Next
Firebird/InterBase Functions | Up | ibase_affected_rows


ibase_affected_rows

(PHP 5)

ibase_affected_rows -- Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ( [resource link_identifier] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.

See also ibase_query() and ibase_execute().

Prev | Home | Next
ibase_add_user | Up | ibase_backup


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.

Prev | Home | Next
ibase_affected_rows | Up | ibase_blob_add


ibase_blob_add

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_add -- Add data into a newly created blob

Description

void ibase_blob_add ( resource blob_handle, string data )

ibase_blob_add() adds data into a blob created with ibase_blob_create(). Returns NULL on success or FALSE on failure.

See also
ibase_blob_cancel(),
ibase_blob_close(),
ibase_blob_create() and
ibase_blob_import().

Prev | Home | Next
ibase_backup | Up | ibase_blob_cancel


ibase_blob_cancel

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_cancel -- Cancel creating blob

Description

bool ibase_blob_cancel ( resource blob_handle )

This function will discard a BLOB created by ibase_create_blob() if it has not yet been closed by ibase_blob_close(). Returns TRUE on success or FALSE on failure.

See also
ibase_blob_close(),
ibase_blob_create() and
ibase_blob_import().

Prev | Home | Next
ibase_blob_add | Up | ibase_blob_close


ibase_blob_close

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_close -- Close blob

Description

mixed ibase_blob_close ( resource blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_open_blob() or has been opened for writing by ibase_create_blob(). If the BLOB was being read, this function returns TRUE on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns FALSE.

See also ibase_blob_cancel() and ibase_blob_open().

Prev | Home | Next
ibase_blob_cancel | Up | ibase_blob_create


ibase_blob_create

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_create -- Create a new blob for adding data

Description

resource ibase_blob_create ( [resource link_identifier] )

ibase_blob_create() creates a new BLOB for filling with data. It returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

See also
ibase_blob_add(),
ibase_blob_cancel(),
ibase_blob_close() and
ibase_blob_import().

Prev | Home | Next
ibase_blob_close | Up | ibase_blob_echo


ibase_blob_echo

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_echo -- Output blob contents to browser

Description

bool ibase_blob_echo ( resource link_identifier, string blob_id )

bool ibase_blob_echo ( string blob_id )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases). Returns TRUE on success or FALSE on failure.

See also
ibase_blob_open(),
ibase_blob_close() and
ibase_blob_get().

Prev | Home | Next
ibase_blob_create | Up | ibase_blob_get


ibase_blob_get

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_get -- Get len bytes data from open blob

Description

string ibase_blob_get ( resource blob_handle, int len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open(). Returns FALSE on failure.

&#60;?php
    $sql       = "SELECT blob_value FROM table";
    $result    = ibase_query($sql);
    $data      = ibase_fetch_object($result);
    $blob_data = ibase_blob_info($data-&#62;BLOB_VALUE);
    $blob_hndl = ibase_blob_open($data-&#62;BLOB_VALUE);
    echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?&#62;

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.

Note: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

See also
ibase_blob_open(),
ibase_blob_close() and
ibase_blob_echo().

Prev | Home | Next
ibase_blob_echo | Up | ibase_blob_import


ibase_blob_import

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_import -- Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource link_identifier, resource file_handle )

string ibase_blob_import ( resource file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id. The file handle is a handle returned by fopen(). Returns FALSE on failure.

Example 1. ibase_blob_import() example

&#60;?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
}
?&#62;

See also
ibase_blob_add(),
ibase_blob_cancel(),
ibase_blob_close() and
ibase_blob_create().

Prev | Home | Next
ibase_blob_get | Up | ibase_blob_info


ibase_blob_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_info -- Return blob length and other useful info

Description

array ibase_blob_info ( resource link_identifier, string blob_id )

array ibase_blob_info ( string blob_id )

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

Prev | Home | Next
ibase_blob_import | Up | ibase_blob_open


ibase_blob_open

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_open -- Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource link_identifier, string blob_id )

resource ibase_blob_open ( string blob_id )

ibase_blob_open() opens an existing BLOB for reading. It returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

See also
ibase_blob_close(),
ibase_blob_echo() and
ibase_blob_get().

Prev | Home | Next
ibase_blob_info | Up | ibase_close


ibase_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_close -- Close a connection to an InterBase database

Description

bool ibase_close ( [resource connection_id] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back. Returns TRUE on success or FALSE on failure.

See also ibase_connect() and ibase_pconnect().

Prev | Home | Next
ibase_blob_open | Up | ibase_commit_ret


ibase_commit_ret

(PHP 5)

ibase_commit_ret -- Commit a transaction without closing it

Description

bool ibase_commit_ret ( [resource link_or_trans_identifier] )

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_close | Up | ibase_commit


ibase_commit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_commit -- Commit a transaction

Description

bool ibase_commit ( [resource link_or_trans_identifier] )

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_commit_ret | Up | ibase_connect


ibase_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_connect -- Open a connection to an InterBase database

Description

resource ibase_connect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Example 1. ibase_connect() example

&#60;?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-&#62;email, "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?&#62;

Note: The optional buffers parameter was added in PHP 4.0.0.

Note: The optional dialect parameter was added in PHP 4.0.0 and is functional only with InterBase 6 and up.

Note: The optional role parameter was added in PHP 4.0.0 and is functional only with InterBase 5 and up.

Note: If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

See also ibase_pconnect() and ibase_close().

Prev | Home | Next
ibase_commit | Up | ibase_db_info


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.

Prev | Home | Next
ibase_connect | Up | ibase_delete_user


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.

See also ibase_add_user() and ibase_modify_user().

Prev | Home | Next
ibase_db_info | Up | ibase_drop_db


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. Returns TRUE on success or FALSE on failure.

See also ibase_connect() and ibase_pconnect().

Prev | Home | Next
ibase_delete_user | Up | ibase_errcode


ibase_errcode

(PHP 5)

ibase_errcode -- Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errmsg().

Prev | Home | Next
ibase_drop_db | Up | ibase_errmsg


ibase_errmsg

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_errmsg -- Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errcode().

Prev | Home | Next
ibase_errcode | Up | ibase_execute


ibase_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_execute -- Execute a previously prepared query

Description

resource ibase_execute ( resource query [, mixed bind_arg [, mixed ...]] )

Execute a query prepared by ibase_prepare(). If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

Example 1. ibase_execute() example

&#60;?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
    1 =&#62; 'Eric',
    5 =&#62; 'Filip',
    7 =&#62; 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz =&#62; $bar) {
    ibase_execute($query, $bar, $baz);
}

?&#62;

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.

See also ibase_query().

Prev | Home | Next
ibase_errmsg | Up | ibase_fetch_assoc


ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc -- Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource result [, int fetch_flag] )

ibase_fetch_assoc() returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.

ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_row() and ibase_fetch_object().

Prev | Home | Next
ibase_execute | Up | ibase_fetch_object


ibase_fetch_object

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( resource result_id [, int fetch_flag] )

Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().

&#60;?php
    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row-&#62;email . "\n";
    }
    ibase_close($dbh);
?&#62;

Subsequent calls to ibase_fetch_object() return the next row in the result set, or FALSE if there are no more rows.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_row() and ibase_fetch_assoc().

Prev | Home | Next
ibase_fetch_assoc | Up | ibase_fetch_row


ibase_fetch_row

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource result_identifier [, int fetch_flag] )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ibase_fetch_row() fetches one row of data from the result associated with the specified result_identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_assoc() and ibase_fetch_object().

Prev | Home | Next
ibase_fetch_object | Up | ibase_field_info


ibase_field_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_field_info -- Get information about a field

Description

array ibase_field_info ( resource result, int field_number )

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

&#60;?php
    $rs = ibase_query("SELECT * FROM tablename");
    $coln = ibase_num_fields($rs);
    for ($i = 0; $i &#60; $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";
    }
?&#62;

See also: ibase_num_fields().

Prev | Home | Next
ibase_fetch_row | Up | ibase_free_event_handler


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. Returns TRUE on success or FALSE on failure.

See also ibase_set_event_handler().

Prev | Home | Next
ibase_field_info | Up | ibase_free_query


ibase_free_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_query -- Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource query )

Free a query prepared by ibase_prepare(). Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_free_event_handler | Up | ibase_free_result


ibase_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_result -- Free a result set

Description

bool ibase_free_result ( resource result_identifier )

Frees a result set that has been created by ibase_query() or ibase_execute(). Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_free_query | Up | ibase_gen_id


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.

Returns new generator value as integer, or as string if the value is too big.

Prev | Home | Next
ibase_free_result | Up | ibase_maintain_db


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.

Prev | Home | Next
ibase_gen_id | Up | ibase_modify_user


ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user -- Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only the argument list is available.

See also ibase_add_user() and ibase_delete_user().

Prev | Home | Next
ibase_maintain_db | Up | ibase_name_result


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. Returns TRUE on success or FALSE on failure.

&#60;?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);
    }
?&#62;

See also ibase_prepare() and ibase_execute().

Prev | Home | Next
ibase_modify_user | Up | ibase_num_fields


ibase_num_fields

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_num_fields -- Get the number of fields in a result set

Description

int ibase_num_fields ( resource result_id )

Returns an integer containing the number of fields in a result set.

&#60;?php
    $rs = ibase_query("SELECT * FROM tablename");
    $coln = ibase_num_fields($rs);
    for ($i = 0; $i &#60; $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";
    }
?&#62;

See also: ibase_field_info().

Prev | Home | Next
ibase_name_result | Up | ibase_num_params


ibase_num_params

(PHP 5)

ibase_num_params -- Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource query )

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

See also ibase_prepare() and ibase_param_info().

Prev | Home | Next
ibase_num_fields | Up | ibase_param_info


ibase_param_info

(PHP 5)

ibase_param_info -- Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource query, int param_number )

Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.

See also ibase_field_info() and ibase_num_params().

Prev | Home | Next
ibase_num_params | Up | ibase_pconnect


ibase_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_pconnect -- Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Note: buffers was added in PHP 4.0.0.

Note: dialect was added in PHP 4.0.0. It is functional only with InterBase 6 and versions higher than that.

Note: role was added in PHP 4.0.0. It is functional only with InterBase 5 and versions higher than that.

See also ibase_close() and ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

Prev | Home | Next
ibase_param_info | Up | ibase_prepare


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()).

Prev | Home | Next
ibase_pconnect | Up | ibase_query


ibase_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_query -- Execute a query on an InterBase database

Description

resource ibase_query ( [resource link_identifier, string query [, int bind_args]] )

Performs a query on an InterBase database. If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Example 1. ibase_query() example

&#60;?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());

?&#62;

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.

Note: If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

See also ibase_errmsg(),
ibase_fetch_row(),
ibase_fetch_object(), and
ibase_free_result().

Prev | Home | Next
ibase_prepare | Up | ibase_restore


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.

Prev | Home | Next
ibase_query | Up | ibase_rollback_ret


ibase_rollback_ret

(PHP 5)

ibase_rollback_ret -- Roll back a transaction without closing it

Description

bool ibase_rollback_ret ( [resource link_or_trans_identifier] )

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_restore | Up | ibase_rollback


ibase_rollback

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_rollback -- Roll back a transaction

Description

bool ibase_rollback ( [resource link_or_trans_identifier] )

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ibase_rollback_ret | Up | ibase_server_info


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.

Prev | Home | Next
ibase_rollback | Up | ibase_service_attach


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.

Prev | Home | Next
ibase_server_info | Up | ibase_service_detach


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.

Prev | Home | Next
ibase_service_attach | Up | ibase_set_event_handler


ibase_set_event_handler

(PHP 5)

ibase_set_event_handler -- Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

resource ibase_set_event_handler ( resource connection, callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

This function registers a PHP user function as event handler for the specified events. The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

&#60;?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");
?&#62;

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

See also ibase_free_event_handler() and ibase_wait_event().

Prev | Home | Next
ibase_service_detach | Up | ibase_timefmt


ibase_timefmt

(PHP 3 >= 3.0.6, PHP 4)

ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype] )

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to its documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

&#60;?php
    /* InterBase 6 TIME-type columns will be returned in
     * the form '05 hours 37 minutes'. */
    ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?&#62;

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.

Prev | Home | Next
ibase_set_event_handler | Up | ibase_trans


ibase_trans

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_trans -- Begin a transaction

Description

resource ibase_trans ( [int trans_args [, resource link_identifier]] )

Begins a transaction.

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

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().

Prev | Home | Next
ibase_timefmt | Up | ibase_wait_event


ibase_wait_event

(PHP 5)

ibase_wait_event -- Wait for an event to be posted by the database

Description

string ibase_wait_event ( string event_name1 [, string event_name2 [, string ...]] )

string ibase_wait_event ( resource connection, string event_name1 [, string event_name2 [, string ...]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

See also ibase_set_event_handler() and ibase_free_event_handler().

Prev | Home | Next
ibase_trans | Up | Firebird/Interbase Functions (PDO_FIREBIRD)


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.

&#60;?php
$options = array('autocommit' =&#62; 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.";
}
?&#62;

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.

&#60;?php
$options = array('autocommit' =&#62; 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.";
}
?&#62;

The above example will output:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

See Also

db2_connect()
db2_pconnect()

Prev | Home | Next
IBM DB2, Cloudscape and Apache Derby Functions | Up | db2_bind_param


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().

&#60;?php

$sql = 'SELECT name, breed, weight FROM animals
    WHERE weight &#62; ? AND weight &#60; ?';
$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";
    }
}
?&#62;

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.

&#60;?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";
    }
}
?&#62;

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.

&#60;?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);
?&#62;

See Also

db2_execute()
db2_prepare()

Prev | Home | Next
db2_autocommit | Up | db2_client_info


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.

&#60;?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?&#62;

The above example will output:

Connection was successfully closed.

See Also

db2_connect()
db2_pconnect()

Prev | Home | Next
db2_client_info | Up | db2_column_privileges


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 name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege for the column.
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users.

See Also

db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_close | Up | db2_columns


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 name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
DATA_TYPE | The SQL data type for the column represented as an integer value.
TYPE_NAME | A string representing the data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the column is nullable or not.
REMARKS | Description of the column.
COLUMN_DEF | Default value for the column.
SQL_DATA_TYPE | An integer value representing the size of the column.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the column in the table.
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable.

See Also

db2_column_privileges()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_column_privileges | Up | db2_commit


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.

See Also

db2_autocommit()
db2_rollback()

Prev | Home | Next
db2_columns | Up | db2_conn_error


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().

&#60;?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print "SQLSTATE value: " . db2_conn_error();
}
?&#62;

The above example will output:

SQLSTATE value: 08001

See Also

db2_conn_errormsg()
db2_connect()
db2_stmt_error()
db2_stmt_errormsg()

Prev | Home | Next
db2_commit | Up | db2_conn_errormsg


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().

&#60;?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print db2_conn_errormsg();
}
?&#62;

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

See Also

db2_conn_error()
db2_connect()
db2_stmt_error()
db2_stmt_errormsg()

Prev | Home | Next
db2_conn_error | Up | db2_connect


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: 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.

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.

&#60;?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.";
}
?&#62;

The above example will output:

Connection succeeded.

Example 2. Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

&#60;?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.";
}
?&#62;

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.

&#60;?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' =&#62; 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.";
}
?&#62;

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().

&#60;?php
  $library = "ADC";
  $i5 = db2_connect("", "", "", array("i5_lib"=&#62;"qsys2"));
  $result = db2_exec($i5,
       "select * from systables where table_schema = '$library'");
  while ($row = db2_fetch_both($result)) {
     echo $row['TABLE_NAME']."&#60;/br&#62;";
  }
  db2_close($i5);
?&#62;

The above example will output:

ANIMALS
NAMES
PICTURES

See Also

db2_close()
db2_pconnect()

Prev | Home | Next
db2_conn_errormsg | Up | db2_cursor_type


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()

Prev | Home | Next
db2_connect | Up | db2_exec


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.

&#60;?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... ";
    }
}
?&#62;

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().

&#60;?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
    WHERE weight &#60; 10.0
    ORDER BY name";
if ($conn) {
    require_once('prepare.inc');
    $stmt = db2_exec($conn, $sql, array('cursor' =&#62; DB2_SCROLLABLE));
    while ($row = db2_fetch_array($stmt)) {
        print "$row[0]\n";
    }
}
?&#62;

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.

&#60;?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-&#62;CID     $row-&#62;NAME     $row-&#62;PHONE\n");
}
db2_close($conn);

?&#62;

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.

&#60;?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-&#62;CID     $row-&#62;NAME     $row-&#62;PHONE     $row-&#62;PONUM     $row-&#62;STATUS\n");
}

db2_close($conn);

?&#62;

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).

&#60;?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    &#60;promoList&#62; {
    for $prod in $doc/product
    where $prod/description/price &#60; 10.00
    order by $prod/description/price ascending
    return(
        &#60;promoitem&#62; {
        $prod,
        &#60;startdate&#62; {$start} &#60;/startdate&#62;,
        &#60;enddate&#62; {$end} &#60;/enddate&#62;,
        &#60;promoprice&#62; {$promo} &#60;/promoprice&#62;
        } &#60;/promoitem&#62;
    )
    } &#60;/promoList&#62;
\' 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);

?&#62;

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>

See Also

db2_execute()
db2_prepare()

Prev | Home | Next
db2_cursor_type | Up | db2_execute


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().

&#60;?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.";
    }
}
?&#62;

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.

&#60;?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!";
?&#62;

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.

&#60;?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-&#62;CID     $row-&#62;NAME     $row-&#62;PHONE\n");
    }
}
db2_close($conn);

?&#62;

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.

&#60;?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-&#62;CID     $row-&#62;NAME     $row-&#62;PHONE     $row-&#62;PONUM     $row-&#62;STATUS\n");
    }
}

db2_close($conn);

?&#62;

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).

&#60;?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    &#60;promoList&#62; {
    for $prod in $doc/product
    where $prod/description/price &#60; 10.00
    order by $prod/description/price ascending
    return(
        &#60;promoitem&#62; {
        $prod,
        &#60;startdate&#62; {$start} &#60;/startdate&#62;,
        &#60;enddate&#62; {$end} &#60;/enddate&#62;,
         &#60;promoprice&#62; {$promo} &#60;/promoprice&#62;
            } &#60;/promoitem&#62;
    )
    } &#60;/promoList&#62;
\' 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);

?&#62;

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>

See Also

db2_exec()
db2_fetch_array()
db2_fetch_assoc()
db2_fetch_both()
db2_fetch_row()
db2_prepare()
db2_result()

Prev | Home | Next
db2_exec | Up | db2_fetch_array


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.

&#60;?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']);
}
?&#62;

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.

&#60;?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' =&#62; 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;
}
?&#62;

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

db2_fetch_array()
db2_fetch_both()
db2_fetch_object()
db2_fetch_row()
db2_result()

Prev | Home | Next
db2_fetch_array | Up | db2_fetch_both


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.

&#60;?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]);
}
?&#62;

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.

&#60;?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' =&#62; 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;
}
?&#62;

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

db2_fetch_array()
db2_fetch_assoc()
db2_fetch_object()
db2_fetch_row()
db2_result()

Prev | Home | Next
db2_fetch_assoc | Up | db2_fetch_object


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().

&#60;?php
$sql = 'SELECT name, breed FROM animals WHERE weight &#60; ?';
$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";
}
?&#62;

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().

&#60;?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' =&#62; DB2_SCROLLABLE));
  while ($row = db2_fetch_both($stmt)){
    echo "&#60;br&#62;db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' =&#62; DB2_SCROLLABLE));
  while ($row = db2_fetch_array($stmt)){
    echo "&#60;br&#62;db2_fetch_array {$row[1]}  {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' =&#62; DB2_SCROLLABLE));
  while ($row = db2_fetch_object($stmt)){
    echo "&#60;br&#62;db2_fetch_object {$row-&#62;SPECIFIC_NAME} {$row-&#62;ROUTINE_CREATED}";
  }
  db2_close($conn);
?&#62;

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

See Also

db2_fetch_array()
db2_fetch_assoc()
db2_fetch_both()
db2_fetch_object()
db2_result()

Prev | Home | Next
db2_fetch_object | Up | db2_field_display_size


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.

See Also

db2_field_name()
db2_field_num()
db2_field_precision()
db2_field_scale()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_fetch_row | Up | db2_field_name


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.

See Also

db2_field_display_size()
db2_field_num()
db2_field_precision()
db2_field_scale()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_field_display_size | Up | db2_field_num


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.

See Also

db2_field_display_size()
db2_field_name()
db2_field_precision()
db2_field_scale()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_field_name | Up | db2_field_precision


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.

See Also

db2_field_display_size()
db2_field_name()
db2_field_num()
db2_field_scale()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_field_num | Up | db2_field_scale


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.

See Also

db2_field_display_size()
db2_field_name()
db2_field_num()
db2_field_precision()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_field_precision | Up | db2_field_type


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.

See Also

db2_field_display_size()
db2_field_name()
db2_field_num()
db2_field_precision()
db2_field_scale()
db2_field_width()

Prev | Home | Next
db2_field_scale | Up | db2_field_width


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.

See Also

db2_field_display_size()
db2_field_name()
db2_field_num()
db2_field_precision()
db2_field_scale()
db2_field_type()

Prev | Home | Next
db2_field_type | Up | db2_foreign_keys


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 name | Description
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM | Name of the schema for the table containing the primary key.
PKTABLE_NAME | Name of the table containing the primary key.
PKCOLUMN_NAME | Name of the column containing the primary key.
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key.
FKTABLE_NAME | Name of the table containing the foreign key.
FKCOLUMN_NAME | Name of the column containing the foreign key.
KEY_SEQ | 1-indexed position of the column in the key.
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE.
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE.
FK_NAME | The name of the foreign key.
PK_NAME | The name of the primary key.
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.

See Also

db2_column_privileges()
db2_columns()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_field_width | Up | db2_free_result


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()

Prev | Home | Next
db2_foreign_keys | Up | 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.

See Also

db2_free_result()

Prev | Home | Next
db2_free_result | Up | db2_next_result


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.

&#60;?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);
}
?&#62;

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           "
}

Prev | Home | Next
db2_free_stmt | Up | db2_num_fields


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.

&#60;?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.";
?&#62;

The above example will output:

There are 4 columns in the result set.

See Also

db2_execute()
db2_field_display_size()
db2_field_name()
db2_field_num()
db2_field_precision()
db2_field_scale()
db2_field_type()
db2_field_width()

Prev | Home | Next
db2_next_result | Up | db2_num_rows


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.

Prev | Home | Next
db2_num_fields | Up | db2_pconnect


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.

&#60;?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.";
}
?&#62;

The above example will output:

Persistent connection succeeded.
Second persistent connection succeeded.

See Also

db2_connect()

Prev | Home | Next
db2_num_rows | Up | db2_prepare


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().

&#60;?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);
    }
}
?&#62;

See Also

db2_bind_param()
db2_execute()
db2_stmt_error()
db2_stmt_errormsg()

Prev | Home | Next
db2_pconnect | Up | db2_primary_keys


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 name | Description
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema for the table containing the primary key.
TABLE_NAME | Name of the table containing the primary key.
COLUMN_NAME | Name of the column containing the primary key.
KEY_SEQ | 1-indexed position of the column in the key.
PK_NAME | The name of the primary key.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_prepare | Up | db2_procedure_columns


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 name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
COLUMN_NAME | Name of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return value | Parameter type
1 (SQL_PARAM_INPUT) | Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) | Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT) | Output (OUT) parameter.

DATA_TYPE | The SQL data type for the parameter represented as an integer value.
TYPE_NAME | A string representing the data type for the parameter.
COLUMN_SIZE | An integer value representing the size of the parameter.
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter.
DECIMAL_DIGITS | The scale of the parameter, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the parameter is nullable or not.
REMARKS | Description of the parameter.
COLUMN_DEF | Default value for the parameter.
SQL_DATA_TYPE | An integer value representing the size of the parameter.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement.
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns NULL values and 'NO' means that the parameter does not accept or return NULL values.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_primary_keys | Up | db2_procedures


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 name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETS | Number of result sets returned by the stored procedure.
REMARKS | Any comments about the stored procedure.
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_special_columns()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_procedure_columns | Up | db2_result


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().

&#60;?php
$sql = 'SELECT name, breed FROM animals WHERE weight &#60; ?';
$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";
}
?&#62;

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

See Also

db2_fetch_array()
db2_fetch_assoc()
db2_fetch_both()
db2_fetch_object()
db2_fetch_row()

Prev | Home | Next
db2_procedures | Up | db2_rollback


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.

&#60;?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);
}
?&#62;

The above example will output:

7
0
7

See Also

db2_autocommit()
db2_commit()

Prev | Home | Next
db2_result | Up | db2_server_info


db2_special_columns

(PECL)

db2_special_columns -- Returns a result set listing the unique row identifier columns for a table

Description

resource db2_special_columns ( resource connection, string qualifier, string schema, string table_name, int scope )

Returns a result set listing the unique row identifier columns 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.

table_name

The name of the table.

scope

Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

Return Values

Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:

Column name | Description
SCOPE

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

COLUMN_NAME | Name of the unique column.
DATA_TYPE | SQL data type for the column.
TYPE_NAME | Character string representation of the SQL data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
PSEUDO_COLUMN | Always returns 1.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_statistics()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_set_option | Up | db2_statistics


db2_statistics

(PECL)

db2_statistics -- Returns a result set listing the index and statistics for a table

Description

resource db2_statistics ( resource connection, string qualifier, string schema, string table-name, bool unique )

Returns a result set listing the index and statistics 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 that contains the targeted table. If this parameter is NULL, the statistics and indexes are returned for the schema of the current user.

table_name

The name of the table.

unique

An integer value representing the type of index information to return.

0

Return only the information for unique indexes on the table.

1

Return the information for all indexes on the table.

Return Values

Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
NON_UNIQUE

An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself:

Return value | Parameter type
0 (SQL_FALSE) | The index allows duplicate values.
1 (SQL_TRUE) | The index values must be unique.
NULL | This row is statistics information for the table itself.

INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME | A string representing the name of the index.
TYPE

An integer value representing the type of information contained in this row of the result set:

Return value | Parameter type
0 (SQL_TABLE_STAT) | The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED) | The row contains information about a clustered index.
2 (SQL_INDEX_HASH) | The row contains information about a hashed index.
3 (SQL_INDEX_OTHER) | The row contains information about a type of index that is neither clustered nor hashed.

ORDINAL_POSITION | The 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself.
COLUMN_NAME | The name of the column in the index. NULL if the row contains statistics information about the table itself.
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, NULL if the row contains statistics information about the table itself.
CARDINALITY

If the row contains information about an index, this column contains an integer value representing the number of unique values in the index.

If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table.

PAGES

If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index.

If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table.

FILTER_CONDITION | Always returns NULL.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_table_privileges()
db2_tables()

Prev | Home | Next
db2_special_columns | Up | db2_stmt_error


db2_stmt_error

(PECL)

db2_stmt_error -- Returns a string containing the SQLSTATE returned by an SQL statement

Description

string db2_stmt_error ( [resource stmt] )

Returns a string containing the SQLSTATE value returned by an SQL statement.

If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parameters

stmt

A valid statement resource.

Return Values

Returns a string containing an SQLSTATE value.

See Also

db2_conn_error()
db2_conn_errormsg()
db2_stmt_errormsg()

Prev | Home | Next
db2_statistics | Up | db2_stmt_errormsg


db2_stmt_errormsg

(PECL)

db2_stmt_errormsg -- Returns a string containing the last SQL statement error message

Description

string db2_stmt_errormsg ( [resource stmt] )

Returns a string containing the last SQL statement error message.

If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

Parameters

stmt

A valid statement resource.

Return Values

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

See Also

db2_conn_error()
db2_conn_errormsg()
db2_stmt_error()

Prev | Home | Next
db2_stmt_error | Up | db2_table_privileges


db2_table_privileges

(PECL)

db2_table_privileges -- Returns a result set listing the tables and associated privileges in a database

Description

resource db2_table_privileges ( resource connection [, string qualifier [, string schema [, string table_name]]] )

Returns a result set listing the tables and associated privileges 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 tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

Return Values

Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE.
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_tables()

Prev | Home | Next
db2_stmt_errormsg | Up | db2_tables


db2_tables

(PECL)

db2_tables -- Returns a result set listing the tables and associated metadata in a database

Description

resource db2_tables ( resource connection [, string qualifier [, string schema [, string table-name [, string table-type]]]] )

Returns a result set listing the tables and associated metadata 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 tables. This parameter accepts a search pattern containing _ and % as wildcards.

table-name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

table-type

A list of comma-delimited table type identifiers. To match all table types, pass NULL or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.

Return Values

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
TABLE_TYPE | Table type identifier for the table.
REMARKS | Description of the table.

See Also

db2_column_privileges()
db2_columns()
db2_foreign_keys()
db2_primary_keys()
db2_procedure_columns()
db2_procedures()
db2_special_columns()
db2_statistics()
db2_table_privileges()

Prev | Home | Next
db2_table_privileges | Up | ICAP Functions [removed]


ICAP Functions [removed]

PHP Manual
Prev Next

LIX. ICAP Functions [removed]

Introduction

Note: Icap was removed from PHP. Neither this module, nor those versions of icap library are supported any longer. If you want to use calendar capabilities in PHP, use mcal instead.

Requirements

The icap library has to be installed, which is not longer supported and available.

Installation

To get these functions to work, you have to compile PHP with --with-icap.

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
icap_close -- Close an ICAP stream
icap_create_calendar -- Create a new calendar
icap_delete_calendar -- Delete a calendar
icap_delete_event -- Delete an event from an ICAP calendar
icap_fetch_event -- Fetches an event from the calendar stream/
icap_list_alarms -- Return a list of events that has an alarm triggered at the given datetime
icap_list_events -- Return a list of events between two given datetimes
icap_open -- Opens up an ICAP connection
icap_rename_calendar -- Rename a calendar
icap_reopen -- Reopen ICAP stream to new calendar
icap_snooze -- Snooze an alarm
icap_store_event -- Store an event into an ICAP calendar

Prev | Home | Next
db2_tables | Up | icap_close


icap_close

(no version information, might be only in CVS)

icap_close -- Close an ICAP stream

Description

int icap_close ( int icap_stream [, int flags] )

Closes the given icap stream.

Prev | Home | Next
ICAP Functions [removed] | Up | icap_create_calendar


icap_create_calendar

(PHP 4 <= 4.2.3)

icap_create_calendar -- Create a new calendar

Description

string icap_create_calendar ( int stream_id, string calendar )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
icap_close | Up | icap_delete_calendar


icap_delete_calendar

(PHP 4 <= 4.2.3)

icap_delete_calendar -- Delete a calendar

Description

string icap_delete_calendar ( int stream_id, string calendar )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
icap_create_calendar | Up | icap_delete_event


icap_delete_event

(PHP 4 <= 4.2.3)

icap_delete_event -- Delete an event from an ICAP calendar

Description

string icap_delete_event ( int stream_id, int uid )

icap_delete_event() deletes the calendar event specified by the uid.

Returns TRUE.

Prev | Home | Next
icap_delete_calendar | Up | icap_fetch_event


icap_fetch_event

(PHP 4 <= 4.2.3)

icap_fetch_event -- Fetches an event from the calendar stream/

Description

int icap_fetch_event ( int stream_id, int event_id [, int options] )

icap_fetch_event() fetches an event from the calendar stream specified by event_id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

Prev | Home | Next
icap_delete_event | Up | icap_list_alarms


icap_list_alarms

(PHP 4 <= 4.2.3)

icap_list_alarms -- Return a list of events that has an alarm triggered at the given datetime

Description

int icap_list_alarms ( int stream_id, array date, array time )

Returns an array of event ID's that has an alarm going off at the given datetime.

icap_list_alarms() function takes in a datetime for a calendar stream. An array of event id's that has an alarm should be going off at the datetime are returned.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

Prev | Home | Next
icap_fetch_event | Up | icap_list_events


icap_list_events

(PHP 4 <= 4.2.3)

icap_list_events -- Return a list of events between two given datetimes

Description

array icap_list_events ( int stream_id, int begin_date [, int end_date] )

Returns an array of event ID's that are between the two given datetimes.

icap_list_events() function takes in a beginning datetime and an end datetime for a calendar stream. An array of event id's that are between the given datetimes are returned.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

Prev | Home | Next
icap_list_alarms | Up | icap_open


icap_open

(PHP 4 <= 4.2.3)

icap_open -- Opens up an ICAP connection

Description

resource icap_open ( string calendar, string username, string password, string options )

Returns an ICAP stream on success, FALSE on error.

icap_open() opens up an ICAP connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

Prev | Home | Next
icap_list_events | Up | icap_rename_calendar


icap_rename_calendar

(PHP 4 <= 4.2.3)

icap_rename_calendar -- Rename a calendar

Description

string icap_rename_calendar ( int stream_id, string old_name, string new_name )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
icap_open | Up | icap_reopen


icap_reopen

(PHP 4 <= 4.2.3)

icap_reopen -- Reopen ICAP stream to new calendar

Description

int icap_reopen ( int stream_id, string calendar [, int options] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
icap_rename_calendar | Up | icap_snooze


icap_snooze

(PHP 4 <= 4.2.3)

icap_snooze -- Snooze an alarm

Description

string icap_snooze ( int stream_id, int uid )

icap_snooze() turns on an alarm for a calendar event specified by the uid.

Returns TRUE.

Prev | Home | Next
icap_reopen | Up | icap_store_event


icap_store_event

(PHP 4 <= 4.2.3)

icap_store_event -- Store an event into an ICAP calendar

Description

string icap_store_event ( int stream_id, object event )

icap_store_event() Stores an event into an ICAP calendar. An event object consists of:

  • int public - 1 if public, 0 if private;

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - Number of minutes before the event to send out an alarm.

  • datetime start - datetime object of the start of the event.

  • datetime end - datetime object of the end of the event.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

Returns TRUE on success and FALSE on error.

Prev | Home | Next
icap_snooze | Up | iconv Functions


iconv Functions

PHP Manual
Prev Next

LX. iconv Functions

Introduction

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the GNU libiconv library. It will most likely end up with more consistent results.

Since PHP 5.0.0, this extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.

Requirements

You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the libiconv library installed in your system.

Installation

To use functions provided by this module, the PHP binary must be built with the following configure line: --with-iconv[=DIR].

Note to Windows® Users: In order to enable this module on a Windows® environment, you need to put a DLL file named iconv.dll or iconv-1.3.dll (prior to 4.2.1) which is bundled with the PHP/Win32 binary package into a directory specified by the PATH environment variable or one of the system directories of your Windows® installation.

This module is part of PHP as of PHP 5 thus iconv.dll and php_iconv.dll is not needed anymore.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Iconv configuration options

Name | Default | Changeable | Changelog
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Warning

Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.

Note: Configuration option iconv.input_encoding is currently not used for anything.

Resource Types

This extension has no resource types defined.

Predefined Constants

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

Table 2. iconv constants

Name | Type | Description
ICONV_IMPL | string | The implementation name
ICONV_VERSION | string | The implementation version

Note: Writing implementation-dependent scripts with these constants is strongly discouraged.

Since PHP 5.0.0, the following constants are also available:

Table 3. iconv constants available since PHP 5.0.0

Name | Type | Description
ICONV_MIME_DECODE_STRICT | integer | A bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | A bitmask used for iconv_mime_decode()

See Also

See also GNU Recode functions.

Table of Contents
iconv_get_encoding -- Retrieve internal configuration variables of iconv extension
iconv_mime_decode_headers -- Decodes multiple MIME header fields at once
iconv_mime_decode -- Decodes a MIME header field
iconv_mime_encode -- Composes a MIME header field
iconv_set_encoding -- Set current setting for character encoding conversion
iconv_strlen -- Returns the character count of string
iconv_strpos -- Finds position of first occurrence of a needle within a haystack
iconv_strrpos -- Finds the last occurrence of a needle within a haystack
iconv_substr -- Cut out part of a string
iconv -- Convert string to requested character encoding
ob_iconv_handler -- Convert character encoding as output buffer handler

Prev | Home | Next
icap_store_event | Up | iconv_get_encoding


iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_get_encoding -- Retrieve internal configuration variables of iconv extension

Description

mixed iconv_get_encoding ( [string type] )

Retrieve internal configuration variables of iconv extension.

Parameters

type

The value of the optional type can be:

all
input_encoding
output_encoding
internal_encoding

Return Values

Returns the current value of the internal configuration variable if successful, or FALSE on failure.

If type is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

Examples

Example 1. iconv_get_encoding() example

&#60;pre&#62;
&#60;?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?&#62;
&#60;/pre&#62;

The above example will output:

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

See Also

iconv_set_encoding()
ob_iconv_handler()

Prev | Home | Next
iconv Functions | Up | iconv_mime_decode_headers


iconv_mime_decode_headers

(PHP 5)

iconv_mime_decode_headers -- Decodes multiple MIME header fields at once

Description

array iconv_mime_decode_headers ( string encoded_headers [, int mode [, string charset]] )

Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.

Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.

Parameters

encoded_headers

The encoded headers, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Table 1. Bitmasks acceptable to iconv_mime_decode_headers()

Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.

Examples

Example 1. iconv_mime_decode_headers() example

&#60;?php
$headers_string = &#60;&#60;&#60;EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: &#60;example@example.com&#62;
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for &#60;example@example.com&#62;;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?&#62;

The above example will output:

Array
(
    [Subject] => Prüfung Prüfung
    [To] => example@example.com
    [Date] => Thu, 1 Jan 1970 00:00:00 +0000
    [Message-Id] => <example@example.com>
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
        )

)

See Also

iconv_mime_decode()
mb_decode_mimeheader()
imap_mime_header_decode()
imap_base64()
imap_qprint()

Prev | Home | Next
iconv_get_encoding | Up | iconv_mime_decode


iconv_mime_decode

(PHP 5)

iconv_mime_decode -- Decodes a MIME header field

Description

string iconv_mime_decode ( string encoded_header [, int mode [, string charset]] )

Decodes a MIME header field.

Parameters

encoded_header

The encoded header, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Table 1. Bitmasks acceptable to iconv_mime_decode()

Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.

Return Values

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

Examples

Example 1. iconv_mime_decode() example

&#60;?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?&#62;

See Also

iconv_mime_decode_headers()
mb_decode_mimeheader()
imap_mime_header_decode()
imap_base64()
imap_qprint()

Prev | Home | Next
iconv_mime_decode_headers | Up | iconv_mime_encode


iconv_mime_encode

(PHP 5)

iconv_mime_encode -- Composes a MIME header field

Description

string iconv_mime_encode ( string field_name, string field_value [, array preferences] )

Composes and returns a string that represents a valid MIME header field, which looks like the following:

Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

Parameters

field_name

The field name.

field_value

The field value.

preferences

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.

Table 1. Configuration items supported by iconv_mime_encode()

Item | Type | Description | Default value | Example
scheme | boolean | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_charset ini setting. | iconv.internal_charset | ISO-8859-1
output-charset | string | Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. | iconv.internal_charset | UTF-8
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n

Return Values

Returns an encoded MIME field on success, or FALSE if an error occurs during the encoding.

Examples

Example 1. iconv_mime_encode() example

&#60;?php
$preferences = array(
    "input-charset" =&#62; "ISO-8859-1",
    "output-charset" =&#62; "UTF-8",
    "line-length" =&#62; 76,
    "line-break-chars" =&#62; "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung_Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?&#62;

See Also

imap_binary()
mb_encode_mimeheader()
imap_8bit()

Prev | Home | Next
iconv_mime_decode | Up | iconv_set_encoding


iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_set_encoding -- Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string type, string charset )

Changes the value of the internal configuration variable specified by type to charset.

Parameters

type

The value of type can be any one of those:

input_encoding
output_encoding
internal_encoding

charset

The character set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. iconv_set_encoding() example

&#60;?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?&#62;

See Also

iconv_get_encoding()
ob_iconv_handler()

Prev | Home | Next
iconv_mime_encode | Up | iconv_strlen


iconv_strlen

(PHP 5)

iconv_strlen -- Returns the character count of string

Description

int iconv_strlen ( string str [, string charset] )

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.

Parameters

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_charset.

Return Values

Returns the character count of str, as an integer.

See Also

strlen()
mb_strlen()

Prev | Home | Next
iconv_set_encoding | Up | iconv_strpos


iconv_strpos

(PHP 5)

iconv_strpos -- Finds position of first occurrence of a needle within a haystack

Description

int iconv_strpos ( string haystack, string needle [, int offset [, string charset]] )

Finds position of first occurrence of a needle within a haystack.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parameters

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the first occurrence of needle in haystack.

If needle is not found, iconv_strpos() will return 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.

See Also

strpos()
iconv_strrpos()
mb_strpos()

Prev | Home | Next
iconv_strlen | Up | iconv_strrpos


iconv_strrpos

(PHP 5)

iconv_strrpos -- Finds the last occurrence of a needle within a haystack

Description

int iconv_strrpos ( string haystack, string needle [, string charset] )

In contrast to strpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found.

Parameters

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the last occurrence of needle in haystack. The characters are counted on the basis of the specified character set charset.

If needle is not found, iconv_strrpos() will return 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.

See Also

strrpos()
iconv_strpos()
mb_strrpos()

Prev | Home | Next
iconv_strpos | Up | iconv_substr


iconv_substr

(PHP 5)

iconv_substr -- Cut out part of a string

Description

string iconv_substr ( string str, int offset [, int length [, string charset]] )

Cuts a portion of str specified by the offset and length parameters.

Parameters

str

The original string.

offset

If offset is non-negative, iconv_substr() cuts the portion out of str beginning at offset'th character, counting from zero.

If offset is negative, iconv_substr() cuts out the portion beginning at the position, offset characters away from the end of str.

length

If length is given and is positive, the return value will contain at most length characters of the portion that begins at offset (depending on the length of string).

If negative length is passed, iconv_substr() cuts the portion out of str from the offset'th character up to the character that is length characters away from the end of the string. In case offset is also negative, the start position is calculated beforehand according to the rule explained above.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.

Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset, whilst the counterpart substr() always takes these for byte offsets.

Return Values

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned.

See Also

substr()
mb_substr()
mb_strcut()

Prev | Home | Next
iconv_strrpos | Up | iconv


iconv

(PHP 4 >= 4.0.5, PHP 5)

iconv -- Convert string to requested character encoding

Description

string iconv ( string in_charset, string out_charset, string str )

Performs a character set conversion on the string str from in_charset to out_charset.

Parameters

in_charset

The input charset.

out_charset

The output charset.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character.

str

The string to be converted.

Return Values

Returns the converted string or FALSE on failure.

Examples

Example 1. iconv() example

&#60;?php
echo iconv("ISO-8859-1", "UTF-8", "This is a test.");
?&#62;

Prev | Home | Next
iconv_substr | Up | ob_iconv_handler


ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5)

ob_iconv_handler -- Convert character encoding as output buffer handler

Description

string ob_iconv_handler ( string contents, int status )

Converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined in the php.ini file or in iconv_set_encoding().

Parameters

See ob_start() for information about this handler parameters.

Return Values

See ob_start() for information about this handler return values.

Examples

Example 1. ob_iconv_handler() example:

&#60;?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?&#62;

See Also

iconv_get_encoding()
iconv_set_encoding()
output-control functions

Prev | Home | Next
iconv | Up | ID3 Functions


ID3 Functions

PHP Manual
Prev Next

LXI. ID3 Functions

Introduction

These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.

Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.

Requirements

No external libraries are needed to build this extension.

Installation

id3 is part of PECL and can be installed using the PEAR installer. To compile PHP with id3 support, download the sourcecode, put it in php-src/ext/id3 and compile PHP using --enable-id3.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.

ID3_V1_0 (integer)

ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.

ID3_V1_1 (integer)

ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.

ID3_V2_1 (integer)

ID3_V2_1 is used if you are working with ID3 V2.1 tags.

ID3_V2_2 (integer)

ID3_V2_2 is used if you are working with ID3 V2.2 tags.

ID3_V2_3 (integer)

ID3_V2_3 is used if you are working with ID3 V2.3 tags.

ID3_V2_4 (integer)

ID3_V2_4 is used if you are working with ID3 V2.4 tags.

ID3_BEST (integer)

ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.

Table of Contents
id3_get_frame_long_name -- Get the long name of an ID3v2 frame
id3_get_frame_short_name -- Get the short name of an ID3v2 frame
id3_get_genre_id -- Get the id for a genre
id3_get_genre_list -- Get all possible genre values
id3_get_genre_name -- Get the name for a genre id
id3_get_tag -- Get all information stored in an ID3 tag
id3_get_version -- Get version of an ID3 tag
id3_remove_tag -- Remove an existing ID3 tag
id3_set_tag -- Update information stored in an ID3 tag

Prev | Home | Next
ob_iconv_handler | Up | id3_get_frame_long_name


id3_get_frame_long_name

(PECL)

id3_get_frame_long_name -- Get the long name of an ID3v2 frame

Description

string id3_get_frame_long_name ( string frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame long name or FALSE on errors.

Examples

Example 1. id3_get_frame_long_name() example

&#60;?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?&#62;

The above example will output:

Original lyricist(s)/text writer(s)

See Also

id3_get_frame_short_name()

Prev | Home | Next
ID3 Functions | Up | id3_get_frame_short_name


id3_get_frame_short_name

(PECL)

id3_get_frame_short_name -- Get the short name of an ID3v2 frame

Description

string id3_get_frame_short_name ( string frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame short name or FALSE on errors.

The values returned by id3_get_short_name() are used in the array returned by id3_get_tag().

Examples

Example 1. id3_get_frame_short_name() example

&#60;?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?&#62;

The above example will output:

originalLyricist

See Also

id3_get_frame_long_name()

Prev | Home | Next
id3_get_frame_long_name | Up | id3_get_genre_id


id3_get_genre_id

(PECL)

id3_get_genre_id -- Get the id for a genre

Description

int id3_get_genre_id ( string genre )

id3_get_genre_id() returns the id for a genre.

Parameters

genre

An integer ranging from 0 to 147

Return Values

The genre id or FALSE on errors.

Examples

Example 1. id3_get_genre_id() example

&#60;?php
$id = id3_get_genre_id("Alternative");
echo $id;
?&#62;

The above example will output:

20

See Also

id3_get_genre_name()
id3_get_genre_list()

Prev | Home | Next
id3_get_frame_short_name | Up | id3_get_genre_list


id3_get_genre_list

(PECL)

id3_get_genre_list -- Get all possible genre values

Description

array id3_get_genre_list ( void )

id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.

This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.

Return Values

Returns an array containing all possible genres that may be stored in an ID3 tag.

Examples

Example 1. id3_get_genre_list() example

&#60;?php
$genres = id3_get_genre_list();
print_r($genres);
?&#62;

The above example will output:

Array
(
    [0] => Blues
    [1] => Classic Rock
    [2] => Country
    [3] => Dance
    [4] => Disco
    [5] => Funk
    [6] => Grunge
    [7] => Hip-Hop
    [8] => Jazz
    [9] => Metal
    [10] => New Age
    [11] => Oldies
    [12] => Other
    [13] => Pop
    [14] => R&B
    [15] => Rap
    [16] => Reggae
    [17] => Rock
    [18] => Techno
    [19] => Industrial
    [20] => Alternative
    [21] => Ska
    [22] => Death Metal
    [23] => Pranks
    [24] => Soundtrack
    [25] => Euro-Techno
    [26] => Ambient
    [27] => Trip-Hop
    [28] => Vocal
    [29] => Jazz+Funk
    [30] => Fusion
    [31] => Trance
    [32] => Classical
    [33] => Instrumental
    [34] => Acid
    [35] => House
    [36] => Game
    [37] => Sound Clip
    [38] => Gospel
    [39] => Noise
    [40] => Alternative Rock
    [41] => Bass
    [42] => Soul
    [43] => Punk
    [44] => Space
    [45] => Meditative
    [46] => Instrumental Pop
    [47] => Instrumental Rock
    [48] => Ethnic
    [49] => Gothic
    [50] => Darkwave
    [51] => Techno-Industrial
    [52] => Electronic
    [53] => Pop-Folk
    [54] => Eurodance
    [55] => Dream
    [56] => Southern Rock
    [57] => Comedy
    [58] => Cult
    [59] => Gangsta
    [60] => Top 40
    [61] => Christian Rap
    [62] => Pop/Funk
    [63] => Jungle
    [64] => Native US
    [65] => Cabaret
    [66] => New Wave
    [67] => Psychadelic
    [68] => Rave
    [69] => Showtunes
    [70] => Trailer
    [71] => Lo-Fi
    [72] => Tribal
    [73] => Acid Punk
    [74] => Acid Jazz
    [75] => Polka
    [76] => Retro
    [77] => Musical
    [78] => Rock & Roll
    [79] => Hard Rock
    [80] => Folk
    [81] => Folk-Rock
    [82] => National Folk
    [83] => Swing
    [84] => Fast Fusion
    [85] => Bebob
    [86] => Latin
    [87] => Revival
    [88] => Celtic
    [89] => Bluegrass
    [90] => Avantgarde
    [91] => Gothic Rock
    [92] => Progressive Rock
    [93] => Psychedelic Rock
    [94] => Symphonic Rock
    [95] => Slow Rock
    [96] => Big Band
    [97] => Chorus
    [98] => Easy Listening
    [99] => Acoustic
    [100] => Humour
    [101] => Speech
    [102] => Chanson
    [103] => Opera
    [104] => Chamber Music
    [105] => Sonata
    [106] => Symphony
    [107] => Booty Bass
    [108] => Primus
    [109] => Porn Groove
    [110] => Satire
    [111] => Slow Jam
    [112] => Club
    [113] => Tango
    [114] => Samba
    [115] => Folklore
    [116] => Ballad
    [117] => Power Ballad
    [118] => Rhytmic Soul
    [119] => Freestyle
    [120] => Duet
    [121] => Punk Rock
    [122] => Drum Solo
    [123] => Acapella
    [124] => Euro-House
    [125] => Dance Hall
    [126] => Goa
    [127] => Drum & Bass
    [128] => Club-House
    [129] => Hardcore
    [130] => Terror
    [131] => Indie
    [132] => BritPop
    [133] => Negerpunk
    [134] => Polsk Punk
    [135] => Beat
    [136] => Christian Gangsta
    [137] => Heavy Metal
    [138] => Black Metal
    [139] => Crossover
    [140] => Contemporary C
    [141] => Christian Rock
    [142] => Merengue
    [143] => Salsa
    [144] => Thrash Metal
    [145] => Anime
    [146] => JPop
    [147] => SynthPop
)

See Also

id3_get_genre_name()
id3_get_genre_id()

Prev | Home | Next
id3_get_genre_id | Up | id3_get_genre_name


id3_get_genre_name

(PECL)

id3_get_genre_name -- Get the name for a genre id

Description

string id3_get_genre_name ( int genre_id )

id3_get_genre_name() returns the name for a genre id.

Parameters

genre_id

An integer ranging from 0 to 147

Return Values

Returns the name as a string.

Examples

Example 1. id3_get_genre_name() example

&#60;?php
$genre = id3_get_genre_name(20);
echo $genre;
?&#62;

The above example will output:

Alternative

See Also

id3_get_genre_list()
id3_get_genre_id()

Prev | Home | Next
id3_get_genre_list | Up | id3_get_tag


id3_get_tag

(PECL)

id3_get_tag -- Get all information stored in an ID3 tag

Description

array id3_get_tag ( string filename [, int version] )

id3_get_tag() is used to get all information stored in the id3 tag of the specified file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.

Return Values

Returns an associative array with various keys like: title, artist, ..

The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.

Examples

Example 1. id3_get_tag() example

&#60;?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?&#62;

The above example will output something similar to:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Example 2. id3_get_tag() example

&#60;?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?&#62;

The above example will output something similar to:

Array
(
    [copyright] => Dirty Mac
    [originalArtist] => Dirty Mac
    [composer] => Marcus Götze
    [artist] => Dirty Mac
    [title] => Little Big Man
    [album] => Demo-Tape
    [track] => 5/12
    [genre] => (17)Rock
    [year] => 2001
)

See Also

id3_set_tag()
id3_remove_tag()
id3_get_version()

Prev | Home | Next
id3_get_genre_name | Up | id3_get_version


id3_get_version

(PECL)

id3_get_version -- Get version of an ID3 tag

Description

int id3_get_version ( string filename )

id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.

If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

Return Values

Returns the version number of the ID3 tag of the file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.

Examples

Example 1. id3_get_version() example

&#60;?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version &#38; ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version &#38; ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version &#38; ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?&#62;

The above example will output something similar to:

Contains a 1.x tag
Contains a 1.1 tag

See Also

id3_set_tag()
id3_get_tag()
id3_remove_tag()

Prev | Home | Next
id3_get_tag | Up | id3_remove_tag


id3_remove_tag

(PECL)

id3_remove_tag -- Remove an existing ID3 tag

Description

bool id3_remove_tag ( string filename [, int version] )

id3_remove_tag() is used to remove the information stored of an ID3 tag.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. id3_remove_tag() example

&#60;?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully removed\n";
}
?&#62;

If the file is writable and contained a 1.0 tag, this will output:

Tag succesfully removed

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.

See Also

id3_set_tag()
id3_get_tag()
id3_get_version()

Prev | Home | Next
id3_get_version | Up | id3_set_tag


id3_set_tag

(PECL)

id3_set_tag -- Update information stored in an ID3 tag

Description

bool id3_set_tag ( string filename, array tag [, int version] )

id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

tag

An associative array of tag keys and values

The following keys may be used in the associative array:

Table 1. Keys in the associative array

key | possible value | available in version
title | string with maximum of 30 characters | v1.0, v1.1
artist | string with maximum of 30 characters | v1.0, v1.1
album | string with maximum of 30 characters | v1.0, v1.1
year | 4 digits | v1.0, v1.1
genre | integer value between 0 and 147 | v1.0, v1.1
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1
track | integer between 0 and 255 | v1.1

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. id3_set_tag() example

&#60;?php
$data = array(
              "title" =&#62; "Re:Start",
              "artist" =&#62; "Re:\Legion",
              "comment" =&#62; "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully updated\n";
}
?&#62;

If the file is writable, this will output:

Tag succesfully updated

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1.

See Also

id3_remove_tag()
id3_get_tag()
id3_get_version()

Prev | Home | Next
id3_remove_tag | Up | IIS Administration Functions


Informix Functions

PHP Manual
Prev Next

LXVI. Informix Functions

Introduction

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.2.1.

Requirements

Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.

Installation

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Note: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is true for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).

Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:

configuration variable: ifx.textasvarchar

configuration variable: ifx.byteasvarchar

runtime functions:

ifx_textasvarchar(0): use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns

ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable: ifx.blobinfile

runtime function:

ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable

ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Table 1. Informix configuration options

Name | Default | Changeable | Changelog
ifx.allow_persistent | "1" | PHP_INI_SYSTEM |
ifx.max_persistent | "-1" | PHP_INI_SYSTEM |
ifx.max_links | "-1" | PHP_INI_SYSTEM |
ifx.default_host | NULL | PHP_INI_SYSTEM |
ifx.default_user | NULL | PHP_INI_SYSTEM |
ifx.default_password | NULL | PHP_INI_SYSTEM |
ifx.blobinfile | "1" | PHP_INI_ALL |
ifx.textasvarchar | "0" | PHP_INI_ALL |
ifx.byteasvarchar | "0" | PHP_INI_ALL |
ifx.charasvarchar | "0" | PHP_INI_ALL |
ifx.nullformat | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().

Resource Types

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.

IFX_SCROLL (integer)

IFX_HOLD (integer)

IFX_LO_RDONLY (integer)

IFX_LO_WRONLY (integer)

IFX_LO_APPEND (integer)

IFX_LO_RDWR (integer)

IFX_LO_BUFFER (integer)

IFX_LO_NOBUFFER (integer)

Table of Contents
ifx_affected_rows -- Get number of rows affected by a query
ifx_blobinfile_mode -- Set the default blob mode for all select queries
ifx_byteasvarchar -- Set the default byte mode
ifx_close -- Close Informix connection
ifx_connect -- Open Informix server connection
ifx_copy_blob -- Duplicates the given blob object
ifx_create_blob -- Creates an blob object
ifx_create_char -- Creates an char object
ifx_do -- Execute a previously prepared SQL-statement
ifx_error -- Returns error code of last Informix call
ifx_errormsg -- Returns error message of last Informix call
ifx_fetch_row -- Get row as an associative array
ifx_fieldproperties -- List of SQL fieldproperties
ifx_fieldtypes -- List of Informix SQL fields
ifx_free_blob -- Deletes the blob object
ifx_free_char -- Deletes the char object
ifx_free_result -- Releases resources for the query
ifx_get_blob -- Return the content of a blob object
ifx_get_char -- Return the content of the char object
ifx_getsqlca -- Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_htmltbl_result -- Formats all rows of a query into a HTML table
ifx_nullformat -- Sets the default return value on a fetch row
ifx_num_fields -- Returns the number of columns in the query
ifx_num_rows -- Count the rows already fetched from a query
ifx_pconnect -- Open persistent Informix connection
ifx_prepare -- Prepare an SQL-statement for execution
ifx_query -- Send Informix query
ifx_textasvarchar -- Set the default text mode
ifx_update_blob -- Updates the content of the blob object
ifx_update_char -- Updates the content of the char object
ifxus_close_slob -- Deletes the slob object
ifxus_create_slob -- Creates an slob object and opens it
ifxus_free_slob -- Deletes the slob object
ifxus_open_slob -- Opens an slob object
ifxus_read_slob -- Reads nbytes of the slob object
ifxus_seek_slob -- Sets the current file or seek position
ifxus_tell_slob -- Returns the current file or seek position
ifxus_write_slob -- Writes a string into the slob object

Prev | Home | Next
imap_utf8 | Up | ifx_affected_rows


ifx_affected_rows

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( resource result_id )

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

Parameters

result_id

A valid result id returned by ifx_query() or ifx_prepare().

Return Values

Returns the number of rows as an integer.

Examples

Example 1. Informix affected rows

&#60;?php
$rid = ifx_prepare("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount &#62; 1000) {
    printf ("Too many rows in result set (%d)\n&#60;br /&#62;", $rowcount);
    die ("Please restrict your query&#60;br /&#62;\n");
}
?&#62;

See Also

ifx_num_rows()

Prev | Home | Next
Informix Functions | Up | ifx_blobinfile_mode


ifx_blobinfile_mode

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

bool ifx_blobinfile_mode ( int mode )

Set the default blob mode for all select queries.

Parameters

mode

Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ifx_affected_rows | Up | ifx_byteasvarchar


ifx_byteasvarchar

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_byteasvarchar -- Set the default byte mode

Description

bool ifx_byteasvarchar ( int mode )

Sets the default byte mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_textasvarchar()

Prev | Home | Next
ifx_blobinfile_mode | Up | ifx_close


ifx_close

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_close -- Close Informix connection

Description

bool ifx_close ( [resource link_identifier] )

ifx_close() closes the link to an Informix database that's associated with the specified link identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

Parameters

link_identifier

The link identifier. If not specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Closing a Informix connection

&#60;?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?&#62;

See Also

ifx_connect()
ifx_pconnect()

Prev | Home | Next
ifx_byteasvarchar | Up | ifx_connect


ifx_connect

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_connect -- Open Informix server connection

Description

resource ifx_connect ( [string database [, string userid [, string password]]] )

ifx_connect() establishes a connection to an Informix server.

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns a connection identifier on success, or FALSE on error.

Examples

Example 1. Connect to a Informix database

&#60;?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?&#62;

See Also

ifx_pconnect()
ifx_close()

Prev | Home | Next
ifx_close | Up | ifx_copy_blob


ifx_copy_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid )

Duplicates the given blob object.

Parameters

bid

A BLOB identifier.

Return Values

Returns the new blob object-id, or FALSE on errors.

See Also

ifx_create_blob()
ifx_free_blob()

Prev | Home | Next
ifx_connect | Up | ifx_create_blob


ifx_create_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param )

Creates a blob object.

Parameters

type

1 = TEXT, 0 = BYTE

mode

0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param

if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return Values

Returns the new BLOB object-id, or FALSE on errors.

See Also

ifx_copy_blob()
ifx_free_blob()

Prev | Home | Next
ifx_copy_blob | Up | ifx_create_char


ifx_create_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param )

Creates an char object.

Parameters

param

The char content.

Return Values

Returns the new char object id, or FALSE on errors.

See Also

ifx_free_char()

Prev | Home | Next
ifx_create_blob | Up | ifx_do


ifx_do

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_do -- Execute a previously prepared SQL-statement

Description

bool ifx_do ( resource result_id )

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows().

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

Example 1. ifx_do() Example

&#60;?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?&#62;

See Also

ifx_prepare()

Prev | Home | Next
ifx_create_char | Up | ifx_error


ifx_error

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( [resource link_identifier] )

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed.

Parameters

link_identifier

The link identifier.

Return Values

The Informix error codes (SQLSTATE & SQLCODE) formatted as x [SQLSTATE = aa bbb SQLCODE=cccc].

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

See Also

ifx_errormsg()

Prev | Home | Next
ifx_do | Up | ifx_errormsg


ifx_errormsg

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode] )

Returns the Informix error message associated with the most recent Informix error.

Parameters

errorcode

If specified, the function will return the message corresponding to the specified code.

Return Values

Return the error message, as a string.

Examples

Example 1. ifx_errormsg() example

printf("%s\n&#38;lt;br&#62;", ifx_errormsg(-201));

See Also

ifx_error()

Prev | Home | Next
ifx_error | Up | ifx_fetch_row


ifx_fetch_row

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fetch_row -- Get row as an associative array

Description

array ifx_fetch_row ( resource result_id [, mixed position] )

Fetches one row of data from the result associated with the specified result identifier.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position

An optional parameter for a "fetch" operation on "scroll" cursors: NEXT, PREVIOUS, CURRENT, FIRST, LAST or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values.

Examples

Example 1. Informix fetch rows

&#60;?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount &#62; 1000) {
    printf ("Too many rows in result set (%d)\n&#60;br /&#62;", $rowcount);
    die ("Please restrict your query&#60;br /&#62;\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n&#60;br /&#62;");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?&#62;

Prev | Home | Next
ifx_errormsg | Up | ifx_fieldproperties


ifx_fieldproperties

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( resource result_id )

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on errors.

Examples

Example 1. Informix SQL fieldproperties

&#60;?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname =&#62; $val) {
    echo "$fname:\t property = $val\n";
}
?&#62;

See Also

ifx_fieldtypes()

Prev | Home | Next
ifx_fetch_row | Up | ifx_fieldtypes


ifx_fieldtypes

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( resource result_id )

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for the query associated with result_id.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Examples

Example 1. Fieldnames and SQL fieldtypes

&#60;?php
$types = ifx_fieldtypes($resultid);
if (is_array($types)) {
    foreach ($types as $fname =&#62; $val) {
        echo "$fname:\t type = $val\n";
    }
}
?&#62;

See Also

ifx_fieldproperties()

Prev | Home | Next
ifx_fieldproperties | Up | ifx_free_blob


ifx_free_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_free_blob -- Deletes the blob object

Description

bool ifx_free_blob ( int bid )

Deletes the blobobject for the given blob object-id.

Parameters

bid

The BLOB object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_create_blob()

Prev | Home | Next
ifx_fieldtypes | Up | ifx_free_char


ifx_free_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_free_char -- Deletes the char object

Description

bool ifx_free_char ( int bid )

Deletes the charobject for the given char object-id.

Parameters

bid

The char object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_create_char()

Prev | Home | Next
ifx_free_blob | Up | ifx_free_result


ifx_free_result

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_free_result -- Releases resources for the query

Description

bool ifx_free_result ( resource result_id )

Releases resources for the query associated with result_id.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_do()

Prev | Home | Next
ifx_free_char | Up | ifx_get_blob


ifx_get_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_get_blob -- Return the content of a blob object

Description

string ifx_get_blob ( int bid )

Returns the content of the blob object.

Parameters

bid

The BLOB object id.

Return Values

The contents of the BLOB as a string, or FALSE on errors.

See Also

ifx_get_char()

Prev | Home | Next
ifx_free_result | Up | ifx_get_char


ifx_get_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_get_char -- Return the content of the char object

Description

string ifx_get_char ( int bid )

Returns the content of the char object.

Parameters

bid

The char object-id.

Return Values

Returns the contents as a string, or FALSE on errors.

See Also

ifx_get_blob()

Prev | Home | Next
ifx_get_blob | Up | ifx_getsqlca


ifx_getsqlca

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ifx_getsqlca -- Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( resource result_id )

Returns a pseudo-row with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a SELECT dbinfo('sqlca.sqlerrdx') query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Parameters

result_id

result_id is a valid result id returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with the following entries: sqlerrd0, sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.

Examples

Example 1. Retrieve Informix sqlca.sqlerrd[x] values

&#60;?php
/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable
                  values (0, '2nd column', 'another column') ", $connid);
if (!$qid) {
    /* ... error ... */
}
$sqlca = ifx_getsqlca($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : $serial_value&#60;br /&#62;\n";
?&#62;

Prev | Home | Next
ifx_get_char | Up | ifx_htmltbl_result


ifx_htmltbl_result

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_htmltbl_result -- Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( resource result_id [, string html_table_options] )

Formats and prints all rows of the result_id query into a HTML table.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

html_table_options

This optional argument is a string of <table> tag options.

Return Values

Returns the number of fetched rows, or FALSE on errors.

Examples

Example 1. Informix results as HTML table

&#60;?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount &#62; 1000) {
    printf ("Too many rows in result set (%d)\n&#60;br /&#62;", $rowcount);
    die ("Please restrict your query&#60;br /&#62;\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?&#62;

Prev | Home | Next
ifx_getsqlca | Up | ifx_nullformat


ifx_nullformat

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_nullformat -- Sets the default return value on a fetch row

Description

bool ifx_nullformat ( int mode )

Sets the default return value of a NULL-value on a fetch row.

Parameters

mode

Mode "0" returns "", and mode "1" returns "NULL".

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ifx_htmltbl_result | Up | ifx_num_fields


ifx_num_fields

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( resource result_id )

After preparing or executing a query, this call gives you the number of columns in the query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of columns in query for result_id, or FALSE on errors.

Examples

Example 1. ifx_num_fields() Example

&#60;?php
$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
echo ifx_num_fields($res_id);
?&#62;

See Also

ifx_num_rows()

Prev | Home | Next
ifx_nullformat | Up | ifx_num_rows


ifx_num_rows

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( resource result_id )

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of fetched rows or FALSE on errors.

See Also

ifx_num_fields()

Prev | Home | Next
ifx_num_fields | Up | ifx_pconnect


ifx_pconnect

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_pconnect -- Open persistent Informix connection

Description

resource ifx_pconnect ( [string database [, string userid [, string password]]] )

ifx_pconnect() acts very much like ifx_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 (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns: valid Informix persistent link identifier on success, or FALSE on errors.

See Also

ifx_connect()

Prev | Home | Next
ifx_num_rows | Up | ifx_prepare


ifx_prepare

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_prepare -- Prepare an SQL-statement for execution

Description

resource ifx_prepare ( string query, resource link_identifier [, int cursor_def, mixed blobidarray] )

Prepares a query for later use with ifx_do().

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns a valid result identifier for use by ifx_do(), or FALSE on errors.

See Also

ifx_do()

Prev | Home | Next
ifx_pconnect | Up | ifx_query


ifx_query

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_query -- Send Informix query

Description

resource ifx_query ( string query, resource link_identifier [, int cursor_type [, mixed blobidarray]] )

Sends a query to the currently active database on the server that's associated with the specified link identifier.

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. I you omit this parameter the cursor is a normal sequential cursor.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns valid Informix result identifier on success, or FALSE on errors.

Examples

Example 1. Show all rows of the "orders" table as a HTML table

&#60;?php
ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n&#60;br /&#62;%s&#60;br /&#62;\n", ifx_error());
    ifx_errormsg();
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?&#62;

Example 2. Insert some values into the "catalog" table

&#60;?php

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");

// store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;

// launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
    /* ... error ... */
}

// free result id
ifx_free_result($res_id);
?&#62;

See Also

ifx_connect()

Prev | Home | Next
ifx_prepare | Up | ifx_textasvarchar


ifx_textasvarchar

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_textasvarchar -- Set the default text mode

Description

bool ifx_textasvarchar ( int mode )

Sets the default text mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_bytesasvarchar()

Prev | Home | Next
ifx_query | Up | ifx_update_blob


ifx_update_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_update_blob -- Updates the content of the blob object

Description

bool ifx_update_blob ( int bid, string content )

Updates the content of the blob object for the given blob object bid.

Parameters

bid

A BLOB object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_update_char()

Prev | Home | Next
ifx_textasvarchar | Up | ifx_update_char


ifx_update_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_update_char -- Updates the content of the char object

Description

bool ifx_update_char ( int bid, string content )

Updates the content of the char object for the given char object bid.

Parameters

bid

A char object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifx_update_blob()

Prev | Home | Next
ifx_update_blob | Up | ifxus_close_slob


ifxus_close_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_close_slob -- Deletes the slob object

Description

bool ifxus_close_slob ( int bid )

Deletes the slob object on the given slob object-id bid.

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifxus_open_slob()

Prev | Home | Next
ifx_update_char | Up | ifxus_create_slob


ifxus_create_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode )

Creates an slob object and opens it.

Parameters

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Return the new slob object-id, or FALSE on errors.

See Also

ifxus_close_slob()
ifxus_free_slob()

Prev | Home | Next
ifxus_close_slob | Up | ifxus_free_slob


ifxus_free_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_free_slob -- Deletes the slob object

Description

bool ifxus_free_slob ( int bid )

Deletes the slob object.

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ifxus_close_slob()

Prev | Home | Next
ifxus_create_slob | Up | ifxus_open_slob


ifxus_open_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( int bid, int mode )

Opens an slob object. bid should be an existing slob id.

Parameters

bid

An existing slob id.

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Returns the new slob object-id, or FALSE on errors.

See Also

ifxus_close_slob()
ifxus_free_slob()

Prev | Home | Next
ifxus_free_slob | Up | ifxus_read_slob


ifxus_read_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_read_slob -- Reads nbytes of the slob object

Description

string ifxus_read_slob ( int bid, int nbytes )

Reads nbytes of the slob object.

Parameters

bid

An existing slob id.

nbytes

The number of bytes to read.

Return Values

Returns the slob contents as a string, or FALSE on errors.

See Also

ifxus_write_slob()

Prev | Home | Next
ifxus_open_slob | Up | ifxus_seek_slob


ifxus_seek_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( int bid, int mode, int offset )

Sets the current file or seek position of an open slob object.

Parameters

bid

An existing slob id.

mode

0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.

offset

A byte offset.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

ifxus_tell_slob()

Prev | Home | Next
ifxus_read_slob | Up | ifxus_tell_slob


ifxus_tell_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( int bid )

Returns the current file or seek position of an open slob object

Parameters

bid

An existing slob id.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

ifxus_seek_slob()

Prev | Home | Next
ifxus_seek_slob | Up | ifxus_write_slob


ifxus_write_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( int bid, string content )

Writes a string into the slob object.

Parameters

bid

An existing slob id.

content

The content to write, as a string.

Return Values

Returns the bytes written as an integer, or FALSE on errors.

See Also

ifxus_read_slob()

Prev | Home | Next
ifxus_tell_slob | Up | Informix Functions (PDO_INFORMIX)


IIS Administration Functions

PHP Manual
Prev Next

LXII. IIS Administration Functions

Introduction

This PECL extension is not bundled with PHP. This extension is available for Win32 only. It provides functions to administrate Microsoft Internet Information Server (IIS). The extension includes function to create web sites and virtual directories as well as configuring security and script mapping. These functions have been added in PHP 4.

In order to use these functions you must enable the php_iisfunc.dll DLL inside of php.ini. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

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 defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

IIS_READ (integer)

IIS_WRITE (integer)

IIS_EXECUTE (integer)

IIS_SCRIPT (integer)

IIS_ANONYMOUS (integer)

IIS_BASIC (integer)

IIS_NTLM (integer)

IIS_STARTING (integer)

IIS_STOPPED (integer)

IIS_PAUSED (integer)

IIS_RUNNING (integer)

Table of Contents
iis_add_server -- Creates a new virtual web server
iis_get_dir_security -- Gets Directory Security
iis_get_script_map -- Gets script mapping on a virtual directory for a specific extension
iis_get_server_by_comment -- Return the instance number associated with the Comment
iis_get_server_by_path -- Return the instance number associated with the Path
iis_get_server_rights -- Gets server rights
iis_get_service_state -- Returns the state for the service defined by ServiceId
iis_remove_server -- Removes the virtual web server indicated by ServerInstance
iis_set_app_settings -- Creates application scope for a virtual directory
iis_set_dir_security -- Sets Directory Security
iis_set_script_map -- Sets script mapping on a virtual directory
iis_set_server_rights -- Sets server rights
iis_start_server -- Starts the virtual web server
iis_start_service -- Starts the service defined by ServiceId
iis_stop_server -- Stops the virtual web server
iis_stop_service -- Stops the service defined by ServiceId

Prev | Home | Next
id3_set_tag | Up | iis_add_server


iis_add_server

(PECL)

iis_add_server -- Creates a new virtual web server

Description

int iis_add_server ( string path, string comment, string server_ip, int port, string host_name, int rights, int start_server )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
IIS Administration Functions | Up | iis_get_dir_security


iis_get_dir_security

(PECL)

iis_get_dir_security -- Gets Directory Security

Description

int iis_get_dir_security ( int server_instance, string virtual_path )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_add_server | Up | iis_get_script_map


iis_get_script_map

(PECL)

iis_get_script_map -- Gets script mapping on a virtual directory for a specific extension

Description

string iis_get_script_map ( int server_instance, string virtual_path, string script_extension )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_get_dir_security | Up | iis_get_server_by_comment


iis_get_server_by_comment

(PECL)

iis_get_server_by_comment -- Return the instance number associated with the Comment

Description

int iis_get_server_by_comment ( string comment )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_get_script_map | Up | iis_get_server_by_path


iis_get_server_by_path

(PECL)

iis_get_server_by_path -- Return the instance number associated with the Path

Description

int iis_get_server_by_path ( string path )

Each virtual server in IIS is associated with an instance number. iis_get_server_by_path() finds the instance number from the actual path to the root directory.

Parameters

path

The path to the root directory

Return Values

Returns the server instance number.

Prev | Home | Next
iis_get_server_by_comment | Up | iis_get_server_rights


iis_get_server_rights

(PECL)

iis_get_server_rights -- Gets server rights

Description

int iis_get_server_rights ( int server_instance, string virtual_path )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_get_server_by_path | Up | iis_get_service_state


iis_get_service_state

(PECL)

iis_get_service_state -- Returns the state for the service defined by ServiceId

Description

int iis_get_service_state ( string service_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_get_server_rights | Up | iis_remove_server


iis_remove_server

(PECL)

iis_remove_server -- Removes the virtual web server indicated by ServerInstance

Description

int iis_remove_server ( int server_instance )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_get_service_state | Up | iis_set_app_settings


iis_set_app_settings

(PECL)

iis_set_app_settings -- Creates application scope for a virtual directory

Description

int iis_set_app_settings ( int server_instance, string virtual_path, string application_scope )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_remove_server | Up | iis_set_dir_security


iis_set_dir_security

(PECL)

iis_set_dir_security -- Sets Directory Security

Description

int iis_set_dir_security ( int server_instance, string virtual_path, int directory_flags )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_set_app_settings | Up | iis_set_script_map


iis_set_script_map

(PECL)

iis_set_script_map -- Sets script mapping on a virtual directory

Description

int iis_set_script_map ( int server_instance, string virtual_path, string script_extension, string engine_path, int allow_scripting )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_set_dir_security | Up | iis_set_server_rights


iis_set_server_rights

(PECL)

iis_set_server_rights -- Sets server rights

Description

int iis_set_server_rights ( int server_instance, string virtual_path, int directory_flags )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_set_script_map | Up | iis_start_server


iis_start_server

(PECL)

iis_start_server -- Starts the virtual web server

Description

int iis_start_server ( int server_instance )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_set_server_rights | Up | iis_start_service


iis_start_service

(PECL)

iis_start_service -- Starts the service defined by ServiceId

Description

int iis_start_service ( string service_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_start_server | Up | iis_stop_server


iis_stop_server

(PECL)

iis_stop_server -- Stops the virtual web server

Description

int iis_stop_server ( int server_instance )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_start_service | Up | iis_stop_service


iis_stop_service

(PECL)

iis_stop_service -- Stops the service defined by ServiceId

Description

int iis_stop_service ( string service_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iis_stop_server | Up | Image Functions


Image Functions

PHP Manual
Prev Next

LXIII. Image Functions

Introduction

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library.

Note: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

Requirements

If you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

Note: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since its codebase is better maintained and more stable.

Note: Support for GD 1.x has been removed as of PHP 6.0.0, which requires GD 2.0.33 or later.

You may wish to enhance GD to handle more image formats.

Table 1. Supported image formats

Image format | Library to download | Notes
gif |  | Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.
jpeg-6b | ftp://ftp.uu.net/graphics/jpeg/ |
png | http://www.libpng.org/pub/png/libpng.html | Only supported in GD versions greater than gd-1.6.
xpm | ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Table 2. Supported font libraries

Font library | Download | Notes
FreeType 1.x | http://www.freetype.org/ | Support removed as of PHP 6.0.0
FreeType 2 | http://www.freetype.org/ |
T1lib | ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts.

Installation

To enable GD-support configure PHP --with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option --with-gd. GD library requires libpng and libjpeg to compile.

In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.

To disable GD support in PHP 3 add --without-gd to your configure line.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Table 3. Supported image formats

Image Format | Configure Switch
jpeg-6b | To enable support for jpeg-6b add --with-jpeg-dir=DIR.
png | To enable support for png add --with-png-dir=DIR. Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line.
xpm | To enable support for xpm add --with-xpm-dir=DIR. If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Note: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

Enhance the capabilities of GD to deal with different fonts by specifying the --with-XXXX configure switch to your PHP configure line.

Table 4. Supported font libraries

Font library | Configure Switch
FreeType 1.x | To enable support for FreeType 1.x add --with-ttf[=DIR].
FreeType 2 | To enable support for FreeType 2 add --with-freetype-dir=DIR.
T1lib | To enable support for T1lib (Postscript Type 1 fonts) add --with-t1lib[=DIR].
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf.

Runtime Configuration

There are no image specific configurations but you may be interested in the exif extension directives.

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.

IMG_GIF (integer)

IMG_JPG (integer)

IMG_JPEG (integer)

IMG_PNG (integer)

IMG_WBMP (integer)

IMG_XPM (integer)

IMG_COLOR_TILED (integer)

IMG_COLOR_STYLED (integer)

IMG_COLOR_BRUSHED (integer)

IMG_COLOR_STYLEDBRUSHED (integer)

IMG_COLOR_TRANSPARENT (integer)

IMG_ARC_ROUNDED (integer)

IMG_ARC_PIE (integer)

IMG_ARC_CHORD (integer)

IMG_ARC_NOFILL (integer)

IMG_ARC_EDGED (integer)

IMAGETYPE_GIF (integer)

IMAGETYPE_JPEG (integer)

IMAGETYPE_PNG (integer)

IMAGETYPE_SWF (integer)

IMAGETYPE_PSD (integer)

IMAGETYPE_BMP (integer)

IMAGETYPE_WBMP (integer)

IMAGETYPE_XBM (integer)

IMAGETYPE_TIFF_II (integer)

IMAGETYPE_TIFF_MM (integer)

IMAGETYPE_IFF (integer)

IMAGETYPE_JB2 (integer)

IMAGETYPE_JPC (integer)

IMAGETYPE_JP2 (integer)

IMAGETYPE_JPX (integer)

IMAGETYPE_SWC (integer)

PNG_NO_FILTER (integer)

PNG_FILTER_NONE (integer)

PNG_FILTER_SUB (integer)

PNG_FILTER_UP (integer)

PNG_FILTER_AVG (integer)

PNG_FILTER_PAETH (integer)

PNG_ALL_FILTERS (integer)

Examples

Example 1. PNG creation with PHP

&#60;?php

header("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
imagedestroy($im);

?&#62;
This example would be called from a page with a tag like: <img src="button.php?text=text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

Table of Contents
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_extension -- Get file extension for image type
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Output image to browser or file
imagealphablending -- Set the blending mode for an image
imageantialias -- Should antialias functions be used or not
imagearc -- Draws an arc
imagechar -- Draw a character horizontally
imagecharup -- Draw a character vertically
imagecolorallocate -- Allocate a color for an image
imagecolorallocatealpha -- Allocate a color for an image
imagecolorat -- Get the index of the color of a pixel
imagecolorclosest -- Get the index of the closest color to the specified color
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate -- De-allocate a color for an image
imagecolorexact -- Get the index of the specified color
imagecolorexactalpha -- Get the index of the specified color + alpha
imagecolormatch -- Makes the colors of the palette version of an image more closely match the true color version
imagecolorresolve -- Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternative
imagecolorset -- Set the color for the specified palette index
imagecolorsforindex -- Get the colors for an index
imagecolorstotal -- Find out the number of colors in an image's palette
imagecolortransparent -- Define a color as transparent
imageconvolution -- Apply a 3x3 convolution matrix, using coefficient and offset
imagecopy -- Copy part of an image
imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an image with gray scale
imagecopyresampled -- Copy and resize part of an image with resampling
imagecopyresized -- Copy and resize part of an image
imagecreate -- Create a new palette based image
imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
imagedashedline -- Draw a dashed line
imagedestroy -- Destroy an image
imageellipse -- Draw an ellipse
imagefill -- Flood fill
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
imagefilledpolygon -- Draw a filled polygon
imagefilledrectangle -- Draw a filled rectangle
imagefilltoborder -- Flood fill to specific color
imagefilter -- Applies a filter to an image
imagefontheight -- Get font height
imagefontwidth -- Get font width
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
imagegammacorrect -- Apply a gamma correction to a GD image
imagegd2 -- Output GD2 image to browser or file
imagegd -- Output GD image to browser or file
imagegif -- Output image to browser or file
imageinterlace -- Enable or disable interlace
imageistruecolor -- Finds whether an image is a truecolor image
imagejpeg -- Output image to browser or file
imagelayereffect -- Set the alpha blending flag to use the bundled libgd layering effects
imageline -- Draw a line
imageloadfont -- Load a new font
imagepalettecopy -- Copy the palette from one image to another
imagepng -- Output a PNG image to either the browser or a file
imagepolygon -- Draws a polygon
imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepsencodefont -- Change the character encoding vector of a font
imagepsextendfont -- Extend or condense a font
imagepsfreefont -- Free memory used by a PostScript Type 1 font
imagepsloadfont -- Load a PostScript Type 1 font from file
imagepsslantfont -- Slant a font
imagepstext -- Draws a text over an image using PostScript Type1 fonts
imagerectangle -- Draw a rectangle
imagerotate -- Rotate an image with a given angle
imagesavealpha -- Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
imagesetbrush -- Set the brush image for line drawing
imagesetpixel -- Set a single pixel
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
imagestring -- Draw a string horizontally
imagestringup -- Draw a string vertically
imagesx -- Get image width
imagesy -- Get image height
imagetruecolortopalette -- Convert a true color image to a palette image
imagettfbbox -- Give the bounding box of a text using TrueType fonts
imagettftext -- Write text to the image using TrueType fonts
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
imagexbm -- Output XBM image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse -- Parse a binary IPTC block into single tags.
jpeg2wbmp -- Convert JPEG image file to WBMP image file
png2wbmp -- Convert PNG image file to WBMP image file

Prev | Home | Next
iis_stop_service | Up | gd_info


gd_info

(PHP 4 >= 4.3.0, PHP 5)

gd_info -- Retrieve information about the currently installed GD library

Description

array gd_info ( void )

Gets information about the version and capabilities of the installed GD library.

Return Values

Returns an associative array.

Table 1. Elements of array returned by gd_info()

Attribute | Meaning
GD Version | string value describing the installed libgd version.
Freetype Support | boolean value. TRUE if Freetype Support is installed.
Freetype Linkage | string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE.
T1Lib Support | boolean value. TRUE if T1Lib support is included.
GIF Read Support | boolean value. TRUE if support for reading GIF images is included.
GIF Create Support | boolean value. TRUE if support for creating GIF images is included.
JPG Support | boolean value. TRUE if JPG support is included.
PNG Support | boolean value. TRUE if PNG support is included.
WBMP Support | boolean value. TRUE if WBMP support is included.
XBM Support | boolean value. TRUE if XBM support is included.

Examples

Example 1. Using gd_info()

&#60;?php
var_dump(gd_info());
?&#62;

The above example will output something similar to:

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

See Also

imagepng()
imagejpeg()
imagegif()
imagewbmp()
imagetypes()

Prev | Home | Next
Image Functions | Up | getimagesize


getimagesize

(PHP 3, PHP 4, PHP 5)

getimagesize -- Get the size of an image

Description

array getimagesize ( string filename [, array &imageinfo] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML <IMG> tag and the correspondant HTTP content type.

getimagesize() can also return some more information in imageinfo parameter.

Note: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

Parameters

filename

imageinfo

This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Return Values

Returns an array with 5 elements.

Index 0 and 1 contains respectively the width and the height of the image.

Note: Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

mime is the correspondant MIME type of the image. This information can be used to deliver images with correct the HTTP Content-type header:

Example 1. getimagesize() and MIME types

&#60;?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size &#38;&#38; $fp) {
    header("Content-type: {$size['mime']}");
    fpassthru($fp);
    exit;
} else {
    // error
}
?&#62;

channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color. However, for some image types, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, FALSE is returned.

Errors/Exceptions

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING.

ChangeLog

Version | Description
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available.
4.3.2 | JPEG 2000 support was added for the imageinfo parameter.
4.3.0 | bits and channels are present for other image types, too.
4.3.0 | mime was added.
4.3.0 | Support for SWC was added.
4.2.0 | Support for TIFF was added.
4.0.5 | URL support was added.

Examples

Example 2. getimagesize (file)

&#60;?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "&#60;img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" /&#62;";
?&#62;

Example 3. getimagesize (URL)

&#60;?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?&#62;

Example 4. getimagesize() returning IPTC

&#60;?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?&#62;

Notes

Note: The getimagesize() function does not require the GD image library.

See Also

image_type_to_mime_type()
exif_imagetype()
exif_read_data()
exif_thumbnail()

Prev | Home | Next
gd_info | Up | image_type_to_extension


image_type_to_extension

(no version information, might be only in CVS)

image_type_to_extension -- Get file extension for image type

Description

string image_type_to_extension ( int imagetype [, bool include_dot] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Wether to prepend a dot to the extension or not. Default to TRUE.

Return Values

A string with the extension corresponding to the given image type.

Prev | Home | Next
getimagesize | Up | image_type_to_mime_type


image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5)

image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Description

string image_type_to_mime_type ( int imagetype )

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constants

Return Values

The returned values are as follows

Table 1. Returned values Constants

imagetype | Returned value
IMAGETYPE_GIF | image/gif
IMAGETYPE_JPEG | image/jpeg
IMAGETYPE_PNG | image/png
IMAGETYPE_SWF | application/x-shockwave-flash
IMAGETYPE_PSD | image/psd
IMAGETYPE_BMP | image/bmp
IMAGETYPE_TIFF_II (intel byte order) | image/tiff
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff
IMAGETYPE_JPC | application/octet-stream
IMAGETYPE_JP2 | image/jp2
IMAGETYPE_JPX | application/octet-stream
IMAGETYPE_JB2 | application/octet-stream
IMAGETYPE_SWC | application/x-shockwave-flash
IMAGETYPE_IFF | image/iff
IMAGETYPE_WBMP | image/vnd.wap.wbmp
IMAGETYPE_XBM | image/xbm

Examples

Example 1. image_type_to_mime_type (file)

&#60;?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?&#62;

Notes

Note: This function does not require the GD image library.

See Also

getimagesize()
exif_imagetype()
exif_read_data()
exif_thumbnail()

Prev | Home | Next
image_type_to_extension | Up | image2wbmp


image2wbmp

(PHP 4 >= 4.0.5, PHP 5)

image2wbmp -- Output image to browser or file

Description

bool image2wbmp ( resource image [, string filename [, int threshold]] )

image2wbmp() outputs or save a WBMP version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

Path to the saved file. If not given, the raw image stream will be outputed directly.

threshold

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. image2wbmp() example

&#60;?php

$file = 'php.png';
$image = imagecreatefrompng($file);

header('Content-type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // output the stream directly

?&#62;

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

imagewbmp()

Prev | Home | Next
image_type_to_mime_type | Up | imagealphablending


imagealphablending

(PHP 4 >= 4.0.6, PHP 5)

imagealphablending -- Set the blending mode for an image

Description

bool imagealphablending ( resource image, bool blendmode )

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

blendmode

Wether to enable the blending mode or not. Default to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Prev | Home | Next
image2wbmp | Up | imageantialias


imageantialias

(PHP 4 >= 4.3.2, PHP 5)

imageantialias -- Should antialias functions be used or not

Description

bool imageantialias ( resource image, bool on )

Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Thickness and styled are not supported.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

on

Wether to enable antialiasing or not.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

imagecreatetruecolor()

Prev | Home | Next
imagealphablending | Up | imagearc


imagearc

(PHP 3, PHP 4, PHP 5)

imagearc -- Draws an arc

Description

bool imagearc ( resource image, int cx, int cy, int width, int height, int start, int end, int color )

imagearc() draws an arc of circle centered at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center

cy

y-coordinate of the center

width

The arc width

height

The arc height

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Drawing a circle with imagearc()

&#60;?php

// create a 200*200 image
$img = imagecreatetruecolor(200, 200);

// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$red   = imagecolorallocate($img, 255,   0,   0);
$green = imagecolorallocate($img,   0, 255,   0);
$blue  = imagecolorallocate($img,   0,   0, 255);

// draw the head
imagearc($img, 100, 100, 200, 200,  0, 360, $white);
// mouth
imagearc($img, 100, 100, 150, 150, 25, 155, $red);
// left and then the right eye
imagearc($img,  60,  75,  50,  50,  0, 360, $green);
imagearc($img, 140,  75,  50,  50,  0, 360, $blue);

// output image in the browser
header("Content-type: image/png");
imagepng($img);

// free memory
imagedestroy($img);

?&#62;

The above example will output something similar to:

See Also

imagefilledarc()
imageellipse()
imagefilledellipse()

Prev | Home | Next
imageantialias | Up | imagechar


imagechar

(PHP 3, PHP 4, PHP 5)

imagechar -- Draw a character horizontally

Description

bool imagechar ( resource image, int font, int x, int y, string c, int color )

imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start

y

y-coordinate of the start

c

The character to draw

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagechar() example

&#60;?php

$im = imagecreate(100, 100);

$string = 'PHP';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "P" in the top left corner
imagechar($im, 1, 0, 0, $string, $black);

header('Content-type: image/png');
imagepng($im);

?&#62;

The above example will output something similar to:

See Also

imagecharup()
imageloadfont()

Prev | Home | Next
imagearc | Up | imagecharup


imagecharup

(PHP 3, PHP 4, PHP 5)

imagecharup -- Draw a character vertically

Description

bool imagecharup ( resource image, int font, int x, int y, string c, int color )

Draws the character c vertically at the specified coordinate on the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start

y

y-coordinate of the start

c

The character to draw

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagecharup() example

&#60;?php

$im = imagecreate(100, 100);

$string = 'Note that the first letter is a N';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "Z" on a white background
imagecharup($im, 3, 10, 10, $string, $black);

header('Content-type: image/png');
imagepng($im);

?&#62;

The above example will output something similar to:

See Also

imagechar()
imageloadfont()

Prev | Home | Next
imagechar | Up | imagecolorallocate


imagecolorallocate

(PHP 3, PHP 4, PHP 5)

imagecolorallocate -- Allocate a color for an image

Description

int imagecolorallocate ( resource image, int red, int green, int blue )

Returns a color identifier representing the color composed of the given RGB components.

imagecolorallocate() must be called to create each color that is to be used in the image represented by image.

Note: The first call to imagecolorallocate() fills the background color in palette-based images - images created using imagecreate().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

ChangeLog

Version | Description
Prior to 5.1.3 | Returns -1 if the allocation failed.

Examples

Example 1. imagecolorallocate() example

&#60;?php

$im = imagecreate(100, 100);

// sets background to red
$background = imagecolorallocate($im, 255, 0, 0);

// sets some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// hexadecimal way
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

?&#62;

See Also

imagecolorallocatealpha()
imagecolordeallocate()

Prev | Home | Next
imagecharup | Up | imagecolorallocatealpha


imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5)

imagecolorallocatealpha -- Allocate a color for an image

Description

int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha )

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

ChangeLog

Version | Description
Prior to 5.1.3 | Returns -1 if the allocation failed.

Examples

Example 1. Example of using imagecolorallocatealpha()

&#60;?php
$size = 300;
$image=imagecreatetruecolor($size, $size);

// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);

$yellow_x = 100;
$yellow_y = 75;
$red_x    = 120;
$red_y    = 165;
$blue_x   = 187;
$blue_y   = 125;
$radius   = 150;

// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red    = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue   = imagecolorallocatealpha($image, 0, 0, 255, 75);

// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);

// don't forget to output a correct header!
header('Content-type: image/png');

// and finally, output the result
imagepng($image);
imagedestroy($image);
?&#62;

The above example will output something similar to:

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecolorallocate()
imagecolordeallocate()

Prev | Home | Next
imagecolorallocate | Up | imagecolorat


imagecolorat

(PHP 3, PHP 4, PHP 5)

imagecolorat -- Get the index of the color of a pixel

Description

int imagecolorat ( resource image, int x, int y )

Returns the index of the color of the pixel at the specified location in the image specified by image.

If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of the point

y

y-coordinate of the point

Return Values

Returns the index of the color.

Examples

Example 1. Access distinct RGB values

&#60;?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb &#62;&#62; 16) &#38; 0xFF;
$g = ($rgb &#62;&#62; 8) &#38; 0xFF;
$b = $rgb &#38; 0xFF;
?&#62;

The above example will output something similar to:

int(119)
int(123)
int(180)

See Also

imagecolorset()
imagecolorsforindex()

Prev | Home | Next
imagecolorallocatealpha | Up | imagecolorclosest


imagecolorclosest

(PHP 3, PHP 4, PHP 5)

imagecolorclosest -- Get the index of the closest color to the specified color

Description

int imagecolorclosest ( resource image, int red, int green, int blue )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the closest color, in the palette of the image, to the specified one

See Also

imagecolorexact()

Prev | Home | Next
imagecolorat | Up | imagecolorclosestalpha


imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource image, int red, int green, int blue, int alpha )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the closest color in the palette.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecolorexactalpha()

Prev | Home | Next
imagecolorclosest | Up | imagecolorclosesthwb


imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5)

imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color

Description

int imagecolorclosesthwb ( resource image, int red, int green, int blue )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

Prev | Home | Next
imagecolorclosestalpha | Up | imagecolordeallocate


imagecolordeallocate

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

imagecolordeallocate -- De-allocate a color for an image

Description

bool imagecolordeallocate ( resource image, int color )

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

color

The color identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Using imagecolordeallocate()

&#60;?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?&#62;

See Also

imagecolorallocate()
imagecolorallocatealpha()

Prev | Home | Next
imagecolorclosesthwb | Up | imagecolorexact


imagecolorexact

(PHP 3, PHP 4, PHP 5)

imagecolorexact -- Get the index of the specified color

Description

int imagecolorexact ( resource image, int red, int green, int blue )

Returns the index of the specified color in the palette of the image.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

Returns the index of the specified color in the palette, or -1 if the color does not exist.

See Also

imagecolorclosest()

Prev | Home | Next
imagecolordeallocate | Up | imagecolorexactalpha


imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorexactalpha -- Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource image, int red, int green, int blue, int alpha )

Returns the index of the specified color+alpha in the palette of the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the specified color+alpha in the palette of the image, or -1 if the color does not exist in the image's palette.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecolorclosestalpha()

Prev | Home | Next
imagecolorexact | Up | imagecolormatch


imagecolormatch

(PHP 4 >= 4.3.0, PHP 5)

imagecolormatch -- Makes the colors of the palette version of an image more closely match the true color version

Description

bool imagecolormatch ( resource image1, resource image2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image1

A truecolor image link resource

image2

A palette image link resource pointing to an image that has the same size as image1

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecreatetruecolor()

Prev | Home | Next
imagecolorexactalpha | Up | imagecolorresolve


imagecolorresolve

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imagecolorresolve -- Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( resource image, int red, int green, int blue )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

Returns a color index.

See Also

imagecolorclosest()

Prev | Home | Next
imagecolormatch | Up | imagecolorresolvealpha


imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource image, int red, int green, int blue, int alpha )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component

green

Value of green component

blue

Value of blue component

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns a color index.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecolorclosestalpha()

Prev | Home | Next
imagecolorresolve | Up | imagecolorset


imagecolorset

(PHP 3, PHP 4, PHP 5)

imagecolorset -- Set the color for the specified palette index

Description

void imagecolorset ( resource image, int index, int red, int green, int blue )

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

An index in the palette

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

No value is returned.

See Also

imagecolorat()

Prev | Home | Next
imagecolorresolvealpha | Up | imagecolorsforindex


imagecolorsforindex

(PHP 3, PHP 4, PHP 5)

imagecolorsforindex -- Get the colors for an index

Description

array imagecolorsforindex ( resource image, int index )

Gets the color for a specified index.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

Return Values

Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.

Examples

Example 1. imagecolorsforindex() example

&#60;?php

// open an image
$im = imagecreatefrompng('nexen.png');

// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);

// what is it ?
print_r($color_tran);

?&#62;

The above example will output something similar to:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

See Also

imagecolorat()
imagecolorexact()

Prev | Home | Next
imagecolorset | Up | imagecolorstotal


imagecolorstotal

(PHP 3, PHP 4, PHP 5)

imagecolorstotal -- Find out the number of colors in an image's palette

Description

int imagecolorstotal ( resource image )

Returns the number of colors in an image palette.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns the number of colors in the specified image's palette or 0 for truecolor images.

See Also

imagecolorat()
imagecolorsforindex()
imageistruecolor()

Prev | Home | Next
imagecolorsforindex | Up | imagecolortransparent


imagecolortransparent

(PHP 3, PHP 4, PHP 5)

imagecolortransparent -- Define a color as transparent

Description

int imagecolortransparent ( resource image [, int color] )

Sets the transparent color in the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

color

A color identifier created with imagecolorallocate()

Return Values

The identifier of the new (or current, if none is specified) transparent color is returned.

Notes

Note: Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.

Note: The transparent color is a property of the image, transparency is not a property of the color. Once you have set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

Prev | Home | Next
imagecolorstotal | Up | imageconvolution


imagecopy

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

imagecopy -- Copy part of an image

Description

bool imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

dst_x

x-coordinate of destination point

dst_y

y-coordinate of destination point

src_x

x-coordinate of source point

src_y

y-coordinate of source point

src_w

Source width

src_h

Source height

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imageconvolution | Up | imagecopymerge


imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge -- Copy and merge part of an image

Description

bool imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

dst_x

x-coordinate of destination point

dst_y

y-coordinate of destination point

src_x

x-coordinate of source point

src_y

y-coordinate of source point

src_w

Source width

src_h

Source height

pct

The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagecopy | Up | imagecopymergegray


imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

bool imagecopymergegray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

dst_x

x-coordinate of destination point

dst_y

y-coordinate of destination point

src_x

x-coordinate of source point

src_y

y-coordinate of source point

src_w

Source width

src_h

Source height

pct

The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagecopymerge | Up | imagecopyresampled


imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5)

imagecopyresampled -- Copy and resize part of an image with resampling

Description

bool imagecopyresampled ( resource dst_image, resource src_image, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h )

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

dst_x

x-coordinate of destination point

dst_y

y-coordinate of destination point

src_x

x-coordinate of source point

src_y

y-coordinate of source point

dst_w

Destination width

dst_h

Destination height

src_w

Source width

src_h

Source height

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Simple example

This example will resample an image to half its original size.

&#60;?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?&#62;

The above example will output something similar to:

Example 2. Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

&#60;?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height &#62; $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?&#62;

The above example will output something similar to:

Notes

Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See Also

imagecopyresized()

Prev | Home | Next
imagecopymergegray | Up | imagecopyresized


imagecopyresized

(PHP 3, PHP 4, PHP 5)

imagecopyresized -- Copy and resize part of an image

Description

bool imagecopyresized ( resource dst_image, resource src_image, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h )

imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

dst_x

x-coordinate of destination point

dst_y

y-coordinate of destination point

src_x

x-coordinate of source point

src_y

y-coordinate of source point

dst_w

Destination width

dst_h

Destination height

src_w

Source width

src_h

Source height

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Resizing an image

This example will display the image at half size.

&#60;?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?&#62;

The above example will output something similar to:

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

Notes

Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See Also

imagecopyresampled()

Prev | Home | Next
imagecopyresampled | Up | imagecreate


imagecreate

(PHP 3, PHP 4, PHP 5)

imagecreate -- Create a new palette based image

Description

resource imagecreate ( int width, int height )

imagecreate() returns an image identifier representing a blank image of specified size.

We recommend the use of imagecreatetruecolor().

Parameters

width

The image width

height

The image height

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example 1. Creating a new GD image stream and outputting an image.

&#60;?php
header("Content-type: image/png");
$im = @imagecreate(110, 20)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?&#62;

The above example will output something similar to:

See Also

imagedestroy()
imagecreatetruecolor()

Prev | Home | Next
imagecopyresized | Up | imagecreatefromgd2


imagecreatefromgd2

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd2 -- Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string filename )

Warning

This function is currently not documented; only the argument list is available.

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 M for a list of supported URL protocols.

Parameters

filename

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

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.

Prev | Home | Next
imagecreate | Up | imagecreatefromgd2part


imagecreatefromgd2part

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height )

Warning

This function is currently not documented; only the argument list is available.

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 M for a list of supported URL protocols.

Parameters

filename

srcX

srcY

width

height

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

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.

Prev | Home | Next
imagecreatefromgd2 | Up | imagecreatefromgd


imagecreatefromgd

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd -- Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string filename )

Warning

This function is currently not documented; only the argument list is available.

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 M for a list of supported URL protocols.

Parameters

filename

Notes

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.

Prev | Home | Next
imagecreatefromgd2part | Up | imagecreatefromgif


imagecreatefromgif

(PHP 3, PHP 4, PHP 5)

imagecreatefromgif -- Create a new image from file or URL

Description

resource imagecreatefromgif ( string filename )

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

To ease debugging the following example will produce an error GIF:

Example 1. Example to handle an error during creation

&#60;?php
function LoadGif ($imgname)
{
    $im = @imagecreatefromgif ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = imagecreatetruecolor (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
header("Content-Type: image/gif");
$img = LoadGif("bogus.image");
imagegif($img);
?&#62;

The above example will output something similar to:

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 M for a list of supported URL protocols.

Parameters

filename

Path to the GIF image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Notes

Note: GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.

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.

Prev | Home | Next
imagecreatefromgd | Up | imagecreatefromjpeg


imagecreatefromjpeg

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagecreatefromjpeg -- Create a new image from file or URL

Description

resource imagecreatefromjpeg ( string filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

Example 1. Example to handle an error during creation

&#60;?php
function LoadJpeg($imgname)
{
    $im = @imagecreatefromjpeg($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor(150, 30); /* Create a black image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
header("Content-Type: image/jpeg");
$img = LoadJpeg("bogus.image");
imagejpeg($img);
?&#62;

The above example will output something similar to:

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 M for a list of supported URL protocols.

Parameters

filename

Path to the JPEG image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Notes

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

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.

Prev | Home | Next
imagecreatefromgif | Up | imagecreatefrompng


imagecreatefrompng

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagecreatefrompng -- Create a new image from file or URL

Description

resource imagecreatefrompng ( string filename )

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

Example 1. Example to handle an error during creation

&#60;?php
function LoadPNG($imgname)
{
    $im = @imagecreatefrompng($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
header("Content-Type: image/png");
$img = LoadPNG("bogus.image");
imagepng($img);
?&#62;

The above example will output something similar to:

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 M for a list of supported URL protocols.

Parameters

filename

Path to the PNG image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Notes

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.

Prev | Home | Next
imagecreatefromjpeg | Up | imagecreatefromstring


imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring -- Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string data )

imagecreatefromstring() returns an image identifier representing the image obtained from the given data These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

Parameters

image

A string containing the image data

Return Values

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

Examples

Example 1. imagecreatefromstring() example

&#60;?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
}
else {
    echo 'An error occurred.';
}
?&#62;

The above example will output something similar to:

See Also

imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromgif()
imagecreatetruecolor()

Prev | Home | Next
imagecreatefrompng | Up | imagecreatefromwbmp


imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp -- Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

Example 1. Example to handle an error during creation

&#60;?php
function LoadWBMP($imgname)
{
    $im = @imagecreatefromwbmp($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?&#62;

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 M for a list of supported URL protocols.

Parameters

filename

Path to the WBMP image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

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.

Prev | Home | Next
imagecreatefromstring | Up | imagecreatefromxbm


imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxbm -- Create a new image from file or URL

Description

resource imagecreatefromxbm ( string filename )

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

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 M for a list of supported URL protocols.

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.

Parameters

filename

Path to the XBM image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Prev | Home | Next
imagecreatefromwbmp | Up | imagecreatefromxpm


imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxpm -- Create a new image from file or URL

Description

resource imagecreatefromxpm ( string filename )

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

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 M for a list of supported URL protocols.

Parameters

filename

Path to the XPM image

Return Values

Returns an image resource identifier on success, FALSE on errors.

Return Values

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

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.

Prev | Home | Next
imagecreatefromxbm | Up | imagecreatetruecolor


imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int width, int height )

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Depending on your PHP and GD versions this function is defined or not. With PHP 4.0.6 through 4.1.x this function always exists if the GD module is loaded, but calling it without GD2 being installed PHP will issue a fatal error and exit. With PHP 4.2.x this behaviour is different in issuing a warning instead of an error. Other versions only define this function, if the correct GD version is installed.

Parameters

width

Image width

height

Image height

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example 1. Creating a new GD image stream and outputting an image.

&#60;?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(120, 20)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?&#62;

The above example will output something similar to:

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function will not work with GIF file formats.

See Also

imagedestroy()
imagecreate()

Prev | Home | Next
imagecreatefromxpm | Up | imagedashedline


imagedashedline

(PHP 3, PHP 4, PHP 5)

imagedashedline -- Draw a dashed line

Description

bool imagedashedline ( resource image, int x1, int y1, int x2, int y2, int color )

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

Prev | Home | Next
imagecreatetruecolor | Up | imagedestroy


imagedestroy

(PHP 3, PHP 4, PHP 5)

imagedestroy -- Destroy an image

Description

bool imagedestroy ( resource image )

imagedestroy() frees any memory associated with image image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagedashedline | Up | imageellipse


imageellipse

(PHP 4 >= 4.0.6, PHP 5)

imageellipse -- Draw an ellipse

Description

bool imageellipse ( resource image, int cx, int cy, int width, int height, int color )

Draws an ellipse centered at the specified coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center

cy

y-coordinate of the center

width

The ellipse width

height

The ellipse height

color

The color of the ellipse. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imageellipse() example

&#60;?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the ellipse
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?&#62;

The above example will output something similar to:

Notes

Note: This function requires GD 2.0.2 or later.

See Also

imagefilledellipse()
imagearc()

Prev | Home | Next
imagedestroy | Up | imagefill


imagefill

(PHP 3, PHP 4, PHP 5)

imagefill -- Flood fill

Description

bool imagefill ( resource image, int x, int y, int color )

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of start point

y

y-coordinate of start point

color

The fill color. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagefill() example

&#60;?php

$im = imagecreatetruecolor(100, 100);

// sets background to red
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?&#62;

The above example will output something similar to:

See Also

imagecolorallocate()

Prev | Home | Next
imageellipse | Up | imagefilledarc


imagefilledarc

(PHP 4 >= 4.0.6, PHP 5)

imagefilledarc -- Draw a partial ellipse and fill it

Description

bool imagefilledarc ( resource image, int cx, int cy, int width, int height, int start, int end, int color, int style )

Draws a partial ellipse centered at the specified coordinate in the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center

cy

y-coordinate of the center

width

The arc width

height

The arc height

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate()

style

A bitwise OR of the following possibilities:

  1. IMG_ARC_PIE

  2. IMG_ARC_CHORD

  3. IMG_ARC_NOFILL

  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Creating a 3D looking pie

&#60;?php

// create image
$image = imagecreatetruecolor(100, 100);

// allocate some solors
$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00);

// make the 3D effect
for ($i = 60; $i &#62; 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?&#62;

The above example will output something similar to:

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Prev | Home | Next
imagefill | Up | imagefilledellipse


imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5)

imagefilledellipse -- Draw a filled ellipse

Description

bool imagefilledellipse ( resource image, int cx, int cy, int width, int height, int color )

Draws an ellipse centered at the specified coordinate on the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center

cy

y-coordinate of the center

width

The arc width

height

The arc height

color

The fill color. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagefilledellipse() example

&#60;?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?&#62;

The above example will output something similar to:

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imageellipse()
imagefilledarc()

Prev | Home | Next
imagefilledarc | Up | imagefilledpolygon


imagefilledpolygon

(PHP 3, PHP 4, PHP 5)

imagefilledpolygon -- Draw a filled polygon

Description

bool imagefilledpolygon ( resource image, array points, int num_points, int color )

imagefilledpolygon() creates a filled polygon in the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

points

An array containing the x and y coordinates of the polygons vertices consecutively

num_points

Total number of vertices, which must be bigger than 3

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagefilledpolygon() example

&#60;?php
// set up array of points for polygon
$values = array(
            40,  50,  // Point 1 (x, y)
            20,  240, // Point 2 (x, y)
            60,  60,  // Point 3 (x, y)
            240, 20,  // Point 4 (x, y)
            50,  40,  // Point 5 (x, y)
            10,  10   // Point 6 (x, y)
            );

// create image
$image = imagecreatetruecolor(250, 250);

// some colors
$bg   = imagecolorallocate($image, 200, 200, 200);
$blue = imagecolorallocate($image, 0, 0, 255);

// draw a polygon
imagefilledpolygon($image, $values, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?&#62;

The above example will output something similar to:

Prev | Home | Next
imagefilledellipse | Up | imagefilledrectangle


imagefilledrectangle

(PHP 3, PHP 4, PHP 5)

imagefilledrectangle -- Draw a filled rectangle

Description

bool imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int color )

Creates a rectangle filled with color in the given image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

x-coordinate for point 1

y1

y-coordinate for point 1

x2

x-coordinate for point 2

y2

y-coordinate for point 2

color

The fill color. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagefilledpolygon | Up | imagefilltoborder


imagefilltoborder

(PHP 3, PHP 4, PHP 5)

imagefilltoborder -- Flood fill to specific color

Description

bool imagefilltoborder ( resource image, int x, int y, int border, int color )

imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color color.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of start

y

y-coordinate of start

border

The border color. A color identifier created with imagecolorallocate()

color

The fill color. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagefilledrectangle | Up | imagefilter


imagefilter

(PHP 5)

imagefilter -- Applies a filter to an image

Description

bool imagefilter ( resource image, int filtertype [, int arg1 [, int arg2 [, int arg3]]] )

imagefilter() applies the given filter filtertype on the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filtertype

filtertype can be one of the following:

  • IMG_FILTER_NEGATE: Reverses all colors of the image.

  • IMG_FILTER_GRAYSCALE: Converts the image into grayscale.

  • IMG_FILTER_BRIGHTNESS: Changes the brightness of the image. Use arg1 to set the level of brightness.

  • IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.

  • IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1, arg2 and arg3 in the form of red, blue, green. The range for each color is 0 to 255.

  • IMG_FILTER_EDGEDETECT: Uses edge detection to highlight the edges in the image.

  • IMG_FILTER_EMBOSS: Embosses the image.

  • IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using the Gaussian method.

  • IMG_FILTER_SELECTIVE_BLUR: Blurs the image.

  • IMG_FILTER_MEAN_REMOVAL: Uses mean removal to achieve a "sketchy" effect.

  • IMG_FILTER_SMOOTH: Makes the image smoother. Use arg1 to set the level of smoothness.

arg1

arg2

arg3

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagefilter() grayscale example

&#60;?php
$im = imagecreatefrompng('dave.png');
if ($im &#38;&#38; imagefilter($im, IMG_FILTER_GRAYSCALE)) {
    echo 'Image converted to grayscale.';
    imagepng($im, 'dave.png');
} else {
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?&#62;

Example 2. imagefilter() brightness example

&#60;?php
$im = imagecreatefrompng('sean.png');
if ($im &#38;&#38; imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
    echo 'Image brightness changed.';
    imagepng($im, 'sean.png');
} else {
    echo 'Image brightness change failed.';
}

imagedestroy($im);
?&#62;

Example 3. imagefilter() colorize example

&#60;?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if ($im &#38;&#38; imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
    echo 'Image successfully shaded green.';
    imagepng($im, 'philip.png');
} else {
    echo 'Green shading failed.';
}

imagedestroy($im);
?&#62;

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

imageconvolution()

Prev | Home | Next
imagefilltoborder | Up | imagefontheight


imagefontheight

(PHP 3, PHP 4, PHP 5)

imagefontheight -- Get font height

Description

int imagefontheight ( int font )

Returns the pixel height of a character in the specified font.

Parameters

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the height of the pixel.

See Also

imagefontwidth()
imageloadfont()

Prev | Home | Next
imagefilter | Up | imagefontwidth


imagefontwidth

(PHP 3, PHP 4, PHP 5)

imagefontwidth -- Get font width

Description

int imagefontwidth ( int font )

Returns the pixel width of a character in font.

Parameters

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the width of the pixel

See Also

imagefontheight()
imageloadfont()

Prev | Home | Next
imagefontheight | Up | imageftbbox


imageftbbox

(PHP 4 >= 4.1.0, PHP 5)

imageftbbox -- Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( float size, float angle, string font_file, string text [, array extrainfo] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

size

angle

font_file

text

extrainfo

Return Values

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

ChangeLog

Version | Description
4.3.5 | extrainfo was made optional.

Prev | Home | Next
imagefontwidth | Up | imagefttext


imagefttext

(PHP 4 >= 4.1.0, PHP 5)

imagefttext -- Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource image, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

angle

x

y

col

font_file

text

extrainfo

Return Values

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

ChangeLog

Version | Description
4.3.5 | extrainfo was made optional.

Prev | Home | Next
imageftbbox | Up | imagegammacorrect


imagegammacorrect

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagegammacorrect -- Apply a gamma correction to a GD image

Description

bool imagegammacorrect ( resource image, float inputgamma, float outputgamma )

Applies gamma correction to the given gd image given an input and an output gamma.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

inputgamma

The input gamma

outputgamma

The output gamma

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagefttext | Up | imagegd2


imagegd2

(PHP 4 >= 4.1.0, PHP 5)

imagegd2 -- Output GD2 image to browser or file

Description

bool imagegd2 ( resource image [, string filename [, int chunk_size [, int type]]] )

Outputs a GD2 image to the given filename.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

chunk_size

type

Either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.

ChangeLog

Version | Description
4.3.2 | chunk_size and type were added.

See Also

imagegd()

Prev | Home | Next
imagegammacorrect | Up | imagegd


imagegd

(PHP 4 >= 4.1.0, PHP 5)

imagegd -- Output GD image to browser or file

Description

bool imagegd ( resource image [, string filename] )

Outputs a GD image to the given filename.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.

See Also

imagegd2()

Prev | Home | Next
imagegd2 | Up | imagegif


imagegif

(PHP 3, PHP 4, PHP 5)

imagegif -- Output image to browser or file

Description

bool imagegif ( resource image [, string filename] )

imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreate() or imagecreatefrom* function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library. Support is expected to return in a version subsequent to the rerelease of GIF support in the GD library in mid 2004. For more information, see the GD Project site.

The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:

&#60;?php
if (function_exists("imagegif")) {
    header("Content-type: image/gif");
    imagegif($im);
} elseif (function_exists("imagejpeg")) {
    header("Content-type: image/jpeg");
    imagejpeg($im, "", 0.5);
} elseif (function_exists("imagepng")) {
    header("Content-type: image/png");
    imagepng($im);
} elseif (function_exists("imagewbmp")) {
    header("Content-type: image/vnd.wap.wbmp");
    imagewbmp($im);
} else {
    die("No image support in this PHP server");
}
?&#62;

Note: As of version 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

&#60;?php
if (imagetypes() &#38; IMG_GIF) {
    header ("Content-type: image/gif");
    imagegif ($im);
} elseif (imagetypes() &#38; IMG_JPG) {
    /* ... etc. */
}
?&#62;

See Also

imagepng()
imagewbmp()
imagejpeg()
imagetypes()

Prev | Home | Next
imagegd | Up | imageinterlace


imageinterlace

(PHP 3, PHP 4, PHP 5)

imageinterlace -- Enable or disable interlace

Description

int imageinterlace ( resource image [, int interlace] )

imageinterlace() turns the interlace bit on or off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

interlace

If non-zero, the image will be interlaced, else the interlace bit is turned off.

Return Values

Returns 1 if the interlace bit is set for the image, 0 otherwise.

Prev | Home | Next
imagegif | Up | imageistruecolor


imageistruecolor

(PHP 4 >= 4.3.2, PHP 5)

imageistruecolor -- Finds whether an image is a truecolor image

Description

bool imageistruecolor ( resource image )

imageistruecolor() finds whether the image image is a truecolor image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE if the image is truecolor, FALSE otherwise.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagecreatetruecolor()

Prev | Home | Next
imageinterlace | Up | imagejpeg


imagejpeg

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagejpeg -- Output image to browser or file

Description

bool imagejpeg ( resource image [, string filename [, int quality]] )

imagejpeg() creates a JPEG file from the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

To skip this argument in order to provide the quality parameter, use NULL.

quality

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

Note: If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See Also

imagepng()
imagegif()
imagewbmp()
imageinterlace()
imagetypes()

Prev | Home | Next
imageistruecolor | Up | imagelayereffect


imagelayereffect

(PHP 4 >= 4.3.0, PHP 5)

imagelayereffect -- Set the alpha blending flag to use the bundled libgd layering effects

Description

bool imagelayereffect ( resource image, int effect )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

effect

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Prev | Home | Next
imagejpeg | Up | imageline


imageline

(PHP 3, PHP 4, PHP 5)

imageline -- Draw a line

Description

bool imageline ( resource image, int x1, int y1, int x2, int y2, int color )

imageline() draws a line between the two given points.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

x-coordinate for first point

y1

y-coordinate for first point

x2

x-coordinate for second point

y2

y-coordinate for second point

color

The line color. A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Drawing a thick line

&#60;?php

function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
    /* this way it works well only for orthogonal lines
    imagesetthickness($image, $thick);
    return imageline($image, $x1, $y1, $x2, $y2, $color);
    */
    if ($thick == 1) {
        return imageline($image, $x1, $y1, $x2, $y2, $color);
    }
    $t = $thick / 2 - 0.5;
    if ($x1 == $x2 || $y1 == $y2) {
        return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
    }
    $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
    $a = $t / sqrt(1 + pow($k, 2));
    $points = array(
        round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
        round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
        round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
        round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
    );
    imagefilledpolygon($image, $points, 4, $color);
    return imagepolygon($image, $points, 4, $color);
}

?&#62;

See Also

imagecreatetruecolor()
imagecolorallocate()

Prev | Home | Next
imagelayereffect | Up | imageloadfont


imageloadfont

(PHP 3, PHP 4, PHP 5)

imageloadfont -- Load a new font

Description

int imageloadfont ( string file )

imageloadfont() loads a user-defined bitmap and returns its identifier.

Parameters

file

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Table 1. Font file format

byte position | C data type | description
byte 0-3 | int | number of characters in the font
byte 4-7 | int | value of first character in the font (often 32 for space)
byte 8-11 | int | pixel width of each character
byte 12-15 | int | pixel height of each character
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

Return Values

The font identifier which is always biigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

Examples

Example 1. Using imageloadfont

&#60;?php
header("Content-type: image/png");
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 49, 19, $white);
$font = imageloadfont("04b.gdf");
imagestring($im, $font, 0, 0, "Hello", $black);
imagepng($im);
?&#62;

See Also

imagefontwidth()
imagefontheight()

Prev | Home | Next
imageline | Up | imagepalettecopy


imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5)

imagepalettecopy -- Copy the palette from one image to another

Description

void imagepalettecopy ( resource destination, resource source )

imagepalettecopy() copies the palette from the source image to the destination image.

Parameters

destination

The destination image resource

source

The source image resource

Return Values

No value is returned.

Prev | Home | Next
imageloadfont | Up | imagepng


imagepng

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagepng -- Output a PNG image to either the browser or a file

Description

bool imagepng ( resource image [, string filename [, int quality [, int filters]]] )

Outputs or saves a PNG image from the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

Note: NULL is invalid if the quality and filters arguments are not used.

quality

Compression level: from 0 (no compression) to 9.

filters

Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the PNG_FILTER_XXX constants. PNG_NO_FILTER or PNG_ALL_FILTERS may also be used to respectively disable or activate all filters.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
5.1.3 | Added the filters parameter.
5.1.2 | Added the quality parameter.

Examples

&#60;?php
$im = imagecreatefrompng("test.png");
imagepng($im);
?&#62;

See Also

imagegif()
imagewbmp()
imagejpeg()
imagetypes()

Prev | Home | Next
imagepalettecopy | Up | imagepolygon


imagepolygon

(PHP 3, PHP 4, PHP 5)

imagepolygon -- Draws a polygon

Description

bool imagepolygon ( resource image, array points, int num_points, int color )

imagepolygon() creates a polygon in the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

points

An array containing the polygon's vertices, i.e. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc.

num_points

Total number of points (vertices)

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagepolygon() example

&#60;?php
// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// draw the polygon
imagepolygon($image, array (
        0,   0,
        100, 200,
        300, 200
    ),
    3,
    $col_poly);

// output the picture
header("Content-type: image/png");
imagepng($image);

?&#62;

The above example will output something similar to:

See Also

imagecreate()
imagecreatetruecolor()

Prev | Home | Next
imagepng | Up | imagepsbbox


imagepsbbox

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string text, int font, int size [, int space, int tightness, float angle] )

Gives the bounding box of a text rectangle using PostScript Type1 fonts.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

Parameters

text

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

size

size is expressed in pixels.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

Return Values

Returns an array containing the following elements:

0 | left x-coordinate
1 | upper y-coordinate
2 | right x-coordinate
3 | lower y-coordinate

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

imagepstext()

Prev | Home | Next
imagepolygon | Up | imagepsencodefont


imagepsencodefont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsencodefont -- Change the character encoding vector of a font

Description

bool imagepsencodefont ( resource font_index, string encodingfile )

Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than English.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

Parameters

font_index

encodingfile

The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

Prev | Home | Next
imagepsbbox | Up | imagepsextendfont


imagepsextendfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsextendfont -- Extend or condense a font

Description

bool imagepsextendfont ( int font_index, float extend )

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

Parameters

font_index

extend

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

Prev | Home | Next
imagepsencodefont | Up | imagepsfreefont


imagepsfreefont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsfreefont -- Free memory used by a PostScript Type 1 font

Description

bool imagepsfreefont ( resource fontindex )

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parameters

fontindex

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

imagepsloadfont()

Prev | Home | Next
imagepsextendfont | Up | imagepsloadfont


imagepsloadfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsloadfont -- Load a PostScript Type 1 font from file

Description

resource imagepsloadfont ( string filename )

Load a PostScript Type 1 font from the given filename.

Parameters

filename

Return Values

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE.

Examples

Example 1. imagepsloadfont() example

&#60;?php
header("Content-type: image/png");
$im = imagecreatetruecolor(350, 45);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 349, 44, $white);
$font = imagepsloadfont("bchbi.pfb"); // or locate your .pfb files on your machine
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);
imagepng($im);
imagedestroy($im);
?&#62;

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

imagepsfreefont()

Prev | Home | Next
imagepsfreefont | Up | imagepsslantfont


imagepsslantfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsslantfont -- Slant a font

Description

bool imagepsslantfont ( resource font_index, float slant )

Slant a given font given.

Parameters

font_index

slant

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

Prev | Home | Next
imagepsloadfont | Up | imagepstext


imagepstext

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepstext -- Draws a text over an image using PostScript Type1 fonts

Description

array imagepstext ( resource image, string text, resource font, int size, int foreground, int background, int x, int y [, int space [, int tightness [, float angle [, int antialias_steps]]]] )

Draws a text on an image using PostScript Type1 fonts.

Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

text

The text to be written.

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

size

size is expressed in pixels.

foreground

The color in which the text will be painted.

background

The color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

x

x-coordinate for the lower-left corner of the first character

y

y-coordinate for the lower-left corner of the first character

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

antialias_steps

Allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Return Values

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

imagepsbbox()

Prev | Home | Next
imagepsslantfont | Up | imagerectangle


imagerectangle

(PHP 3, PHP 4, PHP 5)

imagerectangle -- Draw a rectangle

Description

bool imagerectangle ( resource image, int x1, int y1, int x2, int y2, int color )

imagerectangle() creates a rectangle starting at the specified coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

Upper left x coordinate

y1

Upper left y coordinate 0, 0 is the top left corner of the image.

x2

Bottom right x coordinate

y2

Bottom right y coordinate

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagepstext | Up | imagerotate


imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate -- Rotate an image with a given angle

Description

resource imagerotate ( resource source_image, float angle, int bgd_color [, int ignore_transparent] )

Rotates the source_image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image is scaled down so that the whole rotated image fits in the destination image - the edges are not clipped.

Parameters

source_image

The source image link

angle

Rotation angle, in degrees.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Return Values

ChangeLog

Version | Description
5.1.0 | ignore_transparent was added.

Examples

Example 1. Rotate an image 180 degrees

This example rotates an image 180 degrees - upside down.

&#60;?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);
?&#62;

The above example will output something similar to:

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Prev | Home | Next
imagerectangle | Up | imagesavealpha


imagesavealpha

(PHP 4 >= 4.3.2, PHP 5)

imagesavealpha -- Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

Description

bool imagesavealpha ( resource image, bool saveflag )

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

You have to unset alphablending (imagealphablending($im, FALSE)), to use it.

Alpha channel is not supported by all browsers, if you have problem with your browser, try to load your script with an alpha channel compliant browser, e.g. latest Mozilla.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

saveflag

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

imagealphablending()

Prev | Home | Next
imagerotate | Up | imagesetbrush


imagesetbrush

(PHP 4 >= 4.0.6, PHP 5)

imagesetbrush -- Set the brush image for line drawing

Description

bool imagesetbrush ( resource image, resource brush )

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Note: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

brush

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagesavealpha | Up | imagesetpixel


imagesetpixel

(PHP 3, PHP 4, PHP 5)

imagesetpixel -- Set a single pixel

Description

bool imagesetpixel ( resource image, int x, int y, int color )

imagesetpixel() draws a pixel at the specified coordinate.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate

y

y-coordinate

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagesetpixel() example

A random drawing that ends with a regular picture.

&#60;?php

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' =&#62; 100, 'y' =&#62;  10);
$corners[1] = array('x' =&#62;   0, 'y' =&#62; 190);
$corners[2] = array('x' =&#62; 200, 'y' =&#62; 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for ($i = 0; $i &#60; 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}

header('Content-Type: image/png');
imagepng($gd);

?&#62;

The above example will output something similar to:

See Also

imagecreatetruecolor()
imagecolorallocate()

Prev | Home | Next
imagesetbrush | Up | imagesetstyle


imagesetstyle

(PHP 4 >= 4.0.6, PHP 5)

imagesetstyle -- Set the style for line drawing

Description

bool imagesetstyle ( resource image, array style )

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

style

An array of pixel colors. You can use the IMG_COLOR_TRANSPARENT constant to add a transparent pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Following example script draws a dashed line from upper left to lower right corner of the canvas:

Example 1. imagesetstyle() example

&#60;?php
header("Content-type: image/jpeg");
$im  = imagecreatetruecolor(100, 100);
$w   = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);

$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?&#62;

The above example will output something similar to:

See Also

imagesetbrush()
imageline()

Prev | Home | Next
imagesetpixel | Up | imagesetthickness


imagesetthickness

(PHP 4 >= 4.0.6, PHP 5)

imagesetthickness -- Set the thickness for line drawing

Description

bool imagesetthickness ( resource image, int thickness )

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

thickness

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Prev | Home | Next
imagesetstyle | Up | imagesettile


imagesettile

(PHP 4 >= 4.0.6, PHP 5)

imagesettile -- Set the tile image for filling

Description

bool imagesettile ( resource image, resource tile )

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Note: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

tile

The image resource to be used as a tile

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagesetthickness | Up | imagestring


imagestring

(PHP 3, PHP 4, PHP 5)

imagestring -- Draw a string horizontally

Description

bool imagestring ( resource image, int font, int x, int y, string sring, int color )

Draws a string at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the upper left corner

y

y-coordinate of the upper left corner

sring

The string to be written

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imagestring() example

&#60;?php
// create a 100*30 image
$im = imagecreate(100, 30);

// white background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// write the string at the top left
imagestring($im, 5, 0, 0, "Hello world!", $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?&#62;

The above example will output something similar to:

See Also

imageloadfont()
imagettftext()

Prev | Home | Next
imagesettile | Up | imagestringup


imagestringup

(PHP 3, PHP 4, PHP 5)

imagestringup -- Draw a string vertically

Description

bool imagestringup ( resource image, int font, int x, int y, string string, int color )

Draws a string vertically at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the upper left corner

y

y-coordinate of the upper left corner

sring

The string to be written

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imageloadfont()

Prev | Home | Next
imagestring | Up | imagesx


imagesx

(PHP 3, PHP 4, PHP 5)

imagesx -- Get image width

Description

int imagesx ( resource image )

Returns the width of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the width of the image or FALSE on errors.

Examples

Example 1. Using imagesx()

&#60;?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?&#62;

See Also

imagecreatetruecolor()
getimagesize()
imagesy()

Prev | Home | Next
imagestringup | Up | imagesy


imagesy

(PHP 3, PHP 4, PHP 5)

imagesy -- Get image height

Description

int imagesy ( resource image )

Returns the height of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the height of the image or FALSE on errors.

Examples

Example 1. Using imagesy()

&#60;?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?&#62;

See Also

imagecreatetruecolor()
getimagesize()
imagesx()

Prev | Home | Next
imagesx | Up | imagetruecolortopalette


imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

bool imagetruecolortopalette ( resource image, bool dither, int ncolors )

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

dither

Indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors

Sets the maximum number of colors that should be retained in the palette.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Prev | Home | Next
imagesy | Up | imagettfbbox


imagettfbbox

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

imagettfbbox -- Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( float size, float angle, string fontfile, string text )

This function calculates and returns the bounding box in pixels for a TrueType text.

Parameters

size

The font size in pixels

angle

Angle in degrees in which text will be measured

fontfile

The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path

text

The string to be measured

Return Values

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.

See Also

Note: This function requires both the GD library and the FreeType library.

See Also

imagettftext()

Prev | Home | Next
imagetruecolortopalette | Up | imagettftext


imagettftext

(PHP 3, PHP 4, PHP 5)

imagettftext -- Write text to the image using TrueType fonts

Description

array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )

Writes the given text into the image using TrueType fonts.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2)

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate()

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

&#60;?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
       The y-ordinate. This sets the position of the fonts baseline, not
       the very bottom of the character.
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?&#62;

text

The text string.

May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. The hexadecimal format (like &#xA9;) is supported as of PHP 5.2.0. Strings in UTF-8 encoding can be passed directly.

Named entities, such as &copy;, are not supported. Consider using html_entity_decode() to decode these named entities into UTF-8 strings (html_entity_decode() supports this as of PHP 5.0.0).

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Return Values

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally.

Examples

Example 1. imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

&#60;?php
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?&#62;

Notes

Note: This function requires both the GD library and the FreeType library.

See Also

imagettfbbox()

Prev | Home | Next
imagettfbbox | Up | imagetypes


imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2, PHP 5)

imagetypes -- Return the image types supported by this PHP build

Description

int imagetypes ( void )

Returns the image types supported by the current PHP installation.

Return Values

Returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.

Examples

Example 1. Checking for PNG support

&#60;?php
if (imagetypes() &#38; IMG_PNG) {
    echo "PNG Support is enabled";
}
?&#62;

Prev | Home | Next
imagettftext | Up | imagewbmp


imagewbmp

(PHP 3 >= 3.0.15, PHP 4 >= 4.0.1, PHP 5)

imagewbmp -- Output image to browser or file

Description

bool imagewbmp ( resource image [, string filename [, int foreground]] )

imagewbmp() outputs or save a WBMP version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

image2wbmp()
imagepng()
imagegif()
imagejpeg()
imagetypes()

Prev | Home | Next
imagetypes | Up | imagexbm


imagexbm

(PHP 5)

imagexbm -- Output XBM image to browser or file

Description

bool imagexbm ( resource image, string filename [, int foreground] )

Outputs or save an XBM version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to the saved file. If not set or NULL, the raw image stream will be outputed directly.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Prev | Home | Next
imagewbmp | Up | iptcembed


iptcembed

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

iptcembed -- Embed binary IPTC data into a JPEG image

Description

mixed iptcembed ( string iptcdata, string jpeg_file_name [, int spool] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

iptcdata

jpeg_file_name

spool

Prev | Home | Next
imagexbm | Up | iptcparse


iptcparse

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

iptcparse -- Parse a binary IPTC block into single tags.

Description

array iptcparse ( string iptcblock )

Parses an IPTC block into its single tags.

Parameters

iptcblock

A binary IPTC block

Return Values

Returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found.

See Also

getimagesize() for an example

Prev | Home | Next
iptcembed | Up | jpeg2wbmp


jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5)

jpeg2wbmp -- Convert JPEG image file to WBMP image file

Description

bool jpeg2wbmp ( string jpegname, string wbmpname, int dest_height, int dest_width, int threshold )

Converts a JPEG file into a WBMP file.

Parameters

jpegname

Path to JPEG file

wbmpname

Path to destination WBMP file

dest_height

Destination image height

dest_width

Destination image width

threshold

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

See Also

png2wbmp()

Prev | Home | Next
iptcparse | Up | png2wbmp


png2wbmp

(PHP 4 >= 4.0.5, PHP 5)

png2wbmp -- Convert PNG image file to WBMP image file

Description

bool png2wbmp ( string pngname, string wbmpname, int dest_height, int dest_width, int threshold )

Converts a PNG file into a WBMP file.

Parameters

pngname

Path to PNG file

wbmpname

Path to destination WBMP file

dest_height

Destination image height

dest_width

Destination image width

threshold

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

jpeg2wbmp()

Prev | Home | Next
jpeg2wbmp | Up | Image magick Functions


IMAP, POP3 and NNTP Functions

PHP Manual
Prev Next

LXV. IMAP, POP3 and NNTP Functions

Introduction

These functions enable you to operate with the IMAP protocol, as well as the NNTP, POP3 and local mailbox access methods.

Be warned however, that some of IMAP functions will not work correctly with the POP protocol.

Requirements

This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Note: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.

Note: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.

Installation

To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini. IMAP is not supported on systems earlier that Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.

Note: Depending how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos into the PHP configure line.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they both share the same internal symbol.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

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.

NIL (integer)

OP_DEBUG (integer)

OP_READONLY (integer)

Open mailbox read-only

OP_ANONYMOUS (integer)

Don't use or update a .newsrc for news (NNTP only)

OP_SHORTCACHE (integer)

OP_SILENT (integer)

OP_PROTOTYPE (integer)

OP_HALFOPEN (integer)

For IMAP and NNTP names, open a connection but don't open a mailbox.

OP_EXPUNGE (integer)

OP_SECURE (integer)

CL_EXPUNGE (integer)

silently expunge the mailbox before closing when calling imap_close()

FT_UID (integer)

The parameter is a UID

FT_PEEK (integer)

Do not set the \Seen flag if not already set

FT_NOT (integer)

FT_INTERNAL (integer)

The return string is in internal format, will not canonicalize to CRLF.

FT_PREFETCHTEXT (integer)

ST_UID (integer)

The sequence argument contains UIDs instead of sequence numbers

ST_SILENT (integer)

ST_SET (integer)

CP_UID (integer)

the sequence numbers contain UIDS

CP_MOVE (integer)

Delete the messages from the current mailbox after copying with imap_mail_copy()

SE_UID (integer)

Return UIDs instead of sequence numbers

SE_FREE (integer)

SE_NOPREFETCH (integer)

Don't prefetch searched messages

SO_FREE (integer)

SO_NOSERVER (integer)

SA_MESSAGES (integer)

SA_RECENT (integer)

SA_UNSEEN (integer)

SA_UIDNEXT (integer)

SA_UIDVALIDITY (integer)

SA_ALL (integer)

LATT_NOINFERIORS (integer)

This mailbox has no "children" (there are no mailboxes below this one).

LATT_NOSELECT (integer)

This is only a container, not a mailbox - you cannot open it.

LATT_MARKED (integer)

This mailbox is marked. Only used by UW-IMAPD.

LATT_UNMARKED (integer)

This mailbox is not marked. Only used by UW-IMAPD.

SORTDATE (integer)

Sort criteria for imap_sort(): message Date

SORTARRIVAL (integer)

Sort criteria for imap_sort(): arrival date

SORTFROM (integer)

Sort criteria for imap_sort(): mailbox in first From address

SORTSUBJECT (integer)

Sort criteria for imap_sort(): message subject

SORTTO (integer)

Sort criteria for imap_sort(): mailbox in first To address

SORTCC (integer)

Sort criteria for imap_sort(): mailbox in first cc address

SORTSIZE (integer)

Sort criteria for imap_sort(): size of message in octets

TYPETEXT (integer)

TYPEMULTIPART (integer)

TYPEMESSAGE (integer)

TYPEAPPLICATION (integer)

TYPEAUDIO (integer)

TYPEIMAGE (integer)

TYPEVIDEO (integer)

TYPEOTHER (integer)

ENC7BIT (integer)

ENC8BIT (integer)

ENCBINARY (integer)

ENCBASE64 (integer)

ENCQUOTEDPRINTABLE (integer)

ENCOTHER (integer)

See Also

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

Table of Contents
imap_8bit -- Convert an 8bit string to a quoted-printable string
imap_alerts -- Returns all IMAP alert messages that have occurred
imap_append -- Append a string message to a specified mailbox
imap_base64 -- Decode BASE64 encoded text
imap_binary -- Convert an 8bit string to a base64 string
imap_body -- Read the message body
imap_bodystruct -- Read the structure of a specified body section of a specific message
imap_check -- Check current mailbox
imap_clearflag_full -- Clears flags on messages
imap_close -- Close an IMAP stream
imap_createmailbox -- Create a new mailbox
imap_delete -- Mark a message for deletion from current mailbox
imap_deletemailbox -- Delete a mailbox
imap_errors -- Returns all of the IMAP errors that have occured
imap_expunge -- Delete all messages marked for deletion
imap_fetch_overview -- Read an overview of the information in the headers of the given message
imap_fetchbody -- Fetch a particular section of the body of the message
imap_fetchheader -- Returns header for a message
imap_fetchstructure -- Read the structure of a particular message
imap_get_quota -- Retrieve the quota level settings, and usage statics per mailbox
imap_get_quotaroot -- Retrieve the quota settings per user
imap_getacl -- Gets the ACL for a given mailbox
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed -- List all the subscribed mailboxes
imap_header -- Alias of imap_headerinfo()
imap_headerinfo -- Read the header of the message
imap_headers -- Returns headers for all messages in a mailbox
imap_last_error -- Gets the last IMAP error that occurred during this page request
imap_list -- Read the list of mailboxes
imap_listmailbox -- Alias of imap_list()
imap_listscan -- Returns the list of mailboxes that matches the given text
imap_listsubscribed -- Alias of imap_lsub()
imap_lsub -- List all the subscribed mailboxes
imap_mail_compose -- Create a MIME message based on given envelope and body sections
imap_mail_copy -- Copy specified messages to a mailbox
imap_mail_move -- Move specified messages to a mailbox
imap_mail -- Send an email message
imap_mailboxmsginfo -- Get information about the current mailbox
imap_mime_header_decode -- Decode MIME header elements
imap_msgno -- Gets the message sequence number for the given UID
imap_num_msg -- Gets the number of messages in the current mailbox
imap_num_recent -- Gets the number of recent messages in current mailbox
imap_open -- Open an IMAP stream to a mailbox
imap_ping -- Check if the IMAP stream is still active
imap_qprint -- Convert a quoted-printable string to an 8 bit string
imap_renamemailbox -- Rename an old mailbox to new mailbox
imap_reopen -- Reopen IMAP stream to new mailbox
imap_rfc822_parse_adrlist -- Parses an address string
imap_rfc822_parse_headers -- Parse mail headers from a string
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info
imap_savebody -- Save a specific body section to a file
imap_scanmailbox -- Alias of imap_listscan()
imap_search -- This function returns an array of messages matching the given search criteria
imap_set_quota -- Sets a quota for a given mailbox
imap_setacl -- Sets the ACL for a giving mailbox
imap_setflag_full -- Sets flags on messages
imap_sort -- Gets and sort messages
imap_status -- Returns status information on a mailbox
imap_subscribe -- Subscribe to a mailbox
imap_thread -- Returns a tree of threaded message
imap_timeout -- Set or fetch imap timeout
imap_uid -- This function returns the UID for the given message sequence number
imap_undelete -- Unmark the message which is marked deleted
imap_unsubscribe -- Unsubscribe from a mailbox
imap_utf7_decode -- Decodes a modified UTF-7 encoded string
imap_utf7_encode -- Converts ISO-8859-1 string to modified UTF-7 text
imap_utf8 -- Converts MIME-encoded text to UTF-8

Prev | Home | Next
imagick_zoom | Up | imap_8bit


imap_8bit

(PHP 3, PHP 4, PHP 5)

imap_8bit -- Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string )

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Parameters

string

The 8bit string to convert

Return Values

Returns a quoted-printable string.

See Also

imap_qprint()

Prev | Home | Next
IMAP, POP3 and NNTP Functions | Up | imap_alerts


imap_alerts

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_alerts -- Returns all IMAP alert messages that have occurred

Description

array imap_alerts ( void )

Returns all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page.

When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

Return Values

Returns an array of all of the IMAP alert messages generated or FALSE if no alert messages are available.

See Also

imap_errors()

Prev | Home | Next
imap_8bit | Up | imap_append


imap_append

(PHP 3, PHP 4, PHP 5)

imap_append -- Append a string message to a specified mailbox

Description

bool imap_append ( resource imap_stream, string mailbox, string message [, string options] )

Appends a string message to the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

message

The message to be append, as a string

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail

options

If provided, the options will also be written to the mailbox

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imap_append() example

&#60;?php
$stream = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check-&#62;Nmsgs . "\n";

imap_append($stream, "{imap.example.org}INBOX.Drafts"
                   , "From: me@example.com\r\n"
                   . "To: you@example.com\r\n"
                   . "Subject: test\r\n"
                   . "\r\n"
                   . "this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
echo "Msg Count after append : ". $check-&#62;Nmsgs . "\n";

imap_close($stream);
?&#62;

Prev | Home | Next
imap_alerts | Up | imap_base64


imap_base64

(PHP 3, PHP 4, PHP 5)

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text )

Decodes the given BASE-64 encoded text.

Parameters

text

The encoded text

Return Values

Returns the decoded message as a string.

See Also

imap_binary()
base64_encode()
base64_decode()
RFC2045, Section 6.8

Prev | Home | Next
imap_append | Up | imap_binary


imap_binary

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_binary -- Convert an 8bit string to a base64 string

Description

string imap_binary ( string string )

Convert an 8bit string to a base64 string according to RFC2045, Section 6.8.

Parameters

string

The 8bit string

Return Values

Returns a base64 encoded string.

See Also

imap_base64()

Prev | Home | Next
imap_base64 | Up | imap_body


imap_body

(PHP 3, PHP 4, PHP 5)

imap_body -- Read the message body

Description

string imap_body ( resource imap_stream, int msg_number [, int options] )

imap_body() returns the body of the message, numbered msg_number in the current mailbox.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The optional options are a bit mask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns the body of the specified message, as a string.

Prev | Home | Next
imap_binary | Up | imap_bodystruct


imap_bodystruct

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_bodystruct -- Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( resource imap_stream, int msg_number, string section )

Read the structure of a specified body section of a specific message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

section

The body section to read

Return Values

Returns the information in an object with following properties:

  • type -

  • encoding -

  • ifsubtype -

  • subtype -

  • ifdescription -

  • description -

  • ifid -

  • id -

  • lines - number of lines

  • bytes - size of message, in bytes

  • ifdisposition -

  • disposition -

  • ifdparameters -

  • dparameters -

  • ifparameters -

  • parameters -

Prev | Home | Next
imap_body | Up | imap_check


imap_check

(PHP 3, PHP 4, PHP 5)

imap_check -- Check current mailbox

Description

object imap_check ( resource imap_stream )

Checks information about the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the information in an object with following properties:

  • Date - current system time formatted according to RFC2822

  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP

  • Mailbox - the mailbox name

  • Nmsgs - number of messages in the mailbox

  • Recent - number of recent messages in the mailbox

Returns FALSE on failure.

Examples

Example 1. imap_check() example

&#60;?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?&#62;

The above example will output something similar to:

object(stdClass)(5) {
  ["Date"]=>
  string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
  ["Driver"]=>
  string(4) "imap"
  ["Mailbox"]=>
  string(54)
  "{www.example.com:143/imap/user="foo@example.com"}INBOX"
  ["Nmsgs"]=>
  int(1)
  ["Recent"]=>
  int(0)
}

Prev | Home | Next
imap_bodystruct | Up | imap_clearflag_full


imap_clearflag_full

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_clearflag_full -- Clears flags on messages

Description

bool imap_clearflag_full ( resource imap_stream, string sequence, string flag [, string options] )

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence.

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060)

options

options are a bit mask and may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_setflag_full()

Prev | Home | Next
imap_check | Up | imap_close


imap_close

(PHP 3, PHP 4, PHP 5)

imap_close -- Close an IMAP stream

Description

bool imap_close ( resource imap_stream [, int flag] )

Closes the imap stream.

Parameters

imap_stream

An IMAP stream returned by imap_open().

flag

If set to CL_EXPUNGE, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_open()

Prev | Home | Next
imap_clearflag_full | Up | imap_createmailbox


imap_createmailbox

(PHP 3, PHP 4, PHP 5)

imap_createmailbox -- Create a new mailbox

Description

bool imap_createmailbox ( resource imap_stream, string mailbox )

Creates a new mailbox specified by mbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imap_createmailbox() example

&#60;?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&#38;ouml;x");

$newname = $name1;

echo "Newname will be '$name1'&#60;br /&#62;\n";

// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finaly remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:&#60;br /&#62;\n";
        echo "Messages:   " . $status-&#62;messages    . "&#60;br /&#62;\n";
        echo "Recent:     " . $status-&#62;recent      . "&#60;br /&#62;\n";
        echo "Unseen:     " . $status-&#62;unseen      . "&#60;br /&#62;\n";
        echo "UIDnext:    " . $status-&#62;uidnext     . "&#60;br /&#62;\n";
        echo "UIDvalidity:" . $status-&#62;uidvalidity . "&#60;br /&#62;\n";

        if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
            echo "renamed new mailbox from '$name1' to '$name2'&#60;br /&#62;\n";
            $newname = $name2;
        } else {
            echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "&#60;br /&#62;\n";
        }
    } else {
        echo "imap_status on new mailbox failed: " . imap_last_error() . "&#60;br /&#62;\n";
    }

    if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
        echo "new mailbox removed to restore initial state&#60;br /&#62;\n";
    } else {
        echo "imap_deletemailbox on new mailbox failed: " . implode("&#60;br /&#62;\n", imap_errors()) . "&#60;br /&#62;\n";
    }

} else {
    echo "could not create new mailbox: " . implode("&#60;br /&#62;\n", imap_errors()) . "&#60;br /&#62;\n";
}

imap_close($mbox);
?&#62;

See Also

imap_renamemailbox()
imap_deletemailbox()

Prev | Home | Next
imap_close | Up | imap_delete


imap_delete

(PHP 3, PHP 4, PHP 5)

imap_delete -- Mark a message for deletion from current mailbox

Description

bool imap_delete ( int imap_stream, int msg_number [, int options] )

Marks messages listed in msg_number for deletion. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

You can set the FT_UID which tells the function to treat the msg_number argument as an UID.

Return Values

Returns TRUE.

Examples

Example 1. imap_delete() example

&#60;?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
    or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check-&#62;Nmsgs . "&#60;br /&#62;\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after  delete: " . $check-&#62;Nmsgs . "&#60;br /&#62;\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check-&#62;Nmsgs . "&#60;br /&#62;\n";

imap_close($mbox);
?&#62;

Notes

Note: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

See Also

imap_undelete()
imap_expunge()
imap_close()

Prev | Home | Next
imap_createmailbox | Up | imap_deletemailbox


imap_deletemailbox

(PHP 3, PHP 4, PHP 5)

imap_deletemailbox -- Delete a mailbox

Description

bool imap_deletemailbox ( resource imap_stream, string mailbox )

Deletes the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_createmailbox()
imap_renamemailbox()
imap_open() for the format of mbox

Prev | Home | Next
imap_delete | Up | imap_errors


imap_errors

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_errors -- Returns all of the IMAP errors that have occured

Description

array imap_errors ( void )

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

Return Values

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. Returns FALSE if no error messages are available.

See Also

imap_last_error()
imap_alerts()

Prev | Home | Next
imap_deletemailbox | Up | imap_expunge


imap_expunge

(PHP 3, PHP 4, PHP 5)

imap_expunge -- Delete all messages marked for deletion

Description

bool imap_expunge ( resource imap_stream )

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE.

Prev | Home | Next
imap_errors | Up | imap_fetch_overview


imap_fetch_overview

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_fetch_overview -- Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( resource imap_stream, string sequence [, int options] )

This function fetches mail headers for the given sequence and returns an overview of their contents.

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A message sequence description. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

options

sequence will contain a sequence of message indices or UIDs, if this parameter is set to FT_UID.

Return Values

Returns an array of objects describing one message header each. The object will only define a property if it exists. The possible properties are:

  • subject - the messages subject

  • from - who sent it

  • to - recipient

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • in_reply_to - is a reply to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the mailbox

  • recent - this message is flagged as recent

  • flagged - this message is flagged

  • answered - this message is flagged as answered

  • deleted - this message is flagged for deletion

  • seen - this message is flagged as already read

  • draft - this message is flagged as being a draft

Examples

Example 1. imap_fetch_overview() example

&#60;?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
     or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC-&#62;Nmsgs}",0);
foreach ($result =&#62; $overview) {
    echo "#{$overview-&#62;msgno} ({$overview-&#62;date}) - From: {$overview-&#62;from}
    {$overview-&#62;subject}\n";
}
imap_close($mbox);
?&#62;

See Also

imap_fetchheader()

Prev | Home | Next
imap_expunge | Up | imap_fetchbody


imap_fetchbody

(PHP 3, PHP 4, PHP 5)

imap_fetchbody -- Fetch a particular section of the body of the message

Description

string imap_fetchbody ( resource imap_stream, int msg_number, string part_number [, int options] )

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

part_number

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns a particular section of the body of the specified messages as a text string.

See Also

imap_savebody()
imap_fetchstructure()

Prev | Home | Next
imap_fetch_overview | Up | imap_fetchheader


imap_fetchheader

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( resource imap_stream, int msg_number [, int options] )

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The possible options are:

  • FT_UID - The msgno argument is a UID

  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines

  • FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)

Return Values

Returns the header of the specified message as a text string.

See Also

imap_fetch_overview()

Prev | Home | Next
imap_fetchbody | Up | imap_fetchstructure


imap_fetchstructure

(PHP 3, PHP 4, PHP 5)

imap_fetchstructure -- Read the structure of a particular message

Description

object imap_fetchstructure ( resource imap_stream, int msg_number [, int options] )

Fetches all the structured information for a given message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

This optional parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID.

Return Values

Returns an object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:

Table 1. Returned Objects for imap_fetchstructure()

type | Primary body type
encoding | Body transfer encoding
ifsubtype | TRUE if there is a subtype string
subtype | MIME subtype
ifdescription | TRUE if there is a description string
description | Content description string
ifid | TRUE if there is an identification string
id | Identification string
lines | Number of lines
bytes | Number of bytes
ifdisposition | TRUE if there is a disposition string
disposition | Disposition string
ifdparameters | TRUE if the dparameters array exists
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparameters | TRUE if the parameters array exists
parameters | An array of objects where each object has an "attribute" and a "value" property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Table 2. Primary body type

0 | text
1 | multipart
2 | message
3 | application
4 | audio
5 | image
6 | video
7 | other

Table 3. Transfer encodings

0 | 7BIT
1 | 8BIT
2 | BINARY
3 | BASE64
4 | QUOTED-PRINTABLE
5 | OTHER

See Also

imap_fetchbody()

Prev | Home | Next
imap_fetchheader | Up | imap_get_quota


imap_get_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_get_quota -- Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( resource imap_stream, string quota_root )

Retrieve the quota level settings, and usage statics per mailbox.

For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Return Values

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

As of PHP 4.3, the function more properly reflects the functionality as dictated by the RFC2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it.

For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.

Examples

Example 1. imap_get_quota() example

&#60;?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
    echo "Usage level is: " . $quota_value['usage'];
    echo "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);
?&#62;

Example 2. imap_get_quota() 4.3 or greater example

&#60;?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit is: " .  $message['limit'];

   /* ...  */
}

imap_close($mbox);
?&#62;

Notes

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, other wise this function will fail.

See Also

imap_open()
imap_set_quota()
imap_get_quotaroot()

Prev | Home | Next
imap_fetchstructure | Up | imap_get_quotaroot


imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5)

imap_get_quotaroot -- Retrieve the quota settings per user

Description

array imap_get_quotaroot ( resource imap_stream, string quota_root )

Retrieve the quota settings per user. The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

quota_root should normally be in the form of which mailbox (i.e. INBOX).

Return Values

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

Examples

Example 1. imap_get_quotaroot() example

&#60;?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?&#62;

Notes

This function is currently only available to users of the c-client2000 or greater library.

The imap_stream should be opened as the user whose mailbox you wish to check.

See Also

imap_open()
imap_set_quota()
imap_get_quota()

Prev | Home | Next
imap_get_quota | Up | imap_getacl


imap_getacl

(PHP 5)

imap_getacl -- Gets the ACL for a given mailbox

Description

array imap_getacl ( resource imap_stream, string mailbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Notes

This function is currently only available to users of the c-client2000 or greater library.

See Also

imap_setacl()

Prev | Home | Next
imap_get_quotaroot | Up | imap_getmailboxes


imap_getmailboxes

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( resource imap_stream, string ref, string pattern )

Gets information on the mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Examples

Example 1. imap_getmailboxes() example

&#60;?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $key =&#62; $val) {
        echo "($key) ";
        echo imap_utf7_decode($val-&#62;name) . ",";
        echo "'" . $val-&#62;delimiter . "',";
        echo $val-&#62;attributes . "&#60;br /&#62;\n";
    }
} else {
    echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?&#62;

See Also

imap_getsubscribed()

Prev | Home | Next
imap_getacl | Up | imap_getsubscribed


imap_getsubscribed

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource imap_stream, string ref, string pattern )

Gets information on the subscribeds mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Prev | Home | Next
imap_getmailboxes | Up | imap_header


imap_header

(PHP 3, PHP 4, PHP 5)

imap_header -- Alias of imap_headerinfo()

Description

This function is an alias of: imap_headerinfo().

Prev | Home | Next
imap_getsubscribed | Up | imap_headerinfo


imap_headerinfo

(PHP 3, PHP 4, PHP 5)

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( resource imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]] )

Gets information about the given message number by reading its headers.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

fromlength

Number of characters for the fetchfrom property. Must be greater than or equal to zero.

subjectlength

Number of characters for the fetchsubject property Must be greater than or equal to zero.

defaulthost

Return Values

Returns the information in an object with following properties:

  • toaddress - full to: line, up to 1024 characters

  • to - an array of objects from the To: line, with the following properties: personal, adl, mailbox, and host

  • fromaddress - full from: line, up to 1024 characters

  • from - an array of objects from the From: line, with the following properties: personal, adl, mailbox, and host

  • ccaddress - full cc: line, up to 1024 characters

  • cc - an array of objects from the Cc: line, with the following properties: personal, adl, mailbox, and host

  • bccaddress - full bcc: line, up to 1024 characters

  • bcc - an array of objects from the Bcc: line, with the following properties: personal, adl, mailbox, and host

  • reply_toaddress - full Reply-To: line, up to 1024 characters

  • reply_to - an array of objects from the Reply-To: line, with the following properties: personal, adl, mailbox, and host

  • senderaddress - full sender: line, up to 1024 characters

  • sender - an array of objects from the Sender: line, with the following properties: personal, adl, mailbox, and host

  • return_pathaddress - full Return-Path: line, up to 1024 characters

  • return_path - an array of objects from the Return-Path: line, with the following properties: personal, adl, mailbox, and host

  • remail -

  • date - The message date as found in its headers

  • Date - Same as date

  • subject - The message subject

  • Subject - Same a subject

  • in_reply_to -

  • message_id -

  • newsgroups -

  • followup_to -

  • references -

  • Recent - R if recent and seen, N if recent and not seen, ' ' if not recent.

  • Unseen - U if not seen AND not recent, ' ' if seen OR not seen and recent

  • Flagged - F if flagged, ' ' if not flagged

  • Answered - A if answered, ' ' if unanswered

  • Deleted - D if deleted, ' ' if not deleted

  • Draft - X if draft, ' ' if not draft

  • Msgno - The message number

  • MailDate -

  • Size - The message size

  • udate - mail message date in unix time

  • fetchfrom - from line formatted to fit fromlength characters

  • fetchsubject - subject line formatted to fit subjectlength characters

See Also

imap_fetch_overview()

Prev | Home | Next
imap_header | Up | imap_headers


imap_headers

(PHP 3, PHP 4, PHP 5)

imap_headers -- Returns headers for all messages in a mailbox

Description

array imap_headers ( resource imap_stream )

Returns headers for all messages in a mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns an array of string formatted with header info. One element per mail message.

Prev | Home | Next
imap_headerinfo | Up | imap_last_error


imap_last_error

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_last_error -- Gets the last IMAP error that occurred during this page request

Description

string imap_last_error ( void )

Gets the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

Return Values

Returns the full text of the last IMAP error message that occurred on the current page. Returns FALSE if no error messages are available.

See Also

imap_errors()

Prev | Home | Next
imap_headers | Up | imap_list


imap_list

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_list -- Read the list of mailboxes

Description

array imap_list ( resource imap_stream, string ref, string pattern )

Read the list of mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open().

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array containing the names of the mailboxes.

Examples

Example 1. imap_list() example

&#60;?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $val) {
        echo imap_utf7_decode($val) . "\n";
    }
} else {
    echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?&#62;

See Also

imap_getmailboxes()
imap_lsub()

Prev | Home | Next
imap_last_error | Up | imap_listmailbox


imap_listmailbox

(PHP 3, PHP 4, PHP 5)

imap_listmailbox -- Alias of imap_list()

Description

This function is an alias of: imap_list().

Prev | Home | Next
imap_list | Up | imap_listscan


imap_listscan

(no version information, might be only in CVS)

imap_listscan -- Returns the list of mailboxes that matches the given text

Description

array imap_listscan ( resource imap_stream, string ref, string pattern, string content )

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory

content

The searched string

Return Values

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

See Also

imap_listmailbox()
imap_search()

Prev | Home | Next
imap_listmailbox | Up | imap_listsubscribed


imap_listsubscribed

(PHP 3, PHP 4, PHP 5)

imap_listsubscribed -- Alias of imap_lsub()

Description

This function is an alias of: imap_lsub().

Prev | Home | Next
imap_listscan | Up | imap_lsub


imap_lsub

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_lsub -- List all the subscribed mailboxes

Description

array imap_lsub ( resource imap_stream, string ref, string pattern )

Gets an array of all the mailboxes that you have subscribed.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of all the subscribed mailboxes.

See Also

imap_list()
imap_getmailboxes()

Prev | Home | Next
imap_listsubscribed | Up | imap_mail_compose


imap_mail_compose

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

imap_mail_compose -- Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body )

Create a MIME message based on the given envelope and body sections.

Parameters

envelope

An associative array of headers fields

body

An indexed array of bodies

A body is an associative array which can consist of the following keys: "type", "encoding", "subtype", "description" and "contents.data"

Return Values

Returns the MIME message.

Examples

Example 1. imap_mail_compose() example

&#60;?php

$envelope["from"]= "joe@example.com";
$envelope["to"]  = "foo@example.com";
$envelope["cc"]  = "bar@example.com";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";

$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;

$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;

echo nl2br(imap_mail_compose($envelope, $body));

?&#62;

Prev | Home | Next
imap_lsub | Up | imap_mail_copy


imap_mail_copy

(PHP 3, PHP 4, PHP 5)

imap_mail_copy -- Copy specified messages to a mailbox

Description

bool imap_mail_copy ( resource imap_stream, string msglist, string mailbox [, int options] )

Copies mail messages specified by msglist to specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist is a range not just message numbers (as described in RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS

  • CP_MOVE - Delete the messages from the current mailbox after copying

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_mail_move()

Prev | Home | Next
imap_mail_compose | Up | imap_mail_move


imap_mail_move

(PHP 3, PHP 4, PHP 5)

imap_mail_move -- Move specified messages to a mailbox

Description

bool imap_mail_move ( resource imap_stream, string msglist, string mailbox [, int options] )

Moves mail messages specified by msglist to the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist is a range not just message numbers (as described in RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask and may contain the single option:

  • CP_UID - the sequence numbers contain UIDS

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_mail_copy()

Prev | Home | Next
imap_mail_copy | Up | imap_mail


imap_mail

(PHP 3 >= 3.0.14, PHP 4, PHP 5)

imap_mail -- Send an email message

Description

bool imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]] )

This function allows sending of emails with correct handling of Cc and Bcc receivers.

The parameters to, cc and bcc are all strings and are all parsed as RFC822 address lists.

Parameters

to

The receiver

subject

The mail subject

message

The mail body

additional_headers

As string with additional headers to be set on the mail

cc

bcc

The receivers specified in bcc will get the mail, but are excluded from the headers.

rpath

Use this parameter to specify return path upon mail delivery failure. This is useful when using PHP as a mail client for multiple users.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mail()

Prev | Home | Next
imap_mail_move | Up | imap_mailboxmsginfo


imap_mailboxmsginfo

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( resource imap_stream )

Checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the information in an object with following properties:

Table 1. Mailbox properties

Date | date of last change
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

Returns FALSE on failure.

Examples

Example 1. imap_mailboxmsginfo() example

&#60;?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if ($check) {
    echo "Date: "     . $check-&#62;Date    . "&#60;br /&#62;\n" ;
    echo "Driver: "   . $check-&#62;Driver  . "&#60;br /&#62;\n" ;
    echo "Mailbox: "  . $check-&#62;Mailbox . "&#60;br /&#62;\n" ;
    echo "Messages: " . $check-&#62;Nmsgs   . "&#60;br /&#62;\n" ;
    echo "Recent: "   . $check-&#62;Recent  . "&#60;br /&#62;\n" ;
    echo "Unread: "   . $check-&#62;Unread  . "&#60;br /&#62;\n" ;
    echo "Deleted: "  . $check-&#62;Deleted . "&#60;br /&#62;\n" ;
    echo "Size: "     . $check-&#62;Size    . "&#60;br /&#62;\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "&#60;br /&#62;\n";
}

imap_close($mbox);

?&#62;

Prev | Home | Next
imap_mail | Up | imap_mime_header_decode


imap_mime_header_decode

(PHP 3 >= 3.0.17, PHP 4, PHP 5)

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text )

Decodes MIME message header extensions that are non ASCII text (see RFC2047).

Parameters

text

The MIME text

Return Values

The decoded elements are returned in an array of objects, where each object has two properties, charset and text.

If the element hasn't been encoded, and in other words is in plain US-ASCII, the charset property of that element is set to default.

Examples

Example 1. imap_mime_header_decode() example

&#60;?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= &#60;keld@example.com&#62;";

$elements = imap_mime_header_decode($text);
for ($i=0; $i&#60;count($elements); $i++) {
    echo "Charset: {$elements[$i]-&#62;charset}\n";
    echo "Text: {$elements[$i]-&#62;text}\n\n";
}
?&#62;

The above example will output:

Charset: ISO-8859-1
Text: Keld Jørn Simonsen

Charset: default
Text:  <keld@example.com>

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

See Also

imap_utf8()

Prev | Home | Next
imap_mailboxmsginfo | Up | imap_msgno


imap_msgno

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_msgno -- Gets the message sequence number for the given UID

Description

int imap_msgno ( resource imap_stream, int uid )

Returns the message sequence number for the given uid.

This function is the inverse of imap_uid().

Parameters

imap_stream

An IMAP stream returned by imap_open().

uid

The message UID

Return Values

Returns the message sequence number for the given uid.

See Also

imap_uid()

Prev | Home | Next
imap_mime_header_decode | Up | imap_num_msg


imap_num_msg

(PHP 3, PHP 4, PHP 5)

imap_num_msg -- Gets the number of messages in the current mailbox

Description

int imap_num_msg ( resource imap_stream )

Gets the number of messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Return the number of messages in the current mailbox, as an integer.

See Also

imap_num_recent()
imap_status()

Prev | Home | Next
imap_msgno | Up | imap_num_recent


imap_num_recent

(PHP 3, PHP 4, PHP 5)

imap_num_recent -- Gets the number of recent messages in current mailbox

Description

int imap_num_recent ( resource imap_stream )

Gets the number of recent messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the number of recent messages in the current mailbox, as an integer.

See Also

imap_num_msg()
imap_status()

Prev | Home | Next
imap_num_msg | Up | imap_open


imap_open

(PHP 3, PHP 4, PHP 5)

imap_open -- Open an IMAP stream to a mailbox

Description

resource imap_open ( string mailbox, string username, string password [, int options] )

Opens an IMAP stream to a mailbox.

This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

Parameters

mailbox

A mailbox name consists of a server and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded width imap_utf7_encode().

The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/').

The server part is mandatory in all mailbox parameters.

All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:

  • remote_system_name - Internet domain name or bracketed IP address of server.

  • port - optional TCP port number, default is the default port for that service

  • flags - optional flags, see following table.

  • mailbox_name - remote mailbox name, default is INBOX

Table 1. Optional flags for names

Flag | Description
/service=service | mailbox access service, default is "imap"
/user=user | remote user name for login on the server
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymous | remote access as anonymous user
/debug | record protocol telemetry in application's debug log
/secure | do not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap
/pop3 | equivalent to /service=pop3
/nntp | equivalent to /service=nntp
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session
/ssl | use the Secure Socket Layer to encrypt the session
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior)
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notls | do not do start-TLS to encrypt the session, even with servers that support it
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

username

The user name

password

The password associated with the username

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

  • OP_DEBUG - Debug protocol negotiations

  • OP_SHORTCACHE - Short (elt-only) caching

  • OP_SILENT - Don't pass up events (internal use)

  • OP_PROTOTYPE - Return driver prototype

  • OP_EXPUNGE - Silently expunge recycle stream

  • OP_SECURE - Don't do non-secure authentication

Return Values

Returns an IMAP stream on success or FALSE on error.

Examples

Example 1. Different use of imap_open()

&#60;?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?&#62;

Example 2. imap_open() example

&#60;?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");

echo "&#60;h1&#62;Mailboxes&#60;/h1&#62;\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if ($folders == false) {
    echo "Call failed&#60;br /&#62;\n";
} else {
    foreach ($folders as $val) {
        echo $val . "&#60;br /&#62;\n";
    }
}

echo "&#60;h1&#62;Headers in INBOX&#60;/h1&#62;\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed&#60;br /&#62;\n";
} else {
    foreach ($headers as $val) {
        echo $val . "&#60;br /&#62;\n";
    }
}

imap_close($mbox);
?&#62;

See Also

imap_close()

Prev | Home | Next
imap_num_recent | Up | imap_ping


imap_ping

(PHP 3, PHP 4, PHP 5)

imap_ping -- Check if the IMAP stream is still active

Description

bool imap_ping ( resource imap_stream )

imap_ping() pings the stream to see if it's still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE if the stream is still alive, FALSE otherwise.

Examples

Example 1. imap_ping() Example

&#60;?php

$imap = imap_open("{imap.example.org}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
    // do some stuff to reconnect
}

?&#62;

Prev | Home | Next
imap_open | Up | imap_qprint


imap_qprint

(PHP 3, PHP 4, PHP 5)

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string )

Convert a quoted-printable string to an 8 bit string according to RFC2045, section 6.7.

Parameters

string

A quoted-printable string

Return Values

Returns an 8 bits string.

See Also

imap_8bit()

Prev | Home | Next
imap_ping | Up | imap_renamemailbox


imap_renamemailbox

(PHP 3, PHP 4, PHP 5)

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

bool imap_renamemailbox ( resource imap_stream, string old_mbox, string new_mbox )

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Parameters

imap_stream

An IMAP stream returned by imap_open().

old_mbox

The old mailbox name, see imap_open() for more information

new_mbox

The new mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_createmailbox()
imap_deletemailbox()

Prev | Home | Next
imap_qprint | Up | imap_reopen


imap_reopen

(PHP 3, PHP 4, PHP 5)

imap_reopen -- Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource imap_stream, string mailbox [, int options] )

Reopens the specified stream to a new mailbox on an IMAP or NNTP server.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imap_reopen() example

&#60;?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?&#62;

Prev | Home | Next
imap_renamemailbox | Up | imap_rfc822_parse_adrlist


imap_rfc822_parse_adrlist

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host )

Parses the address string as defined in RFC2822 and for each address.

Parameters

address

A string containing addresses

default_host

The default host name

Return Values

Returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)

  • host - the host name

  • personal - the personal name

  • adl - at domain source route

Examples

Example 1. imap_rfc822_parse_adrlist() example

&#60;?php

$address_string = "Joe Doe &#60;doe@example.com&#62;, postmaster@example.com, root";
$address_array  = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) &#60; 1) {
    die("something is wrong\n");
}

foreach ($address_array as $id =&#62; $val) {
    echo "# $id\n";
    echo "  mailbox : " . $val-&#62;mailbox . "\n";
    echo "  host    : " . $val-&#62;host . "\n";
    echo "  personal: " . $val-&#62;personal . "\n";
    echo "  adl     : " . $val-&#62;adl . "\n";
}
?&#62;

The above example will output:

# 0
  mailbox : doe
  host    : example.com
  personal: Joe Doe
  adl     :
# 1
  mailbox : postmaster
  host    : example.com
  personal:
  adl     :
# 2
  mailbox : root
  host    : example.com
  personal:
  adl     :

See Also

imap_rfc822_parse_headers()

Prev | Home | Next
imap_reopen | Up | imap_rfc822_parse_headers


imap_rfc822_parse_headers

(PHP 4, PHP 5)

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost] )

Gets an object of various header elements, similar to imap_header().

Parameters

headers

The parsed headers data

defaulthost

The default host name

Return Values

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

See Also

imap_rfc822_parse_adrlist()

Prev | Home | Next
imap_rfc822_parse_adrlist | Up | imap_rfc822_write_address


imap_rfc822_write_address

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal )

Returns a properly formatted email address as defined in RFC2822 given the needed information.

Parameters

mailbox

The mailbox name, see imap_open() for more information

host

The email host part

personal

The name of the account owner

Return Values

Returns a string properly formatted email address as defined in RFC2822.

Examples

Example 1. imap_rfc822_write_address() example

&#60;?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?&#62;

The above example will output:

Hartmut Holzgraefe <hartmut@example.com>

Prev | Home | Next
imap_rfc822_parse_headers | Up | imap_savebody


imap_scanmailbox

(PHP 3, PHP 4, PHP 5)

imap_scanmailbox -- Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().

Prev | Home | Next
imap_savebody | Up | imap_search


imap_search

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_search -- This function returns an array of messages matching the given search criteria

Description

array imap_search ( resource imap_stream, string criteria [, int options [, string charset]] )

This function performs a search on the mailbox currently opened in the given imap stream.

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also RFC2060, section 6.4.4).

Parameters

imap_stream

An IMAP stream returned by imap_open().

criteria

A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.

  • ALL - return all messages matching the rest of the criteria

  • ANSWERED - match messages with the \\ANSWERED flag set

  • BCC "string" - match messages with "string" in the Bcc: field

  • BEFORE "date" - match messages with Date: before "date"

  • BODY "string" - match messages with "string" in the body of the message

  • CC "string" - match messages with "string" in the Cc: field

  • DELETED - match deleted messages

  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set

  • FROM "string" - match messages with "string" in the From: field

  • KEYWORD "string" - match messages with "string" as a keyword

  • NEW - match new messages

  • OLD - match old messages

  • ON "date" - match messages with Date: matching "date"

  • RECENT - match messages with the \\RECENT flag set

  • SEEN - match messages that have been read (the \\SEEN flag is set)

  • SINCE "date" - match messages with Date: after "date"

  • SUBJECT "string" - match messages with "string" in the Subject:

  • TEXT "string" - match messages with text "string"

  • TO "string" - match messages with "string" in the To:

  • UNANSWERED - match messages that have not been answered

  • UNDELETED - match messages that are not deleted

  • UNFLAGGED - match messages that are not flagged

  • UNKEYWORD "string" - match messages that do not have the keyword "string"

  • UNSEEN - match messages which have not been read yet

options

Valid values for options are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

charset

Return Values

Returns an array of message numbers or UIDs.

Return FALSE if it does not understand the search criteria or no messages have been found.

ChangeLog

Version | Description
4.3.3 | The charset parameter was added

See Also

imap_listscan()

Prev | Home | Next
imap_scanmailbox | Up | imap_set_quota


imap_set_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_set_quota -- Sets a quota for a given mailbox

Description

bool imap_set_quota ( resource imap_stream, string quota_root, int quota_limit )

Sets an upper limit quota on a per mailbox basis.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: user.name.

quota_limit

The maximum size (in KB) for the quota_root

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imap_set_quota() example

&#60;?php
$mbox = imap_open("{imap.example.org:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    echo "Error in setting quota\n";
    return;
}

imap_close($mbox);
?&#62;

Notes

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, other wise this function will fail.

See Also

imap_open()
imap_get_quota()

Prev | Home | Next
imap_search | Up | imap_setacl


imap_setacl

(PHP 4 >= 4.1.0, PHP 5)

imap_setacl -- Sets the ACL for a giving mailbox

Description

bool imap_setacl ( resource imap_stream, string mailbox, string id, string rights )

Warning

This function is currently not documented; only the argument list is available.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

id

rights

Return Values

Returns TRUE on success or FALSE on failure.

Notes

This function is currently only available to users of the c-client2000 or greater library.

See Also

imap_getacl()

Prev | Home | Next
imap_set_quota | Up | imap_setflag_full


imap_setflag_full

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_setflag_full -- Sets flags on messages

Description

bool imap_setflag_full ( resource imap_stream, string sequence, string flag [, string options] )

Causes a store to add the specified flag to the flags set for the messages in the specified sequence.

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can set are \\Seen, \\Answered, \\Flagged, \\Deleted, and \\Draft as defined by RFC2060.

options

A bit mask that may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. imap_setflag_full() example

&#60;?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?&#62;

See Also

imap_clearflag_full()

Prev | Home | Next
imap_setacl | Up | imap_sort


imap_sort

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_sort -- Gets and sort messages

Description

array imap_sort ( resource imap_stream, int criteria, int reverse [, int options [, string search_criteria [, string charset]]] )

Gets and sorts message numbers by the given parameters.

Parameters

imap_stream

An IMAP stream returned by imap_open().

criteria

Criteria can be one (and only one) of the following:

  • SORTDATE - message Date

  • SORTARRIVAL - arrival date

  • SORTFROM - mailbox in first From address

  • SORTSUBJECT - message subject

  • SORTTO - mailbox in first To address

  • SORTCC - mailbox in first cc address

  • SORTSIZE - size of message in octets

reverse

Set this to 1 for reverse sorting

options

The options are a bitmask of one or more of the following:

  • SE_UID - Return UIDs instead of sequence numbers

  • SE_NOPREFETCH - Don't prefetch searched messages

search_criteria

charset

Return Values

Returns an array of message numbers sorted by the given parameters.

ChangeLog

Version | Description
4.3.3 | The charset parameter was added

Prev | Home | Next
imap_setflag_full | Up | imap_status


imap_status

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_status -- Returns status information on a mailbox

Description

object imap_status ( resource imap_stream, string mailbox, int options )

Gets status information about the given mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

Valid flags are:

  • SA_MESSAGES - set status->messages to the number of messages in the mailbox

  • SA_RECENT - set status->recent to the number of recent messages in the mailbox

  • SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox

  • SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox

  • SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid

  • SA_ALL - set all of the above

Return Values

This function returns an object containing status information. The object has the following properties: messages, recent, unseen, uidnext, and uidvalidity.

flags is also set, which contains a bitmask which can be checked against any of the above constants.

Examples

Example 1. imap_status() example

&#60;?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
  echo "Messages:   " . $status-&#62;messages    . "&#60;br /&#62;\n";
  echo "Recent:     " . $status-&#62;recent      . "&#60;br /&#62;\n";
  echo "Unseen:     " . $status-&#62;unseen      . "&#60;br /&#62;\n";
  echo "UIDnext:    " . $status-&#62;uidnext     . "&#60;br /&#62;\n";
  echo "UIDvalidity:" . $status-&#62;uidvalidity . "&#60;br /&#62;\n";
} else {
  echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?&#62;

Prev | Home | Next
imap_sort | Up | imap_subscribe


imap_subscribe

(PHP 3, PHP 4, PHP 5)

imap_subscribe -- Subscribe to a mailbox

Description

bool imap_subscribe ( resource imap_stream, string mailbox )

Subscribe to a new mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_unsubscribe()

Prev | Home | Next
imap_status | Up | imap_thread


imap_thread

(PHP 4 >= 4.1.0, PHP 5)

imap_thread -- Returns a tree of threaded message

Description

array imap_thread ( resource imap_stream [, int options] )

Gets a tree of a threaded message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

options

Return Values

imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or FALSE on error.

Every message in the current mailbox will be represented by three entries in the resulting array:

  • $thread["XX.num"] - current message number

  • $thread["XX.next"]

  • $thread["XX.branch"]

Examples

Example 1. imap_thread() Example

&#60;?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($threads as $key =&#62; $val) {
  $tree = explode('.', $key);
  if ($tree[1] == 'num') {
    $header = imap_headerinfo($nntp, $val);
    echo "&#60;ul&#62;\n\t&#60;li&#62;" . $header-&#62;fromaddress . "\n";
  } elseif ($tree[1] == 'branch') {
    echo "\t&#60;/li&#62;\n&#60;/ul&#62;\n";
  }
}

imap_close($nntp);

?&#62;

Prev | Home | Next
imap_subscribe | Up | imap_timeout


imap_timeout

(PHP 4 >= 4.3.3, PHP 5)

imap_timeout -- Set or fetch imap timeout

Description

mixed imap_timeout ( int timeout_type [, int timeout] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
imap_thread | Up | imap_uid


imap_uid

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_uid -- This function returns the UID for the given message sequence number

Description

int imap_uid ( resource imap_stream, int msg_number )

This function returns the UID for the given message sequence number. An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes.

This function is the inverse of imap_msgno().

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number.

Return Values

The UID of the given message.

Notes

Note: This function is not supported by POP3 mailboxes.

See Also

imap_msgno()

Prev | Home | Next
imap_timeout | Up | imap_undelete


imap_undelete

(PHP 3, PHP 4, PHP 5)

imap_undelete -- Unmark the message which is marked deleted

Description

bool imap_undelete ( resource imap_stream, int msg_number [, int flags] )

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

flags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_delete()
imap_mail_move()

Prev | Home | Next
imap_uid | Up | imap_unsubscribe


imap_unsubscribe

(PHP 3, PHP 4, PHP 5)

imap_unsubscribe -- Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( string imap_stream, string mailbox )

Unsubscribe from the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_subscribe()

Prev | Home | Next
imap_undelete | Up | imap_utf7_decode


imap_utf7_decode

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

imap_utf7_decode -- Decodes a modified UTF-7 encoded string

Description

string imap_utf7_decode ( string text )

Decodes modified UTF-7 text into ISO-8859-1 string.

This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parameters

text

A modified UTF-7 encoding string, as defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).

Return Values

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.

See Also

imap_utf7_encode()

Prev | Home | Next
imap_unsubscribe | Up | imap_utf7_encode


imap_utf7_encode

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

imap_utf7_encode -- Converts ISO-8859-1 string to modified UTF-7 text

Description

string imap_utf7_encode ( string data )

Converts data to modified UTF-7 text.

This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parameters

data

An ISO-8859-1 string.

Return Values

Returns data encoded with the modified UTF-7 encoding as defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).

See Also

imap_utf7_decode()

Prev | Home | Next
imap_utf7_decode | Up | imap_utf8


imap_utf8

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imap_utf8 -- Converts MIME-encoded text to UTF-8

Description

string imap_utf8 ( string mime_encoded_text )

Converts the given mime_encoded_text to UTF-8.

Parameters

mime_encoded_text

A MIME encoded string. MIME encoding method and the UTF-8 specification are described in RFC2047 and RFC2044 respectively.

Return Values

Returns an UTF-8 encoded string.

See Also

imap_mime_header_decode()

Prev | Home | Next
imap_utf7_encode | Up | Informix Functions


PHP Options&Information

PHP Manual
Prev Next

CXXII. PHP Options&Information

Introduction

This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.

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. PHP Options/Inf Configuration Options

Name | Default | Changeable | Changelog
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
enable_dl | "1" | PHP_INI_SYSTEM |
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
magic_quotes_runtime | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

user function to call on failed assertions

assert.quiet_eval boolean

Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()

enable_dl boolean

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

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, it's always impossible to use dl().

max_execution_time integer

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

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

You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.

Your webserver can have other timeouts. E.g. Apache has Timeout directive, IIS has CGI timeout function, both default to 300 seconds. See the webserver documentation for meaning of it.

max_input_time integer

This sets the maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.

magic_quotes_gpc boolean

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

Note: If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.

See also get_magic_quotes_gpc()

magic_quotes_runtime boolean

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

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are always available as part of the PHP core.

Table 2. Pre-defined phpcredits() constants

Constant | Value | Description
CREDITS_GROUP | 1 | A list of the core developers
CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors.
CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors.
CREDITS_DOCS | 16 | The credits for the documentation team.
CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA | 64 | The credits for the quality assurance team.
CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.

Table 3. phpinfo() constants

Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

Table of Contents
assert_options -- Set/get the various assert flags
assert -- Checks if assertion is FALSE
dl -- Loads a PHP extension at runtime
extension_loaded -- Find out whether an extension is loaded
get_cfg_var -- Gets the value of a PHP configuration option
get_current_user -- Gets the name of the owner of the current PHP script
get_defined_constants -- Returns an associative array with the names of all the constants and their values
get_extension_funcs -- Returns an array with the names of the functions of a module
get_include_path -- Gets the current include_path configuration option
get_included_files -- Returns an array with the names of included or required files
get_loaded_extensions -- Returns an array with the names of all modules compiled and loaded
get_magic_quotes_gpc -- Gets the current configuration setting of magic quotes gpc
get_magic_quotes_runtime -- Gets the current active configuration setting of magic_quotes_runtime
get_required_files -- Alias of get_included_files()
getenv -- Gets the value of an environment variable
getlastmod -- Gets time of last page modification
getmygid -- Get PHP script owner's GID
getmyinode -- Gets the inode of the current script
getmypid -- Gets PHP's process ID
getmyuid -- Gets PHP script owner's UID
getopt -- Gets options from the command line argument list
getrusage -- Gets the current resource usages
ini_alter -- Alias of ini_set()
ini_get_all -- Gets all configuration options
ini_get -- Gets the value of a configuration option
ini_restore -- Restores the value of a configuration option
ini_set -- Sets the value of a configuration option
main -- Dummy for main()
memory_get_peak_usage -- Returns the peak of memory allocated by PHP
memory_get_usage -- Returns the amount of memory allocated to PHP
php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir
php_logo_guid -- Gets the logo guid
php_sapi_name -- Returns the type of interface between web server and PHP
php_uname -- Returns information about the operating system PHP is running on
phpcredits -- Prints out the credits for PHP
phpinfo -- Outputs lots of PHP information
phpversion -- Gets the current PHP version
putenv -- Sets the value of an environment variable
restore_include_path -- Restores the value of the include_path configuration option
set_include_path -- Sets the include_path configuration option
set_magic_quotes_runtime -- Sets the current active configuration setting of magic_quotes_runtime
set_time_limit -- Limits the maximum execution time
sys_get_temp_dir -- Returns directory path used for temporary files
version_compare -- Compares two "PHP-standardized" version number strings
zend_logo_guid -- Gets the Zend guid
zend_version -- Gets the version of the current Zend engine

Prev | Home | Next
PharFileInfo->setUncompressed | Up | assert_options


assert_options

(PHP 4, PHP 5)

assert_options -- Set/get the various assert flags

Description

mixed assert_options ( int what [, mixed value] )

Set the various assert() control options or just query their current settings.

Parameters

what

Table 1. Assert Options

option | ini-parameter | default | description
ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation
ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion
ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK | assert.callback | (NULL) | user function to call on failed assertions

value

An optional new value for the option.

Return Values

Returns the original setting of any option or FALSE on errors.

Prev | Home | Next
PHP Options&Information | Up | assert


assert

(PHP 4, PHP 5)

assert -- Checks if assertion is FALSE

Description

bool assert ( mixed assertion )

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

Parameters

assertion

The assertion.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Examples

Example 1. Handle a failed assertion with a custom handler

&#60;?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "&#60;hr&#62;Assertion Failed:
        File '$file'&#60;br /&#62;
        Line '$line'&#60;br /&#62;
        Code '$code'&#60;br /&#62;&#60;hr /&#62;";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?&#62;

Prev | Home | Next
assert_options | Up | dl


dl

(PHP 3, PHP 4, PHP 5)

dl -- Loads a PHP extension at runtime

Description

int dl ( string library )

Loads the PHP extension given by the parameter library.

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

Parameters

library

This parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php_sockets.dll on the Windows platform.

The directory where the extension is loaded from depends on your platform:

Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\ by default.

Unix - If not explicitly set in the php.ini, the default extension directory depends on

  • whether PHP has been built with --enable-debug or not

  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not

  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

Taking into account the above, the directory then defaults to <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Return Values

Returns TRUE on success or FALSE on failure. If the functionality of loading modules is not available (see Note) or has been disabled (either by turning it off enable_dl or by enabling safe mode in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

Examples

Example 1. dl() examples

&#60;?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        dl('php_sqlite.dll');
    } else {
        dl('sqlite.so');
    }
}

// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
    $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
    dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?&#62;

Notes

Note: dl() is not supported in multithreaded Web servers. Use the extensions statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not affected !

Note: As of PHP 5, the dl() function is deprecated in every SAPI except CLI. Use Extension Loading Directives method instead.

Note: Since PHP 6 this function is disabled in all SAPIs, except CLI, CGI and embed.

Note: dl() is case sensitive on Unix platforms.

Note: This function is disabled in safe mode.

See Also

Extension Loading Directives
extension_loaded()

Prev | Home | Next
assert | Up | extension_loaded


extension_loaded

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

extension_loaded -- Find out whether an extension is loaded

Description

bool extension_loaded ( string name )

Finds out whether the extension is loaded.

Parameters

name

The extension name.

You can see the names of various extensions by using phpinfo() or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions:

$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

Return Values

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Examples

Example 1. extension_loaded() example

&#60;?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}
?&#62;

Notes

Note: extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extension available which also use uppercase letters. Be warned that this function compares case sensitive !

See Also

get_loaded_extensions()
get_extension_funcs()
phpinfo()
dl()

Prev | Home | Next
dl | Up | get_cfg_var


get_cfg_var

(PHP 3, PHP 4, PHP 5)

get_cfg_var -- Gets the value of a PHP configuration option

Description

string get_cfg_var ( string option )

Gets the value of a PHP configuration option.

This function will not return configuration information set when the PHP was compiled, or read from an Apache configuration file (using the php3_configuration_option directives).

To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.

Parameters

option

The configuration option name.

Return Values

Returns the current value of the PHP configuration variable specified by varname, or FALSE if an error occurs.

See Also

ini_get()

Prev | Home | Next
extension_loaded | Up | get_current_user


get_current_user

(PHP 3, PHP 4, PHP 5)

get_current_user -- Gets the name of the owner of the current PHP script

Description

string get_current_user ( void )

Returns the name of the owner of the current PHP script.

Return Values

Returns the username as a string.

See Also

getmyuid()
getmygid()
getmypid()
getmyinode()
getlastmod()

Prev | Home | Next
get_cfg_var | Up | get_defined_constants


get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constants -- Returns an associative array with the names of all the constants and their values

Description

array get_defined_constants ( [mixed categorize] )

Returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.

Parameters

categorize

May be passed, causing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension.

&#60;?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?&#62;

The above example will output something similar to:

Array
(
    [internal] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

Note: The value of the categorize parameter is irrelevant, only its presence is considered.

Return Values

ChangeLog

Version | Description
5.0.0 | The categorize parameter was added.

Examples

Example 1. get_defined_constants() Example

&#60;?php
print_r(get_defined_constants());
?&#62;

The above example will output something similar to:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

See Also

defined()
get_loaded_extensions()
get_defined_functions()
get_defined_vars()

Prev | Home | Next
get_current_user | Up | get_extension_funcs


get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcs -- Returns an array with the names of the functions of a module

Description

array get_extension_funcs ( string module_name )

This function returns the names of all the functions defined in the module indicated by module_name.

Parameters

module_name

The module name.

Note: This parameter must be in lowercase.

Return Values

Returns an array with all the functions, or FALSE if module_name is not a valid extension.

Examples

Example 1. Prints the XML functions

&#60;?php
print_r(get_extension_funcs("xml"));
?&#62;

The above example will output something similar to:

Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
    [3] => xml_set_element_handler
    [4] => xml_set_character_data_handler
    [5] => xml_set_processing_instruction_handler
    [6] => xml_set_default_handler
    [7] => xml_set_unparsed_entity_decl_handler
    [8] => xml_set_notation_decl_handler
    [9] => xml_set_external_entity_ref_handler
    [10] => xml_set_start_namespace_decl_handler
    [11] => xml_set_end_namespace_decl_handler
    [12] => xml_parse
    [13] => xml_parse_into_struct
    [14] => xml_get_error_code
    [15] => xml_error_string
    [16] => xml_get_current_line_number
    [17] => xml_get_current_column_number
    [18] => xml_get_current_byte_index
    [19] => xml_parser_free
    [20] => xml_parser_set_option
    [21] => xml_parser_get_option
    [22] => utf8_encode
    [23] => utf8_decode
)

See Also

get_loaded_extensions()

Prev | Home | Next
get_defined_constants | Up | get_include_path


get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_path -- Gets the current include_path configuration option

Description

string get_include_path ( void )

Gets the current include_path configuration option value.

Return Values

Returns the path, as a string.

Examples

Example 1. get_include_path() example

&#60;?php
// Works as of PHP 4.3.0
echo get_include_path();

// Works in all PHP versions
echo ini_get('include_path');
?&#62;

See Also

ini_get()
restore_include_path()
set_include_path()
include()

Prev | Home | Next
get_extension_funcs | Up | get_included_files


get_included_files

(PHP 4, PHP 5)

get_included_files -- Returns an array with the names of included or required files

Description

array get_included_files ( void )

Gets the names of all files that have been included using include(), include_once(), require() or require_once().

Return Values

Returns an array of the names of all files.

The script originally called is considered an "included file," so it will be listed together with the files referenced by include() and family.

Files that are included or required multiple times only show up once in the returned array.

ChangeLog

Version | Description
4.0.1 | In PHP 4.0.1 and previous versions this function assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().

Examples

Example 1. get_included_files() example

&#60;?php
// This file is abc.php

include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';

$included_files = get_included_files();

foreach ($included_files as $filename) {
    echo "$filename\n";
}

?&#62;

The above example will output:

abc.php
test1.php
test2.php
test3.php
test4.php

Notes

Note: Files included using the auto_prepend_file configuration directive are not included in the returned array.

See Also

include()
include_once()
require()
require_once()
get_required_files()

Prev | Home | Next
get_include_path | Up | get_loaded_extensions


get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensions -- Returns an array with the names of all modules compiled and loaded

Description

array get_loaded_extensions ( void )

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

Return Values

Returns an indexed array of all the modules names.

Examples

Example 1. get_loaded_extensions() Example

&#60;?php
print_r(get_loaded_extensions());
?&#62;

The above example will output something similar to:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

See Also

get_extension_funcs()
extension_loaded()
dl()
phpinfo()

Prev | Home | Next
get_included_files | Up | get_magic_quotes_gpc


get_magic_quotes_gpc

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

get_magic_quotes_gpc -- Gets the current configuration setting of magic quotes gpc

Description

int get_magic_quotes_gpc ( void )

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that the setting magic_quotes_gpc will not work at runtime.

For more information about magic_quotes, see this security section.

Return Values

Returns 0 if magic quotes gpc are off, 1 otherwise.

Examples

Example 1. get_magic_quotes_gpc() example

&#60;?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?&#62;

Notes

Note: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''

See Also

addslashes()
stripslashes()
get_magic_quotes_runtime()
ini_get()

Prev | Home | Next
get_loaded_extensions | Up | get_magic_quotes_runtime


get_magic_quotes_runtime

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

get_magic_quotes_runtime -- Gets the current active configuration setting of magic_quotes_runtime

Description

int get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

Return Values

Returns 0 if magic quotes runtime is off, 1 otherwise.

See Also

get_magic_quotes_gpc()
set_magic_quotes_runtime()

Prev | Home | Next
get_magic_quotes_gpc | Up | get_required_files


get_required_files

(PHP 4, PHP 5)

get_required_files -- Alias of get_included_files()

Description

This function is an alias of: get_included_files().

Prev | Home | Next
get_magic_quotes_runtime | Up | getenv


getenv

(PHP 3, PHP 4, PHP 5)

getenv -- Gets the value of an environment variable

Description

string getenv ( string varname )

Gets the value of an environment variable.

You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the CGI specification, specifically the page on environmental variables.

Parameters

varname

The variable name.

Return Values

Returns the value of the environment variable varname, or FALSE on an error.

Examples

Example 1. getenv() Example

&#60;?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?&#62;

See Also

putenv()
apache_getenv()
Superglobals

Prev | Home | Next
get_required_files | Up | getlastmod


getlastmod

(PHP 3, PHP 4, PHP 5)

getlastmod -- Gets time of last page modification

Description

int getlastmod ( void )

Gets the time of the last modification of the current page.

If you're interested in getting the last modification time of a different file, consider using filemtime().

Return Values

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.

Examples

Example 1. getlastmod() example

&#60;?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?&#62;

See Also

date()
getmyuid()
getmygid()
get_current_user()
getmyinode()
getmypid()
filemtime()

Prev | Home | Next
getenv | Up | getmygid


getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygid -- Get PHP script owner's GID

Description

int getmygid ( void )

Gets the group ID of the current script.

Return Values

Returns the group ID of the current script, or FALSE on error.

See Also

getmyuid()
getmypid()
get_current_user()
getmyinode()
getlastmod()

Prev | Home | Next
getlastmod | Up | getmyinode


getmyinode

(PHP 3, PHP 4, PHP 5)

getmyinode -- Gets the inode of the current script

Description

int getmyinode ( void )

Gets the inode of the current script.

Return Values

Returns the current script's inode as a string, or FALSE on error.

Notes

Note: This function is not implemented on Windows platforms.

See Also

getmygid()
getmyuid()
getmypid()
get_current_user()
getlastmod()

Prev | Home | Next
getmygid | Up | getmypid


getmypid

(PHP 3, PHP 4, PHP 5)

getmypid -- Gets PHP's process ID

Description

int getmypid ( void )

Gets the current PHP process ID.

Return Values

Returns the current PHP process ID, or FALSE on error.

Notes

Warning

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

See Also

getmygid()
getmyuid()
get_current_user()
getmyinode()
getlastmod()

Prev | Home | Next
getmyinode | Up | getmyuid


getmyuid

(PHP 3, PHP 4, PHP 5)

getmyuid -- Gets PHP script owner's UID

Description

int getmyuid ( void )

Gets the user ID of the current script.

Return Values

Returns the user ID of the current script, or FALSE on error.

See Also

getmygid()
getmypid()
get_current_user()
getmyinode()
getlastmod()

Prev | Home | Next
getmypid | Up | getopt


getopt

(PHP 4 >= 4.3.0, PHP 5)

getopt -- Gets options from the command line argument list

Description

array getopt ( string options )

Returns an associative array of option / argument pairs based on the options format specified in options, or FALSE on an error.

Parameters

options

The options parameter may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string x recognizes an option -x, and an option string x: recognizes an option and argument -x argument. It does not matter if an argument has leading white space.

Return Values

This function will return an array of option / argument pairs. If an option does not have an argument, the value will be set to FALSE.

Examples

Example 1. getopt() Example

&#60;?php
// parse the command line ($GLOBALS['argv'])
$options = getopt("f:hp:");
?&#62;

Notes

Note: This function is not implemented on Windows platforms.

Prev | Home | Next
getmyuid | Up | getrusage


getrusage

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

getrusage -- Gets the current resource usages

Description

array getrusage ( [int who] )

This is an interface to getrusage(2). It gets data returned from the system call.

Parameters

who

If who is 1, getrusage will be called with RUSAGE_CHILDREN.

Return Values

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.

Examples

Example 1. getrusage() example

&#60;?php
$dat = getrusage();
echo $dat["ru_nswap"];         // number of swaps
echo $dat["ru_majflt"];        // number of page faults
echo $dat["ru_utime.tv_sec"];  // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
?&#62;

Notes

Note: This function is not implemented on Windows platforms.

See Also

Your system's man page on getrusage(2)

Prev | Home | Next
getopt | Up | ini_alter


ini_alter

(PHP 4, PHP 5)

ini_alter -- Alias of ini_set()

Description

This function is an alias of: ini_set().

Prev | Home | Next
getrusage | Up | ini_get_all


ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all -- Gets all configuration options

Description

array ini_get_all ( [string extension] )

Returns all the registered configuration options.

Parameters

extension

An optional extension name. If set, the function return only options specific for that extension.

Return Values

Returns an associative array uses the directive name as the array key, with elements of that array being global_value (set in php.ini), local_value (perhaps set with ini_set() or .htaccess), and access (the access level). See the manual section on configuration changes for information on what access levels mean.

Note: It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.

Examples

Example 1. A ini_get_all() example

&#60;?php
$inis = ini_get_all();

print_r($inis);

?&#62;

The above example will output something similar to:

Array
(
    [allow_call_time_pass_reference] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 6
    )
    [allow_url_fopen] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 7
    )

    ...

)

See Also

ini_get()
ini_restore()
ini_set()
get_loaded_extensions()
phpinfo()

Prev | Home | Next
ini_alter | Up | ini_get


ini_get

(PHP 4, PHP 5)

ini_get -- Gets the value of a configuration option

Description

string ini_get ( string varname )

Returns the value of the configuration option on success.

Parameters

varname

The configuration option name.

Return Values

Returns the value of the configuration option as a string on success, or an empty string on failure.

Examples

Example 1. A few ini_get() examples

&#60;?php
/*
Our php.ini contains the following settings:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

?&#62;

The above example will output something similar to:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Notes

When querying boolean values: A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1".

When querying memory size values: Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example below shows one way to convert shorthand notation into bytes, much like how the PHP source does it.

See Also

get_cfg_var()
ini_get_all()
ini_restore()
ini_set()

Prev | Home | Next
ini_get_all | Up | ini_restore


ini_restore

(PHP 4, PHP 5)

ini_restore -- Restores the value of a configuration option

Description

void ini_restore ( string varname )

Restores a given configuration option to its original value.

Parameters

varname

The configuration option name.

Return Values

No value is returned.

See Also

ini_get()
ini_get_all()
ini_set()

Prev | Home | Next
ini_get | Up | ini_set


ini_set

(PHP 4, PHP 5)

ini_set -- Sets the value of a configuration option

Description

string ini_set ( string varname, string newvalue )

Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

Parameters

varname

Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

newvalue

The new value for the option.

Return Values

Returns the old value on success, FALSE on failure.

See Also

get_cfg_var()
ini_get()
ini_get_all()
ini_restore()
How to change configuration settings

Prev | Home | Next
ini_restore | Up | main


main

(no version information, might be only in CVS)

main -- Dummy for main()

Description

There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.

Sometimes error messages refer to a manual page for the function main() which is why this page exists. Please add a user comment below that mentions what PHP function caused the error that linked to main() and it will be fixed and properly documented.

Table 1. Known errors that point to main()

Function name | No longer points here as of
include() | 5.1.0
include_once() | 5.1.0
require() | 5.1.0
require_once() | 5.1.0

See Also

html_errors
display_errors

Prev | Home | Next
ini_set | Up | memory_get_peak_usage


memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usage -- Returns the amount of memory allocated to PHP

Description

int memory_get_usage ( [bool real_usage] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

memory_get_usage() will only be defined if your PHP is compiled with the --enable-memory-limit configuration option.

Parameters

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

Return Values

Returns the memory amount in bytes.

ChangeLog

Version | Description
5.2.0 | real_usage was added.

Examples

Example 1. A memory_get_usage() example

&#60;?php
// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

?&#62;

See Also

memory_get_peak_usage()
memory_limit

Prev | Home | Next
memory_get_peak_usage | Up | php_ini_scanned_files


php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir

Description

string php_ini_scanned_files ( void )

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir option which is set during compilation.

The returned configuration files also include the path as declared in the --with-config-file-scan-dir option.

Return Values

Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the directive --with-config-files-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().

Examples

Example 1. A simple example to list the returned ini files

&#60;?php
if ($filelist = php_ini_scanned_files()) {
    if (strlen($filelist) &#62; 0) {
        $files = explode(',', $filelist);

        foreach ($files as $file) {
            echo "&#60;li&#62;" . trim($file) . "&#60;/li&#62;\n";
        }
    }
}
?&#62;

See Also

ini_set()
phpinfo()

Prev | Home | Next
memory_get_usage | Up | php_logo_guid


php_logo_guid

(PHP 4, PHP 5)

php_logo_guid -- Gets the logo guid

Description

string php_logo_guid ( void )

This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.

Return Values

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Examples

Example 1. php_logo_guid() example

&#60;?php

echo '&#60;img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" /&#62;';

?&#62;

See Also

phpinfo()
phpversion()
phpcredits()
zend_logo_guid()

Prev | Home | Next
php_ini_scanned_files | Up | php_sapi_name


php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_name -- Returns the type of interface between web server and PHP

Description

string php_sapi_name ( void )

Returns a lowercase string which describes the type of interface between web server and PHP (Server API, SAPI). In CGI PHP, this string is "cgi", in mod_php for Apache, this string is "apache" and so on.

Return Values

Returns the interface type, as a lowercase string.

Examples

Example 1. php_sapi_name() example

&#60;?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    echo "You are using CGI PHP\n";
} else {
    echo "You are not using CGI PHP\n";
}
?&#62;

See Also

PHP_SAPI

Prev | Home | Next
php_logo_guid | Up | php_uname


php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_uname -- Returns information about the operating system PHP is running on

Description

string php_uname ( [string mode] )

php_uname() returns a description of the operating system PHP is running on. For the name of just the operating system, consider using the PHP_OS constant, but be reminded this constant will contain the operating system PHP was built on.

On Unix, the output reverts to displaying the operating system information PHP was built on if it cannot determine the currently running OS.

Parameters

mode

mode is a single character that defines what information is returned:

  • 'a': This is the default. Contains all modes in the sequence "s n r v m".

  • 's': Operating system name. eg. FreeBSD.

  • 'n': Host name. eg. localhost.example.com.

  • 'r': Release name. eg. 5.1.2-RELEASE.

  • 'v': Version information. Varies a lot between operating systems.

  • 'm': Machine type. eg. i386.

Return Values

Returns the description, as a string.

Examples

Example 1. Some php_uname() examples

&#60;?php
echo php_uname();
echo PHP_OS;

/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

?&#62;

There are also some related Predefined PHP constants that may come in handy, for example:

Example 2. A few OS related constant examples

&#60;?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX;    // so
echo PATH_SEPARATOR;      // :

// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX;    // dll
echo PATH_SEPARATOR;      // ;
?&#62;

See Also

phpversion()
php_sapi_name()
phpinfo()

Prev | Home | Next
php_sapi_name | Up | phpcredits


phpcredits

(PHP 4, PHP 5)

phpcredits -- Prints out the credits for PHP

Description

bool phpcredits ( [int flag] )

This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page.

Parameters

flag

To generate a custom credits page, you may want to use the flag parameter. flag is optional, and it defaults to CREDITS_ALL.

Table 1. Pre-defined phpcredits() flags

name | description
CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS | The credits for the documentation team
CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP | A list of the core developers
CREDITS_MODULES | A list of the extension modules for PHP, and their authors
CREDITS_SAPI | A list of the server API modules for PHP, and their authors

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Prints the general credits

&#60;?php
phpcredits(CREDITS_GENERAL);
?&#62;

Example 2. Prints the core developers and the documentation group

&#60;?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?&#62;

Example 3. Printing all the credits

&#60;html&#62;
 &#60;head&#62;
  &#60;title&#62;My credits page&#60;/title&#62;
 &#60;/head&#62;
 &#60;body&#62;
&#60;?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?&#62;
 &#60;/body&#62;
&#60;/html&#62;

See Also

phpversion()
php_logo_guid()
phpinfo()

Prev | Home | Next
php_uname | Up | phpinfo


phpinfo

(PHP 3, PHP 4, PHP 5)

phpinfo -- Outputs lots of PHP information

Description

bool phpinfo ( [int what] )

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.

phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

Parameters

what

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.

Table 1. phpinfo() options

Name (constant) | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings. See also get_loaded_extensions().
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the license FAQ.
INFO_ALL | -1 | Shows all of the above. This is the default value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. phpinfo() Example

&#60;?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?&#62;

Notes

Note: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.

Note: phpinfo() outputs plain text instead of HTML when using the CLI mode.

See Also

phpversion()
phpcredits()
php_logo_guid()
ini_get()
ini_set()
get_loaded_extensions()
Predefined Variables

Prev | Home | Next
phpcredits | Up | phpversion


phpversion

(PHP 3, PHP 4, PHP 5)

phpversion -- Gets the current PHP version

Description

string phpversion ( [string extension] )

Returns a string containing the version of the currently running PHP parser or extension.

Parameters

extension

An optional extension name.

Return Values

If the optional extension parameter is specified, phpversion() returns the version of that extension, or FALSE if there is no version information associated or the extension isn't enabled.

Examples

Example 1. phpversion() example

&#60;?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?&#62;

Notes

Note: This information is also available in the predefined constant PHP_VERSION.

See Also

version_compare()
phpinfo()
phpcredits()
php_logo_guid()
zend_version()

Prev | Home | Next
phpinfo | Up | putenv


putenv

(PHP 3, PHP 4, PHP 5)

putenv -- Sets the value of an environment variable

Description

bool putenv ( string setting )

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

Parameters

setting

The setting, like "FOO=BAR"

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Setting an environment variable

&#60;?php
putenv("UNIQID=$uniqid");
?&#62;

Notes

Warning

These directives have only effect when safe-mode itself is enabled!

See Also

getenv()

Prev | Home | Next
phpversion | Up | restore_include_path


restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_path -- Restores the value of the include_path configuration option

Description

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

Return Values

No value is returned.

Examples

Example 1. restore_include_path() example

&#60;?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path();  // /inc

// Works as of PHP 4.3.0
restore_include_path();

// Works in all PHP versions
ini_restore('include_path');

echo get_include_path();  // .:/usr/local/lib/php

?&#62;

See Also

ini_restore()
get_include_path()
set_include_path()
include()

Prev | Home | Next
putenv | Up | set_include_path


set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_path -- Sets the include_path configuration option

Description

string set_include_path ( string new_include_path )

Sets the include_path configuration option for the duration of the script.

Parameters

new_include_path

The new value for the include_path

Return Values

Returns the old include_path on success or FALSE on failure.

Examples

Example 1. set_include_path() example

&#60;?php
// Works as of PHP 4.3.0
set_include_path('/inc');

// Works in all PHP versions
ini_set('include_path', '/inc');
?&#62;

Example 2. Adding to the include path

Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.

In this example we add /usr/lib/pear to the end of the existing include_path.

&#60;?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?&#62;

See Also

ini_set()
get_include_path()
restore_include_path()
include()

Prev | Home | Next
restore_include_path | Up | set_magic_quotes_runtime


set_magic_quotes_runtime

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

set_magic_quotes_runtime -- Sets the current active configuration setting of magic_quotes_runtime

Description

bool set_magic_quotes_runtime ( int new_setting )

Set the current active configuration setting of magic_quotes_runtime.

Parameters

new_setting

0 for off, 1 for on.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

get_magic_quotes_gpc()
get_magic_quotes_runtime()

Prev | Home | Next
set_include_path | Up | set_time_limit


set_time_limit

(PHP 3, PHP 4, PHP 5)

set_time_limit -- Limits the maximum execution time

Description

void set_time_limit ( int seconds )

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Parameters

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Return Values

No value is returned.

Notes

Warning

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running.

See Also

max_execution_time
max_input_time

Prev | Home | Next
set_magic_quotes_runtime | Up | sys_get_temp_dir


version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compare -- Compares two "PHP-standardized" version number strings

Description

mixed version_compare ( string version1, string version2 [, string operator] )

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: dev < alpha = a < beta = b < RC < pl. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.

Parameters

version1

First version number.

version2

Second version number.

operator

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.

Return Values

version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and +1 if the second is lower.

Examples

Example 1. version_compare() example

&#60;?php
// prints -1
echo version_compare("4.0.4", "4.0.6");

// these all print 1
echo version_compare("4.0.4", "4.0.6", "&#60;");
echo version_compare("4.0.6", "4.0.6", "eq");
?&#62;

Notes

Note: The PHP_VERSION constant holds current PHP version.

Prev | Home | Next
sys_get_temp_dir | Up | zend_logo_guid


zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guid -- Gets the Zend guid

Description

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

Return Values

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Examples

Example 1. zend_logo_guid() example

&#60;?php

echo '&#60;img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" /&#62;';

?&#62;

See Also

php_logo_guid()

Prev | Home | Next
version_compare | Up | zend_version


zend_version

(PHP 4, PHP 5)

zend_version -- Gets the version of the current Zend engine

Description

string zend_version ( void )

Returns a string containing the version of the currently running Zend Engine.

Return Values

Returns the Zend Engine version number, as a string.

Examples

Example 1. zend_version() example

&#60;?php
echo "Zend engine version: " . zend_version();
?&#62;

The above example will output something similar to:

Zend engine version: 2.2.0

See Also

phpinfo()
phpcredits()
php_logo_guid()
phpversion()

Prev | Home | Next
zend_logo_guid | Up | POSIX Functions


Ingres II Functions

PHP Manual
Prev Next

LXVIII. Ingres II Functions

Introduction

These functions allow you to access Ingres II database servers.

Note: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be committed or rolled back before opening another transaction (which is automatically done when sending the first query).

Requirements

To compile PHP with Ingres support, you need the Ingres OpenAPI library and header files.

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/ingres.

In order to have these functions available, you must compile PHP with Ingres support by using the --with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.

When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environment variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Ingres configuration options

Name | Default | Changeable | Changelog
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.default_database | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.default_user | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.default_password | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.report_db_warnings | "1" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since version 1.2.0 of the PECL extension.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since version 1.3.1 of the PECL extension.
ingres.timeout | "-1" | PHP_INI_ALL | Available since version 1.3.1 of the PECL extension.
ingres.array_index_start | "1" | PHP_INI_ALL | Available since version 1.3.1 of the PECL extension.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

INGRES_ASSOC (integer)

Columns are returned into the array having the fieldname as the array index.

INGRES_NUM (integer)

Columns are returned into the array having a numerical index to the fields. This index starts with 1, the first field in the result.

INGRES_BOTH (integer)

Columns are returned into the array having both a numerical index and the fieldname as the array index.

INGRES_EXT_VERSION (string)

Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.

INGRES_API_VERSION (integer)

Specifies the version of Ingres OpenAPI the extension was built against. Available since version 1.2.0 of the PECL extension.

INGRES_CURSOR_READONLY (integer)

Specifies that Ingres cursors should be opened in 'readonly' mode. Available since version 1.2.0 of the PECL extension.

INGRES_CURSOR_UPDATE (integer)

Specifies that Ingres cursors should be opened 'for update'. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MULTINATIONAL (integer)

Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MULTINATIONAL4 (integer)

Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_FINNISH (integer)

Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_ISO (integer)

Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_ISO4 (integer)

Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_GERMAN (integer)

Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MDY (integer)

Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_DMY (integer)

Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_YMD (integer)

Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.

INGRES_MONEY_LEADING (integer)

Specifies the currency character that should be placed at the start of a money value. Equivalent to setting II_MONEY_FORMAT to 'L:'. Available since version 1.2.0 of the PECL extension.

INGRES_MONEY_TRAILING (integer)

Specifies the currency character that should be placed at the end of a money value. Equivalent to setting II_MONEY_FORMAT to 'T:'. Available since version 1.2.0 of the PECL extension.

INGRES_STRUCTURE_BTREE (integer)

Specifies the default table or index structure to BTREE when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_CBTREE (integer)

Specifies the default table or index structure to COMPRESSED BTREE when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_HASH (integer)

Specifies the default table or index structure to HASH when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_CHASH (integer)

Specifies the default table or index structure to COMPRESSED HASH when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_HEAP (integer)

Specifies the default table structure to HEAP when used in combination with the table_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_CHEAP (integer)

Specifies the default table structure to COMPRESSED HEAP when used in combination with the table_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_ISAM (integer)

Specifies the default table or index structure to ISAM when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

INGRES_STRUCTURE_CISAM (integer)

Specifies the default table or index structure to COMPRESSED ISAM when used in combination with the table_structure or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.

Examples

This simple example shows how to connect, execute a query, print resulting rows and disconnect from an Ingres database.

Example 1. Simple Ingres Example

&#60;?php
// Connecting, selecting database
$link = ingres_connect('database', 'user', 'password')
    or die('Could not connect: ' . ingres_error($link));
echo 'Connected successfully';

// Select from a table that exists in all Ingres databases
$query = 'SELECT * FROM iirelation';
$returncode = ingres_query($query,$link) or die('Query failed: ' .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "&#60;table&#62;\n";
while ($iirelation = ingres_fetch_object(INGRES_BOTH, $link)) {
    echo "\t&#60;tr&#62;\n";
    echo "\t\t&#60;td&#62;" . $iirelation-&#62;relid . "&#60;/td&#62;\n";
    echo "\t\t&#60;td&#62;" . $iirelation-&#62;relowner . "&#60;/td&#62;\n";
    echo "\t&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

// Commit transaction
ingres_commit($link);
// Closing connection
ingres_close($link);
?&#62;

Table of Contents
ingres_autocommit -- Switch autocommit on or off
ingres_close -- Close an Ingres II database connection
ingres_commit -- Commit a transaction
ingres_connect -- Open a connection to an Ingres database
ingres_cursor -- Gets a cursor name for a given link resource
ingres_errno -- Gets the last ingres error number generated
ingres_error -- Gets a meaningful error message for the last error generated
ingres_errsqlstate -- Gets the last SQLSTATE error code generated
ingres_fetch_array -- Fetch a row of result into an array
ingres_fetch_object -- Fetch a row of result into an object
ingres_fetch_row -- Fetch a row of result into an enumerated array
ingres_field_length -- Get the length of a field
ingres_field_name -- Get the name of a field in a query result
ingres_field_nullable -- Test if a field is nullable
ingres_field_precision -- Get the precision of a field
ingres_field_scale -- Get the scale of a field
ingres_field_type -- Get the type of a field in a query result
ingres_num_fields -- Get the number of fields returned by the last query
ingres_num_rows -- Get the number of rows affected or returned by the last query
ingres_pconnect -- Open a persistent connection to an Ingres II database
ingres_query -- Send a SQL query to Ingres II
ingres_rollback -- Roll back a transaction

Prev | Home | Next
PDO_INFORMIX DSN | Up | ingres_autocommit


ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link] )

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the "autocommit" mode of the server on or off (when the script begins the autocommit mode is off).

When the autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query().

See also
ingres_query(),
ingres_rollback(), and
ingres_commit().

Prev | Home | Next
Ingres II Functions | Up | ingres_close


ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link] )

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

Prev | Home | Next
ingres_autocommit | Up | ingres_commit


ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link] )

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new one can be open by sending a query with ingres_query().

You can also have the server commit automatically after every query by calling ingres_autocommit() before opening the transaction.

See also
ingres_query(),
ingres_rollback(), and
ingres_autocommit().

Prev | Home | Next
ingres_close | Up | ingres_connect


ingres_connect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_connect -- Open a connection to an Ingres database

Description

resource ingres_connect ( [string database [, string username [, string password [, array options]]]] )

Returns a Ingres link resource on success, or FALSE on failure.

ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user and ingres.default_password.

The connection is closed when the script ends or when ingres_close() is called on this link.

All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.

ingres_connect() options

Option name | Description
date_century_boundary | The threshold by which a 2 digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY.
group | Speficfies the group ID of the user, equivalent to the '-G' flag
role | The role ID of the application. If a role password is required, the parameter value should be specified as "role/password"
effective_user | The ingres user account being impersonated, equivalent to the '-u' flag
dbms_password | The internal database password for the user connecting to Ingres
table_structure The default structure for new tables. Valid values for table_structure are:

  • INGRES_STRUCTURE_BTREE

  • INGRES_STRUCTURE_HASH

  • INGRES_STRUCTURE_HEAP

  • INGRES_STRUCTURE_ISAM

  • INGRES_STRUCTURE_CBTREE

  • INGRES_STRUCTURE_CISAM

  • INGRES_STRUCTURE_CHASH

  • INGRES_STRUCTURE_CHEAP

index_structure The default structure for new secondary indexes. Valid values for index_structure are:

  • INGRES_STRUCTURE_CBTREE

  • INGRES_STRUCTURE_CISAM

  • INGRES_STRUCTURE_CHASH

  • INGRES_STRUCTURE_BTREE

  • INGRES_STRUCTURE_HASH

  • INGRES_STRUCTURE_ISAM

login_local | Determines how the connection user ID and password are used when a VNODE is included in the target database string. If set to TRUE, the user ID and password are used to locally access the VNODE and the VNODE login information is used to establish the DBMS connection. If set to FALSE, the process user ID is used to access the VNODE and the connection user ID and password are used in place of the VNODE login information to establish the DBMS connection. This parameter is ignored if no VNODE is included in the target database string. The default is FALSE.
timezone | Controls the timezone of the session. If not set it will default the the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined the NA-PACIFIC (GMT-8 with Daylight Savings) is used.
date_format Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set the default date format is US, e.g. mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY

  • INGRES_DATE_FINISH

  • INGRES_DATE_GERMAN

  • INGRES_DATE_ISO

  • INGRES_DATE_ISO4

  • INGRES_DATE_MDY

  • INGRES_DATE_MULTINATIONAL

  • INGRES_DATE_MULTINATIONAL4

  • INGRES_DATE_YMD

  • INGRES_DATE_US

decimal_separator | The character identifier for decimal data
money_lort Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING

  • INGRES_MONEY_TRAILING

money_sign | The currency symbol to be used with the MONEY datatype
money_precision | The precision of the MONEY datatype
float4_precision | Precision of the FLOAT4 datatype
float8_precision | Precision of the FLOAT8 data
blob_segment_length | The amount of data in bytes to fetch at a time when retrieving BLOB/CLOB data, defaults to 4096 bytes when not explicitly set.

Example 1. ingres_connect() example

&#60;?php
    $link = ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close($link);
?&#62;

Example 2. ingres_connect() example using default link

&#60;?php
    ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close();
?&#62;

See also ingres_pconnect() and ingres_close().

Prev | Home | Next
ingres_commit | Up | ingres_cursor


ingres_fetch_array

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]] )

ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column.

&#60;?php

ingres_query("select t1.f1 as foo t2.f1 as bar from t1, t2");
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];

?&#62;

result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Example 1. ingres_fetch_array() example

&#60;?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?&#62;

See also
ingres_query(),
ingres_num_fields(),
ingres_field_name(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_errsqlstate | Up | ingres_fetch_object


ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_object -- Fetch a row of result into an object

Description

object ingres_fetch_object ( [int result_type [, resource link]] )

ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Example 1. ingres_fetch_object() example

&#60;?php
ingres_connect($database, $user, $password);
ingres_query("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row-&#62;user_id;
    echo $row-&#62;fullname;
}
?&#62;

See also
ingres_query(),
ingres_num_fields(),
ingres_field_name(),
ingres_fetch_array(), and
ingres_fetch_row().

Prev | Home | Next
ingres_fetch_array | Up | ingres_fetch_row


ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_row -- Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link] )

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Example 1. ingres_fetch_row() example

&#60;?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?&#62;

See also
ingres_num_fields(),
ingres_query(),
ingres_fetch_array(), and
ingres_fetch_object().

Prev | Home | Next
ingres_fetch_object | Up | ingres_field_length


ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link] )

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_fetch_row | Up | ingres_field_name


ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_name -- Get the name of a field in a query result

Description

string ingres_field_name ( int index [, resource link] )

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object() and
ingres_fetch_row().

Prev | Home | Next
ingres_field_length | Up | ingres_field_nullable


ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link] )

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_field_name | Up | ingres_field_precision


ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link] )

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_field_nullable | Up | ingres_field_scale


ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link] )

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_field_precision | Up | ingres_field_type


ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_type -- Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link] )

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_field_scale | Up | ingres_num_fields


ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_num_fields -- Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link] )

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_field_type | Up | ingres_num_rows


ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_num_rows -- Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link] )

For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

Note: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.

You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

Prev | Home | Next
ingres_num_fields | Up | ingres_pconnect


ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_pconnect -- Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]] )

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.

See also ingres_connect() and ingres_close().

Prev | Home | Next
ingres_num_rows | Up | ingres_query


ingres_query

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link] )

Returns TRUE on success, or FALSE on failure.

ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Some types of SQL queries can't be sent with this function:

  • close (see ingres_close())

  • commit (see ingres_commit())

  • connect (see ingres_connect())

  • disconnect (see ingres_close())

  • get dbevent

  • prepare to commit

  • rollback (see ingres_rollback())

  • savepoint

  • set autocommit (see ingres_autocommit())

  • all cursor related queries are unsupported

Example 1. ingres_query() example

&#60;?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?&#62;

See also
ingres_fetch_array(),
ingres_fetch_object(),
ingres_fetch_row(),
ingres_commit(),
ingres_rollback(), and
ingres_autocommit().

Prev | Home | Next
ingres_pconnect | Up | ingres_rollback


ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link] )

ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.

This closes the transaction. A new one can be open by sending a query with ingres_query().

See also
ingres_query(),
ingres_commit(), and
ingres_autocommit().

Prev | Home | Next
ingres_query | Up | IRC Gateway Functions


IRC Gateway Functions

PHP Manual
Prev Next

LXIX. IRC Gateway Functions

Introduction

With IRCG you can rapidly stream XML data to thousands of concurrently connected users. This can be used to build powerful, extensible interactive platforms such as online games and webchats. IRCG also features support for a non-streaming mode where a helper application reformats incoming data and supplies static file snippets in special formats such as cHTML (i-mode) or WML (WAP). These static files are then delivered by the high-performance web server.

Up to v4, IRCG runs under these platforms:

  • AIX

  • FreeBSD

  • HP-UX

  • Irix

  • Linux

  • Solaris

  • Tru64

  • Windows

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Installation

Detailed installation instructions can be found at http://www.schumann.cx/ircg/. We urge you to use the provided installation script.

It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, --with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Predefined Constants

This extension has no constants defined.

Table of Contents
ircg_channel_mode -- Set channel mode flags for user
ircg_disconnect -- Close connection to server
ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parameters
ircg_fetch_error_msg -- Returns the error from previous IRCG operation
ircg_get_username -- Get username for connection
ircg_html_encode -- Encodes HTML preserving output
ircg_ignore_add -- Add a user to your ignore list on a server
ircg_ignore_del -- Remove a user from your ignore list on a server
ircg_invite -- Invites nickname to channel
ircg_is_conn_alive -- Check connection status
ircg_join -- Join a channel on a connected server
ircg_kick -- Kick a user out of a channel on server
ircg_list -- List topic/user count of channel(s)
ircg_lookup_format_messages -- Check for the existence of a format message set
ircg_lusers -- IRC network statistics
ircg_msg -- Send message to channel or user on server
ircg_names -- Query visible usernames
ircg_nick -- Change nickname on server
ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape -- Decodes encoded nickname
ircg_notice -- Send a notice to a user on server
ircg_oper -- Elevates privileges to IRC OPER
ircg_part -- Leave a channel on server
ircg_pconnect -- Connect to an IRC server
ircg_register_format_messages -- Register a format message set
ircg_set_current -- Set current connection for output
ircg_set_file -- Set logfile for connection
ircg_set_on_die -- Set action to be executed when connection dies
ircg_topic -- Set topic for channel on server
ircg_who -- Queries server for WHO information
ircg_whois -- Query server for user information

Prev | Home | Next
ingres_rollback | Up | ircg_channel_mode


ircg_channel_mode

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_channel_mode -- Set channel mode flags for user

Description

bool ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick )

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.

Prev | Home | Next
IRC Gateway Functions | Up | ircg_disconnect


ircg_disconnect

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_disconnect -- Close connection to server

Description

bool ircg_disconnect ( resource connection, string reason )

ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().

See also: ircg_pconnect().

Prev | Home | Next
ircg_channel_mode | Up | ircg_eval_ecmascript_params


ircg_eval_ecmascript_params

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parameters

Description

array ircg_eval_ecmascript_params ( string params )

Warning

This function is currently not documented; only the argument list is available.

From the ircg_eval_ecmascript_params source file:
   /*
    * State 0: Looking for ' or digit
    * State 1: Assembling parameter inside '..'
    * State 2: After escape sign: Copies single char verbatim, go to 1
    * State 3: Assembling numeric para, no quotation
    * State 4: Looking for ",", skipping whitespace
    */

See also ircg_lookup_format_messages().

Prev | Home | Next
ircg_disconnect | Up | ircg_fetch_error_msg


ircg_fetch_error_msg

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

ircg_fetch_error_msg -- Returns the error from previous IRCG operation

Description

array ircg_fetch_error_msg ( resource connection )

ircg_fetch_error_msg() returns the error from a failed connection.

Note: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.

Example 1. ircg_fetch_error_msg() example

&#60;?php
if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    echo "Can't join channel #php. Error code:
          $error[0] Description: $error[1]";
}
?&#62;

Prev | Home | Next
ircg_eval_ecmascript_params | Up | ircg_get_username


ircg_get_username

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

ircg_get_username -- Get username for connection

Description

string ircg_get_username ( resource connection )

Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.

Prev | Home | Next
ircg_fetch_error_msg | Up | ircg_html_encode


ircg_html_encode

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_html_encode -- Encodes HTML preserving output

Description

string ircg_html_encode ( string html_string [, bool auto_links [, bool conv_br]] )

Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.

Prev | Home | Next
ircg_get_username | Up | ircg_ignore_add


ircg_ignore_add

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_ignore_add -- Add a user to your ignore list on a server

Description

void ircg_ignore_add ( resource connection, string nick )

This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.

See also: ircg_ignore_del().

Prev | Home | Next
ircg_html_encode | Up | ircg_ignore_del


ircg_ignore_del

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_ignore_del -- Remove a user from your ignore list on a server

Description

bool ircg_ignore_del ( resource connection, string nick )

This function removes user nick from the IRCG ignore list associated with connection.

See also: ircg_ignore_add().

Prev | Home | Next
ircg_ignore_add | Up | ircg_invite


ircg_invite

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_invite -- Invites nickname to channel

Description

bool ircg_invite ( resource connection, string channel, string nickname )

ircg_invite() will send an invitation to the user nickname, prompting him to join channel. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ircg_ignore_del | Up | ircg_is_conn_alive


ircg_is_conn_alive

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_is_conn_alive -- Check connection status

Description

bool ircg_is_conn_alive ( resource connection )

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.

Prev | Home | Next
ircg_invite | Up | ircg_join


ircg_join

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_join -- Join a channel on a connected server

Description

bool ircg_join ( resource connection, string channel [, string key] )

Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.

Prev | Home | Next
ircg_is_conn_alive | Up | ircg_kick


ircg_kick

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_kick -- Kick a user out of a channel on server

Description

bool ircg_kick ( resource connection, string channel, string nick, string reason )

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

Prev | Home | Next
ircg_join | Up | ircg_list


ircg_list

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_list -- List topic/user count of channel(s)

Description

bool ircg_list ( resource connection, string channel )

ircg_list() will request a list of users in the channel. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Returns TRUE on success or FALSE on failure.

Example 1. ircg_list() example

&#60;?php

// connect to server
$id = ircg_pconnect($nickname, $ip, $port);

// set to output to a file
ircg_set_file($id, 'irc_output.html');

// try to join a channel
if (!ircg_join($id, $channel)) {
    echo "Cannot /join $channel&#60;br /&#62;";
}

// send list command
ircg_list($id, $channel);

// wait for output to arrive
sleep(5);

// disconnect
ircg_disconnect($id,'Bye World');

// output everything
readfile('irc_output.html');

?&#62;

This example will output something similar to:

...
Channel #channel has n users and the topic is 'Topic'
End of LIST
...

See also: ircg_set_file(),
ircg_set_current(), and
ircg_who().

Prev | Home | Next
ircg_kick | Up | ircg_lookup_format_messages


ircg_lookup_format_messages

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_lookup_format_messages -- Check for the existence of a format message set

Description

bool ircg_lookup_format_messages ( string name )

Check for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.

See also: ircg_register_format_messages()

Prev | Home | Next
ircg_list | Up | ircg_lusers


ircg_lusers

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_lusers -- IRC network statistics

Description

bool ircg_lusers ( resource connection )

ircg_lusers() will request a statistical breakdown of users on the network connected to on connection. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Returns TRUE on success or FALSE on failure.

See also: ircg_set_file(), and ircg_set_current().

Prev | Home | Next
ircg_lookup_format_messages | Up | ircg_msg


ircg_msg

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_msg -- Send message to channel or user on server

Description

bool ircg_msg ( resource connection, string recipient, string message [, bool suppress] )

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.

Prev | Home | Next
ircg_lusers | Up | ircg_names


ircg_names

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_names -- Query visible usernames

Description

bool ircg_names ( int connection, string channel [, string target] )

Warning

This function is currently not documented; only the argument list is available.

See also ircg_get_username() and ircg_lusers().

Prev | Home | Next
ircg_msg | Up | ircg_nick


ircg_nick

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_nick -- Change nickname on server

Description

bool ircg_nick ( resource connection, string nick )

Change your nickname on the given connection to the one given in nick, if possible.

Will return TRUE on success and FALSE on failure.

Prev | Home | Next
ircg_names | Up | ircg_nickname_escape


ircg_nickname_escape

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick )

Function ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.

See also: ircg_nickname_unescape()

Prev | Home | Next
ircg_nick | Up | ircg_nickname_unescape


ircg_nickname_unescape

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

ircg_nickname_unescape -- Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick )

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

Prev | Home | Next
ircg_nickname_escape | Up | ircg_notice


ircg_notice

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_notice -- Send a notice to a user on server

Description

bool ircg_notice ( resource connection, string nick, string message )

This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.

Prev | Home | Next
ircg_nickname_unescape | Up | ircg_oper


ircg_oper

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_oper -- Elevates privileges to IRC OPER

Description

bool ircg_oper ( resource connection, string name, string password )

ircg_oper() will authenticate the logged in user on connection as an IRC operator. name and password must match a registered IRC operator account. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ircg_notice | Up | ircg_part


ircg_part

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_part -- Leave a channel on server

Description

bool ircg_part ( resource connection, string channel )

Leave the channel channel on the server connected to by connection.

Prev | Home | Next
ircg_oper | Up | ircg_pconnect


ircg_pconnect

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_pconnect -- Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings [, bool bailout_on_trivial]]]]]] )

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Note: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.

You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.

If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.

You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.

See also: ircg_disconnect(),
ircg_is_conn_alive(),
ircg_register_format_messages().

Prev | Home | Next
ircg_part | Up | ircg_register_format_messages


ircg_register_format_messages

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_register_format_messages -- Register a format message set

Description

bool ircg_register_format_messages ( string name, array messages )

With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

Prev | Home | Next
ircg_pconnect | Up | ircg_set_current


ircg_set_current

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_set_current -- Set current connection for output

Description

bool ircg_set_current ( resource connection )

Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().

See also: ircg_register_format_messages().

Prev | Home | Next
ircg_register_format_messages | Up | ircg_set_file


ircg_set_file

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

ircg_set_file -- Set logfile for connection

Description

bool ircg_set_file ( resource connection, string path )

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

Prev | Home | Next
ircg_set_current | Up | ircg_set_on_die


ircg_set_on_die

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

ircg_set_on_die -- Set action to be executed when connection dies

Description

bool ircg_set_on_die ( resource connection, string host, int port, string data )

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.

This feature requires IRCG 3.

Prev | Home | Next
ircg_set_file | Up | ircg_topic


ircg_topic

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_topic -- Set topic for channel on server

Description

bool ircg_topic ( resource connection, string channel, string new_topic )

Change the topic for channel channel on the server connected to by connection to new_topic.

Prev | Home | Next
ircg_set_on_die | Up | ircg_who


ircg_who

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_who -- Queries server for WHO information

Description

bool ircg_who ( resource connection, string mask [, bool ops_only] )

ircg_who() will request a list of users whose nickname is matching mask on connected network connection. The optional parameter ops_only will shrink the list to server operators only.

The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Returns TRUE on success or FALSE on failure.

See also: ircg_set_file(), and ircg_set_current().

Prev | Home | Next
ircg_topic | Up | ircg_whois


ircg_whois

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_whois -- Query server for user information

Description

bool ircg_whois ( resource connection, string nick )

Sends a query to the connected server connection to ask for information about the specified user nick.

Prev | Home | Next
ircg_who | Up | PHP / Java Integration


PHP / Java Integration

PHP Manual
Prev Next

LXX. PHP / Java Integration

Introduction

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

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 a Java VM installed on your machine to use this extension.

Installation

This PECL extension is not bundled with PHP.

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 Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build extensions can be found in php-src/ext/java/README.

Windows users will enable php_java.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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Note: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Java configuration options

Name | Default | Changeable | Changelog
java.class.path | NULL | PHP_INI_ALL |
java.home | NULL | PHP_INI_ALL |
java.library.path | NULL | PHP_INI_ALL |
java.library | JAVALIB | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

Example 1. Java Example

&#60;?php
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');

// demonstrate property access
echo 'Java version=' . $system-&#62;getProperty('java.version') . '&#60;br /&#62;';
echo 'Java vendor=' . $system-&#62;getProperty('java.vendor') . '&#60;br /&#62;';
echo 'OS=' . $system-&#62;getProperty('os.name') . ' ' .
             $system-&#62;getProperty('os.version') . ' on ' .
             $system-&#62;getProperty('os.arch') . ' &#60;br /&#62;';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
                      "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

echo $formatter-&#62;format(new Java('java.util.Date'));
?&#62;

Example 2. AWT Example

&#60;?php
// This example is only intended to be run as a CGI.

$frame  = new Java('java.awt.Frame', 'PHP');
$button = new Java('java.awt.Button', 'Hello Java World!');

$frame-&#62;add('North', $button);
$frame-&#62;validate();
$frame-&#62;pack();
$frame-&#62;visible = True;

$thread = new Java('java.lang.Thread');
$thread-&#62;sleep(10000);

$frame-&#62;dispose();
?&#62;
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

    • java_last_exception_get()

    • java_last_exception_clear()

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advantage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Table of Contents
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception

Prev | Home | Next
ircg_whois | Up | java_last_exception_clear


java_last_exception_clear

(PHP 4 >= 4.0.2, PECL)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void )

Clears last Java exception.

Return Values

No value is returned.

Examples

See java_last_exception_get() for an example.

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.

Prev | Home | Next
PHP / Java Integration | Up | java_last_exception_get


java_last_exception_get

(PHP 4 >= 4.0.2, PECL)

java_last_exception_get -- Get last Java exception

Description

object java_last_exception_get ( void )

Gets last Java exception.

Return Values

Returns an exception object.

Examples

The following example demonstrates the usage of Java's exception handler from within PHP:

Example 1. Java exception handler

&#60;?php
$stack = new Java('java.util.Stack');
$stack-&#62;push(1);

// This should succeed
$result = $stack-&#62;pop();
$ex = java_last_exception_get();
if (!$ex) {
  echo "$result\n";
}

// This should fail (error suppressed by @)
$result = @$stack-&#62;pop();
$ex = java_last_exception_get();
if ($ex) {
  echo $ex-&#62;toString();
}

// Clear last exception
java_last_exception_clear();
?&#62;

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.

Prev | Home | Next
java_last_exception_clear | Up | JSON Functions


LDAP Functions

PHP Manual
Prev Next

LXXIII. LDAP Functions

Introduction

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like:

/usr/local/myapp/docs

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:

cn=John Smith,ou=Accounts,o=My Company,c=US

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:

country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Lots of information about LDAP can be found at

  • Mozilla

  • OpenLDAP Project

The Netscape SDK contains a helpful Programmer's Guide in HTML format.

Requirements

You will need to get and compile LDAP client libraries from either OpenLDAP or Bind9.net in order to compile PHP with LDAP support.

Installation

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy several files from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your windows machine. (Ex: C:\WINNT\SYSTEM32, or C:\WINDOWS\SYSTEM). For PHP <= 4.2.0 copy libsasl.dll, for PHP >= 4.3.0 copy libeay32.dll and ssleay32.dll to your SYSTEM folder.

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. LDAP configuration options

Name | Default | Changeable | Changelog
ldap.max_links | "-1" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)

Examples

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Example 1. LDAP search example

&#60;?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "&#60;h3&#62;LDAP query test&#60;/h3&#62;";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "&#60;br /&#62;";

if ($ds) {
    echo "Binding ...";
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "&#60;br /&#62;";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");
    echo "Search result is " . $sr . "&#60;br /&#62;";

    echo "Number of entires returned is " . ldap_count_entries($ds, $sr) . "&#60;br /&#62;";

    echo "Getting entries ...&#60;p&#62;";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:&#60;p&#62;";

    for ($i=0; $i&#60;$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "&#60;br /&#62;";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "&#60;br /&#62;";
        echo "first email entry is: " . $info[$i]["mail"][0] . "&#60;br /&#62;&#60;hr /&#62;";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "&#60;h4&#62;Unable to connect to LDAP server&#60;/h4&#62;";
}
?&#62;

Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:

ldap_connect() // establish connection to server
|
ldap_bind() // anonymous or authenticated "login"
|
do something like search or update the directory
and display the results
|
ldap_close() // "logout"

Table of Contents
ldap_8859_to_t61 -- Translate 8859 characters to t61 characters
ldap_add -- Add entries to LDAP directory
ldap_bind -- Bind to LDAP directory
ldap_close -- Alias of ldap_unbind()
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str -- Convert LDAP error number into string error message
ldap_errno -- Return the LDAP error number of the last LDAP command
ldap_error -- Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference -- Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values_len -- Get all binary values from a result entry
ldap_get_values -- Get all values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference -- Get next reference
ldap_parse_reference -- Extract information from reference entry
ldap_parse_result -- Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_sasl_bind -- Bind to LDAP directory using SASL
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing
ldap_sort -- Sort LDAP result entries
ldap_start_tls -- Start TLS
ldap_t61_to_8859 -- Translate t61 characters to 8859 characters
ldap_unbind -- Unbind from LDAP directory

Prev | Home | Next
kadm5_modify_principal | Up | ldap_8859_to_t61


ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5)

ldap_8859_to_t61 -- Translate 8859 characters to t61 characters

Description

string ldap_8859_to_t61 ( string value )

Translate ISO-8859 characters to t61 characters.

This function is useful if you have to talk to a legacy LDAPv2 server.

Parameters

value

The text to be translated.

Return Values

Return the t61 translation of value.

See Also

ldap_t61_to_8859()

Prev | Home | Next
LDAP Functions | Up | ldap_add


ldap_add

(PHP 3, PHP 4, PHP 5)

ldap_add -- Add entries to LDAP directory

Description

bool ldap_add ( resource link_identifier, string dn, array entry )

Add entries in the LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An array that specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.

&#60;?php
$entree["attribut1"] = "value";
$entree["attribut2"][0] = "value1";
$entree["attribut2"][1] = "value2";
?&#62;

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Complete example with authenticated bind

&#60;?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"] = "John Jones";
    $info["sn"] = "Jones";
    $info["mail"] = "jonj@example.com";
    $info["objectclass"] = "person";

    // add data to directory
    $r = ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?&#62;

Notes

Note: This function is binary-safe.

Prev | Home | Next
ldap_8859_to_t61 | Up | ldap_bind


ldap_bind

(PHP 3, PHP 4, PHP 5)

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]] )

Binds to the LDAP directory with specified RDN and password.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

bind_rdn

bind_password

If bind_rdn and bind_password are not specified, an anonymous bind is attempted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Using LDAP Bind

&#60;?php

// using ldap bind
$ldaprdn  = 'uname';     // ldap rdn or dn
$ldappass = 'password';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }

}

?&#62;

Example 2. Using LDAP Bind Anonymously

&#60;?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";
    } else {
        echo "LDAP bind anonymous failed...";
    }

}

?&#62;

Prev | Home | Next
ldap_add | Up | ldap_close


ldap_close

(PHP 3, PHP 4, PHP 5)

ldap_close -- Alias of ldap_unbind()

Description

This function is an alias of: ldap_unbind().

Prev | Home | Next
ldap_bind | Up | ldap_compare


ldap_compare

(PHP 4 >= 4.0.2, PHP 5)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

mixed ldap_compare ( resource link_identifier, string dn, string attribute, string value )

Compare value of attribute with value of same attribute in an LDAP directory entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

attribute

The attribute name.

value

The compared value.

Return Values

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

Examples

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Example 1. Complete example of password check

&#60;?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {

    // bind
    if (ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password";

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: " . ldap_error($ds);
        } elseif ($r === true) {
            echo "Password correct.";
        } elseif ($r === false) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?&#62;

Notes

Warning

ldap_compare() can NOT be used to compare BINARY values!

Prev | Home | Next
ldap_close | Up | ldap_connect


ldap_connect

(PHP 3, PHP 4, PHP 5)

ldap_connect -- Connect to an LDAP server

Description

resource ldap_connect ( [string hostname [, int port]] )

Establishes a connection to a LDAP server on a specified hostname and port.

Parameters

hostname

If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and set this parameter as ldaps://hostname/.

port

The port to connect to. Not used when using URLs. Defaults to 389.

Return Values

Returns a positive LDAP link identifier on success, or FALSE on error. When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* funcs, usually with ldap_bind().

If no arguments are specified then the link identifier of the already opened link will be returned.

ChangeLog

Version | Description
4.0.4 | URL and SSL support was added.

Examples

Example 1. Example of connecting to LDAP server.

&#60;?php

// LDAP variables
$ldaphost = "ldap.example.com";  // your ldap servers
$ldapport = 389;                 // your ldap server's port number

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport)
          or die("Could not connect to $ldaphost");

?&#62;

Example 2. Example of connecting securely to LDAP server.

&#60;?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost)
          or die("Could not connect to {$ldaphost}");

?&#62;

See Also

ldap_bind()

Prev | Home | Next
ldap_compare | Up | ldap_count_entries


ldap_count_entries

(PHP 3, PHP 4, PHP 5)

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries ( resource link_identifier, resource result_identifier )

Returns the number of entries stored in the result of previous search operations.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

The internal LDAP result.

Return Values

Returns number of entries in the result or FALSE on error.

Prev | Home | Next
ldap_connect | Up | ldap_delete


ldap_delete

(PHP 3, PHP 4, PHP 5)

ldap_delete -- Delete an entry from a directory

Description

bool ldap_delete ( resource link_identifier, string dn )

Deletes a particular entry in LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ldap_count_entries | Up | ldap_dn2ufn


ldap_dn2ufn

(PHP 3, PHP 4, PHP 5)

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn ( string dn )

Turns the specified dn, into a more user-friendly form, stripping off type names.

Parameters

dn

The distinguished name of an LDAP entity.

Return Values

Returns the user friendly name.

Prev | Home | Next
ldap_delete | Up | ldap_err2str


ldap_err2str

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ldap_err2str -- Convert LDAP error number into string error message

Description

string ldap_err2str ( int errno )

Returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Parameters

errno

The error number.

Return Values

Returns the error message, as a string.

Examples

Example 1. Enumerating all LDAP error messages

&#60;?php
  for ($i=0; $i&#60;100; $i++) {
    printf("Error $i: %s&#60;br /&#62;\n", ldap_err2str($i));
  }
?&#62;

See Also

ldap_errno()
ldap_error()

Prev | Home | Next
ldap_dn2ufn | Up | ldap_errno


ldap_errno

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ldap_errno -- Return the LDAP error number of the last LDAP command

Description

int ldap_errno ( resource link_identifier )

Returns the standardized error number returned by the last LDAP command. This number can be converted into a textual error message using ldap_err2str().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Return the LDAP error number of the last LDAP command for this link.

Examples

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Example 1. Generating and catching an error

&#60;?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    echo "LDAP-Errno: " . ldap_errno($ld) . "&#60;br /&#62;\n";
    echo "LDAP-Error: " . ldap_error($ld) . "&#60;br /&#62;\n";
    die("Argh!&#60;br /&#62;\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.&#60;br /&#62;\n";
?&#62;

See Also

ldap_err2str()
ldap_error()

Prev | Home | Next
ldap_err2str | Up | ldap_error


ldap_error

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ldap_error -- Return the LDAP error message of the last LDAP command

Description

string ldap_error ( resource link_identifier )

Returns the string error message explaining the error generated by the last LDAP command for the given link_identifier. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Returns string error message.

See Also

ldap_err2str()
ldap_errno()

Prev | Home | Next
ldap_errno | Up | ldap_explode_dn


ldap_explode_dn

(PHP 3, PHP 4, PHP 5)

ldap_explode_dn -- Splits DN into its component parts

Description

array ldap_explode_dn ( string dn, int with_attrib )

Splits the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN.

Parameters

dn

The distinguished name of an LDAP entity.

with_attrib

Used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

Return Values

Returns an array of all DN components.

Prev | Home | Next
ldap_error | Up | ldap_first_attribute


ldap_first_attribute

(PHP 3, PHP 4, PHP 5)

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute ( resource link_identifier, resource result_entry_identifier, int &ber_identifier )

Gets the first attribute in the given entry. Remaining attributes are retrieved by calling ldap_next_attribute() successively.

Similar to reading entries, attributes are also read one by one from a particular entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to ldap_next_attribute() , which modifies that pointer.

Return Values

Returns the first attribute in the entry on success and FALSE on error.

See Also

ldap_next_attribute()
ldap_get_attributes()

Prev | Home | Next
ldap_explode_dn | Up | ldap_first_entry


ldap_first_entry

(PHP 3, PHP 4, PHP 5)

ldap_first_entry -- Return first result id

Description

resource ldap_first_entry ( resource link_identifier, resource result_identifier )

Returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Return Values

Returns the result entry identifier for the first entry on success and FALSE on error.

See Also

ldap_get_entries()

Prev | Home | Next
ldap_first_attribute | Up | ldap_first_reference


ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_first_reference -- Return first reference

Description

resource ldap_first_reference ( resource link, resource result )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_first_entry | Up | ldap_free_result


ldap_free_result

(PHP 3, PHP 4, PHP 5)

ldap_free_result -- Free result memory

Description

bool ldap_free_result ( resource result_identifier )

Frees up the memory allocated internally to store the result. All result memory will be automatically freed when the script terminates.

Typically all the memory allocated for the LDAP result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.

Parameters

result_identifier

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ldap_first_reference | Up | ldap_get_attributes


ldap_get_attributes

(PHP 3, PHP 4, PHP 5)

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes ( resource link_identifier, resource result_entry_identifier )

Reads attributes and values from an entry in the search result.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.

return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

Examples

Example 1. Show the list of attributes held for a particular directory entry

&#60;?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"] . " attributes held for this entry:&#60;p&#62;";

for ($i=0; $i &#60; $attrs["count"]; $i++) {
    echo $attrs[$i] . "&#60;br /&#62;";
}
?&#62;

See Also

ldap_first_attribute()
ldap_next_attribute()

Prev | Home | Next
ldap_free_result | Up | ldap_get_dn


ldap_get_dn

(PHP 3, PHP 4, PHP 5)

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn ( resource link_identifier, resource result_entry_identifier )

Finds out the DN of an entry in the result.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns the DN of the result entry and FALSE on error.

Prev | Home | Next
ldap_get_attributes | Up | ldap_get_entries


ldap_get_entries

(PHP 3, PHP 4, PHP 5)

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries ( resource link_identifier, resource result_identifier )

Reads multiple entries from the given result, and then reading the attributes and multiple values.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Return Values

Returns a complete result information in a multi-dimensional array on success and FALSE on error.

The structure of the array is as follows. The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)

return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] =  DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

See Also

ldap_first_entry()
ldap_next_entry()

Prev | Home | Next
ldap_get_dn | Up | ldap_get_option


ldap_get_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_get_option -- Get the current value for given option

Description

bool ldap_get_option ( resource link_identifier, int option, mixed &retval )

Sets retval to the value of the specified option.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array

retval

This will be set to the option value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Check protocol version

&#60;?php
// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version)) {
    echo "Using protocol version $version\n";
} else {
    echo "Unable to determine protocol version\n";
}
?&#62;

Notes

Note: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

ldap_set_option()

Prev | Home | Next
ldap_get_entries | Up | ldap_get_values_len


ldap_get_values_len

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ldap_get_values_len -- Get all binary values from a result entry

Description

array ldap_get_values_len ( resource link_identifier, resource result_entry_identifier, string attribute )

Reads all the values of the attribute in the entry in the result.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Return Values

Returns an array of values for the attribute on success and FALSE on error. Individual values are accessed by integer index in the array. The first index is 0. The number of values can be found by indexing "count" in the resultant array.

Prev | Home | Next
ldap_get_option | Up | ldap_get_values


ldap_get_values

(PHP 3, PHP 4, PHP 5)

ldap_get_values -- Get all values from a result entry

Description

array ldap_get_values ( resource link_identifier, resource result_entry_identifier, string attribute )

Reads all the values of the attribute in the entry in the result.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Return Values

Returns an array of values for the attribute on success and FALSE on error. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"

return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute

Examples

Example 1. List all values of the "mail" attribute for a directory entry

&#60;?php
// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry, "mail");

echo $values["count"] . " email addresses for this entry.&#60;br /&#62;";

for ($i=0; $i &#60; $values["count"]; $i++) {
    echo $values[$i] . "&#60;br /&#62;";
}
?&#62;

Prev | Home | Next
ldap_get_values_len | Up | ldap_list


ldap_list

(PHP 3, PHP 4, PHP 5)

ldap_list -- Single-level search

Description

resource ldap_list ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.

  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.

  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.

  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Return Values

Returns a search result identifier or FALSE on error.

ChangeLog

Version | Description
4.0.5 | Parallel searches support was added. See ldap_search() for details.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Examples

Example 1. Produce a list of all organizational units of an organization

// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr=ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i<$info["count"]; $i++) {
    echo $info[$i]["ou"][0] ;
}

See Also

ldap_search()

Prev | Home | Next
ldap_get_values | Up | ldap_mod_add


ldap_mod_add

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ldap_mod_add -- Add attribute values to current attributes

Description

bool ldap_mod_add ( resource link_identifier, string dn, array entry )

Adds one or more attributes to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is binary-safe.

Prev | Home | Next
ldap_list | Up | ldap_mod_del


ldap_mod_del

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ldap_mod_del -- Delete attribute values from current attributes

Description

bool ldap_mod_del ( resource link_identifier, string dn, array entry )

Removes one or more attributes from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ldap_mod_add | Up | ldap_mod_replace


ldap_mod_replace

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ldap_mod_replace -- Replace attribute values with new ones

Description

bool ldap_mod_replace ( resource link_identifier, string dn, array entry )

Replaces one or more attributes from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is binary-safe.

Prev | Home | Next
ldap_mod_del | Up | ldap_modify


ldap_modify

(PHP 3, PHP 4, PHP 5)

ldap_modify -- Modify an LDAP entry

Description

bool ldap_modify ( resource link_identifier, string dn, array entry )

Modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is binary-safe.

Prev | Home | Next
ldap_mod_replace | Up | ldap_next_attribute


ldap_next_attribute

(PHP 3, PHP 4, PHP 5)

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute ( resource link_identifier, resource result_entry_identifier, resource &ber_identifier )

Retrieves the attributes in an entry. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

The internal state of the pointer is maintained by this parameter.

Return Values

Returns the next attribute in an entry on success and FALSE on error.

See Also

ldap_get_attributes()

Prev | Home | Next
ldap_modify | Up | ldap_next_entry


ldap_next_entry

(PHP 3, PHP 4, PHP 5)

ldap_next_entry -- Get next result entry

Description

resource ldap_next_entry ( resource link_identifier, resource result_entry_identifier )

Retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

See Also

ldap_get_entries()

Prev | Home | Next
ldap_next_attribute | Up | ldap_next_reference


ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_next_reference -- Get next reference

Description

resource ldap_next_reference ( resource link, resource entry )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_next_entry | Up | ldap_parse_reference


ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_reference -- Extract information from reference entry

Description

bool ldap_parse_reference ( resource link, resource entry, array &referrals )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_next_reference | Up | ldap_parse_result


ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_result -- Extract information from result

Description

bool ldap_parse_result ( resource link, resource result, int &errcode [, string &matcheddn [, string &errmsg [, array &referrals]]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_parse_reference | Up | ldap_read


ldap_read

(PHP 3, PHP 4, PHP 5)

ldap_read -- Read an entry

Description

resource ldap_read ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of objectClass=*. If you know which entry types are used on the directory server, you might use an appropriate filter such as objectClass=inetOrgPerson.

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.

  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.

  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.

  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Return Values

Returns a search result identifier or FALSE on error.

ChangeLog

Version | Description
4.0.5 | Parallel searches support was added. See ldap_search() for details.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Prev | Home | Next
ldap_parse_result | Up | ldap_rename


ldap_rename

(PHP 4 >= 4.0.5, PHP 5)

ldap_rename -- Modify the name of an entry

Description

bool ldap_rename ( resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn )

The entry specified by dn is renamed/moved.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

newrdn

The new RDN.

newparent

The new parent/superior entry.

deleteoldrdn

If TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

Prev | Home | Next
ldap_read | Up | ldap_sasl_bind


ldap_sasl_bind

(PHP 5)

ldap_sasl_bind -- Bind to LDAP directory using SASL

Description

bool ldap_sasl_bind ( resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authz_id [, string props]]]]]] )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Requirement: ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.

Prev | Home | Next
ldap_rename | Up | ldap_search


ldap_search

(PHP 3, PHP 4, PHP 5)

ldap_search -- Search LDAP tree

Description

resource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the Netscape Directory SDK for full information on filters).

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note: This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.

  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.

  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.

  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Return Values

Returns a search result identifier or FALSE on error.

ChangeLog

Version | Description
4.0.5 | Parallel searches support was added.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Examples

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

Example 1. LDAP search

&#60;?php
// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?&#62;

Prev | Home | Next
ldap_sasl_bind | Up | ldap_set_option


ldap_set_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_set_option -- Set the value of the given option

Description

bool ldap_set_option ( resource link_identifier, int option, mixed newval )

Sets the value of the specified option to be newval.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array

LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See draft-ietf-ldapext-ldap-c-api-xx.txt for details. See also the second example below.

newval

The new value for the specified option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Set protocol version

&#60;?php
// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    echo "Using LDAPv3";
} else {
    echo "Failed to set protocol version to 3";
}
?&#62;

Example 2. Set server controls

&#60;?php
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" =&#62; "1.2.752.58.10.1", "iscritical" =&#62; true);
// iscritical defaults to FALSE
$ctrl2 = array("oid" =&#62; "1.2.752.58.1.10", "value" =&#62; "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) {
    echo "Failed to set server controls";
}
?&#62;

Notes

Note: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

ldap_get_option()

Prev | Home | Next
ldap_search | Up | ldap_set_rebind_proc


ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5)

ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing

Description

bool ldap_set_rebind_proc ( resource link, callback callback )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_set_option | Up | ldap_sort


ldap_sort

(PHP 4 >= 4.2.0, PHP 5)

ldap_sort -- Sort LDAP result entries

Description

bool ldap_sort ( resource link, resource result, string sortfilter )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_set_rebind_proc | Up | ldap_start_tls


ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5)

ldap_start_tls -- Start TLS

Description

bool ldap_start_tls ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_sort | Up | ldap_t61_to_8859


ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5)

ldap_t61_to_8859 -- Translate t61 characters to 8859 characters

Description

string ldap_t61_to_8859 ( string value )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ldap_start_tls | Up | ldap_unbind


ldap_unbind

(PHP 3, PHP 4, PHP 5)

ldap_unbind -- Unbind from LDAP directory

Description

bool ldap_unbind ( resource link_identifier )

Unbinds from the LDAP directory.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ldap_t61_to_8859 | Up | libxml Functions


libxml Functions

PHP Manual
Prev Next

LXXIV. libxml Functions

Introduction

These functions/constants are available since PHP 5.1.0 and if you have compiled one of the extensions based on libxml, like DOM, SimpleXML and XSLT.

Requirements

This extension requires libxml >= 2.6.0.

Predefined Classes

LibXMLError

Properties

  • code - the error's code

  • column - the column where the error occurred. Please note that this property isn't entirely implemented in libxml and therefore 0 is often returned.

  • file - the filename, or empty if the XML was loaded from a string

  • level - the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

  • line - the line where the error occurred

  • message - the error message

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.

LIBXML_COMPACT (integer)

Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Note: Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (integer)

Default DTD attributes

LIBXML_DTDLOAD (integer)

Load the external subset

LIBXML_DTDVALID (integer)

Validate with the DTD

LIBXML_NOBLANKS (integer)

Remove blank nodes

LIBXML_NOCDATA (integer)

Merge CDATA as text nodes

LIBXML_NOEMPTYTAG (integer)

Expand empty tags (e.g. <br/> to <br></br>)

Note: This option is currently just available in the DOMDocument->save() and DOMDocument->saveXML() functions.

LIBXML_NOENT (integer)

Substitute entities

LIBXML_NOERROR (integer)

Suppress error reports

LIBXML_NONET (integer)

Disable network access when loading documents

LIBXML_NOWARNING (integer)

Suppress warning reports

LIBXML_NOXMLDECL (integer)

Drop the XML declaration when saving a document

Note: Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)

Remove redundant namespaces declarations

LIBXML_XINCLUDE (integer)

Implement XInclude substitution

LIBXML_ERR_ERROR (integer)

A recoverable error

LIBXML_ERR_FATAL (integer)

A fatal error

LIBXML_ERR_NONE (integer)

No errors

LIBXML_ERR_WARNING (integer)

A simple warning

LIBXML_VERSION (integer)

libxml version like 20605 or 20617

LIBXML_DOTTED_VERSION (string)

libxml version like 2.6.5 or 2.6.17

Table of Contents
libxml_clear_errors -- Clear libxml error buffer
libxml_get_errors -- Retrieve array of errors
libxml_get_last_error -- Retrieve last error from libxml
libxml_set_streams_context -- Set the streams context for the next libxml document load or write
libxml_use_internal_errors -- Disable libxml errors and allow user to fetch error information as needed

Prev | Home | Next
ldap_unbind | Up | libxml_clear_errors


libxml_clear_errors

(PHP 5 >= 5.1.0RC1)

libxml_clear_errors -- Clear libxml error buffer

Description

void libxml_clear_errors ( void )

libxml_clear_errors() clears the libxml error buffer.

Return Values

No value is returned.

See Also

libxml_get_errors()
libxml_get_last_error()

Prev | Home | Next
libxml Functions | Up | libxml_get_errors


libxml_get_errors

(PHP 5 >= 5.1.0RC1)

libxml_get_errors -- Retrieve array of errors

Description

array libxml_get_errors ( void )

Retrieve array of errors.

Return Values

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Examples

Example 1. A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

&#60;?php

libxml_use_internal_errors(true);

$xmlstr = &#60;&#60;&#60; XML
&#60;?xml version='1.0' standalone='yes'?&#62;
&#60;movies&#62;
 &#60;movie&#62;
  &#60;titles&#62;PHP: Behind the Parser&#60;/title&#62;
 &#60;/movie&#62;
&#60;/movies&#62;
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
    $return  = $xml[$error-&#62;line - 1] . "\n";
    $return .= str_repeat('-', $error-&#62;column) . "^\n";

    switch ($error-&#62;level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error-&#62;code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error-&#62;code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error-&#62;code: ";
            break;
    }

    $return .= trim($error-&#62;message) .
               "\n  Line: $error-&#62;line" .
               "\n  Column: $error-&#62;column";

    if ($error-&#62;file) {
        $return .= "\n  File: $error-&#62;file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?&#62;

The above example will output:

<titles>PHP: Behind the Parser</title>
^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 0

--------------------------------------------

See Also

libxml_get_last_error()
libxml_clear_errors()

Prev | Home | Next
libxml_clear_errors | Up | libxml_get_last_error


libxml_get_last_error

(PHP 5 >= 5.1.0RC1)

libxml_get_last_error -- Retrieve last error from libxml

Description

LibXMLError libxml_get_last_error ( void )

Retrieve last error from libxml.

Return Values

Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.

See Also

libxml_get_errors()
libxml_clear_errors()

Prev | Home | Next
libxml_get_errors | Up | libxml_set_streams_context


libxml_set_streams_context

(PHP 5)

libxml_set_streams_context -- Set the streams context for the next libxml document load or write

Description

void libxml_set_streams_context ( resource streams_context )

Sets the streams context for the next libxml document load or write.

Parameters

streams_context

The stream context resource (created with stream_context_create())

Return Values

No value is returned.

Examples

Example 1. A libxml_set_streams_context() example

&#60;?php

$opts = array(
    'http' =&#62; array(
        'user_agent' =&#62; 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?&#62;

See Also

stream_context_create()

Prev | Home | Next
libxml_get_last_error | Up | libxml_use_internal_errors


libxml_use_internal_errors

(PHP 5 >= 5.1.0RC1)

libxml_use_internal_errors -- Disable libxml errors and allow user to fetch error information as needed

Description

bool libxml_use_internal_errors ( [bool use_errors] )

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

Parameters

use_errors

Whether to enable user error handling. Defaults to FALSE.

Return Values

This function returns the previous value of use_errors.

Examples

Example 1. A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

&#60;?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

$doc = DOMDocument::load('file.xml');

if (!$doc) {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?&#62;

The above example will output:

bool(false)

See Also

libxml_clear_errors()
libxml_get_errors()

Prev | Home | Next
libxml_set_streams_context | Up | Lotus Notes Functions


LZF Functions

PHP Manual
Prev Next

LXXVI. LZF Functions

Introduction

LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation.

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/lzf.

In order to use these functions you must compile PHP with lzf support by using the --with-lzf[=DIR] configure option. You may also pass --enable-lzf-better-compression to optimize LZF for space rather then speed.

Windows users will enable php_lzf.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Table of Contents
lzf_compress -- LZF compression
lzf_decompress -- LZF decompression
lzf_optimized_for -- Determines what LZF extension was optimized for

Prev | Home | Next
notes_version | Up | lzf_compress


lzf_compress

(PECL)

lzf_compress -- LZF compression

Description

string lzf_compress ( string data )

lzf_compress() compresses the given data.

Parameters

data

The string to compress.

Return Values

Returns the compressed data or FALSE if an error occurred.

See Also

lzf_decompress()

Prev | Home | Next
LZF Functions | Up | lzf_decompress


lzf_decompress

(PECL)

lzf_decompress -- LZF decompression

Description

string lzf_decompress ( string data )

lzf_compress() decompresses the given data.

Parameters

data

The compressed string.

Return Values

Returns the decompressed data or FALSE if an error occurred.

See Also

lzf_compress()

Prev | Home | Next
lzf_compress | Up | lzf_optimized_for


lzf_optimized_for

(PECL)

lzf_optimized_for -- Determines what LZF extension was optimized for

Description

int lzf_optimized_for ( void )

Determines for what the LZF extension was optimised.

Return Values

Returns 1 if LZF was optimized for speed, 0 for compression.

Prev | Home | Next
lzf_decompress | Up | Mail Functions


Mail Functions

PHP Manual
Prev Next

LXXVII. Mail Functions

Introduction

The mail() function allows you to send mail.

Requirements

For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

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. Mail configuration options

Name | Default | Changeable | Changelog
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Available since PHP 4.3.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

SMTP string

Used under Windows only: host name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

smtp_port int

Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25. Only available since PHP 4.3.0.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows. This directive also sets the "Return-Path:" header.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.

qmail-inject does not require any option to process mail correctly.

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
ezmlm_hash -- Calculate the hash value needed by EZMLM
mail -- Send mail

Prev | Home | Next
lzf_optimized_for | Up | ezmlm_hash


ezmlm_hash

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.2, PHP 5)

ezmlm_hash -- Calculate the hash value needed by EZMLM

Description

int ezmlm_hash ( string addr )

ezmlm_hash() calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database.

Parameters

addr

The email address that's being hashed.

Return Values

The hash value of addr.

Examples

Example 1. Calculating the hash and subscribing a user

&#60;?php

$user = "joecool@example.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db-&#62;query($query); // using PHPLIB db interface

?&#62;

Prev | Home | Next
Mail Functions | Up | mail


mail

(PHP 3, PHP 4, PHP 5)

mail -- Send mail

Description

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )

Sends an email.

Parameters

to

Receiver, or receivers of the mail.

The formatting of this string must comply with RFC 2822. Some examples are:

user@example.com
user@example.com, anotheruser@example.com
User <user@example.com>
User <user@example.com>, Another User <anotheruser@example.com>

subject

Subject of the email to be sent.

Caution

This must not contain any newline characters, or the mail may not be sent properly.

message

Message to be sent.

Each line should be separated with a LF (\n). Lines should not be larger than 70 characters.

Caution

(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

&#60;?php
$text = str_replace("\n.", "\n..", $text);
?&#62;

additional_headers (optional)

String to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n).

Note: When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.

Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path under Windows.

Note: If messages are not received, try using a LF (\n) only. Some poor quality Unix mail transfer agents replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with RFC 2822.

additional_parameters (optional)

The additional_parameters parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

Return Values

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

ChangeLog

Version | Description
4.3.0 (Windows only) | All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. (As custom headers are not interpreted by the MTA in the first place, but are parsed by PHP, PHP < 4.3 only supported the Cc header element and was case-sensitive).
4.2.3 | The additional_parameters parameter is disabled in safe_mode and the mail() function will expose a warning message and return FALSE when used.
4.0.5 | The additional_parameters parameter was added.

Examples

Example 1. Sending mail.

Using mail() to send a simple email:

&#60;?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);

// Send
mail('caffinated@example.com', 'My Subject', $message);
?&#62;

Example 2. Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

&#60;?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?&#62;

Example 3. Sending mail with an additional command line parameter.

The additional_parameters parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path.

&#60;?php
mail('nobody@example.com', 'the subject', 'the message', null,
   '-fwebmaster@example.com');
?&#62;

Example 4. Sending HTML email

It is also possible to send HTML email with mail().

&#60;?php
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
&#60;html&#62;
&#60;head&#62;
  &#60;title&#62;Birthday Reminders for August&#60;/title&#62;
&#60;/head&#62;
&#60;body&#62;
  &#60;p&#62;Here are the birthdays upcoming in August!&#60;/p&#62;
  &#60;table&#62;
    &#60;tr&#62;
      &#60;th&#62;Person&#60;/th&#62;&#60;th&#62;Day&#60;/th&#62;&#60;th&#62;Month&#60;/th&#62;&#60;th&#62;Year&#60;/th&#62;
    &#60;/tr&#62;
    &#60;tr&#62;
      &#60;td&#62;Joe&#60;/td&#62;&#60;td&#62;3rd&#60;/td&#62;&#60;td&#62;August&#60;/td&#62;&#60;td&#62;1970&#60;/td&#62;
    &#60;/tr&#62;
    &#60;tr&#62;
      &#60;td&#62;Sally&#60;/td&#62;&#60;td&#62;17th&#60;/td&#62;&#60;td&#62;August&#60;/td&#62;&#60;td&#62;1973&#60;/td&#62;
    &#60;/tr&#62;
  &#60;/table&#62;
&#60;/body&#62;
&#60;/html&#62;
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary &#60;mary@example.com&#62;, Kelly &#60;kelly@example.com&#62;' . "\r\n";
$headers .= 'From: Birthday Reminder &#60;birthday@example.com&#62;' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?&#62;

Note: If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR package PEAR::Mail_Mime.

Notes

Note: The Windows implementation of mail() differs in many ways from the Unix implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on a network socket (which can either on the localhost or a remote machine).

Second, the custom headers like From:, Cc:, Bcc: and Date: are not interpreted by the MTA in the first place, but are parsed by PHP.

As such, the to parameter should not be an address in the form of "Something <someone@example.com>". The mail command may not parse this properly while talking with the MTA.

Note: Email with attachments and special types of content (e.g. HTML) can be sent using this function. This is accomplished via MIME-encoding - for more information, see this Zend article or the PEAR Mime Classes.

Note: It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

For the sending of large amounts of email, see the PEAR::Mail, and PEAR::Mail_Queue packages.

Note: The following RFCs may be useful: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048, RFC 2049, and RFC 2822.

See Also

imap_mail()
PEAR::Mail
PEAR::Mail_Mime

Prev | Home | Next
ezmlm_hash | Up | mailparse Functions


mailparse Functions

PHP Manual
Prev Next

LXXVIII. mailparse 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.

This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 4.2.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/mailparse.

In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.

Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Table of Contents
mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able
mailparse_msg_create -- Returns a handle that can be used to parse a message
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding
mailparse_msg_extract_part -- Extracts/decodes a message section
mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()
mailparse_msg_get_part_data -- Returns an associative array of info about the message
mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message
mailparse_msg_parse_file -- Parse file and return a resource representing the structure
mailparse_msg_parse -- Incrementally parse data into buffer
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that data
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfp
mailparse_uudecode_all -- Scans the data from fp and extract each embedded uuencoded file

Prev | Home | Next
mail | Up | mailparse_determine_best_xfer_encoding


mailparse_determine_best_xfer_encoding

(4.1.0 - 4.1.2 only, PECL)

mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able

Description

string mailparse_determine_best_xfer_encoding ( resource fp )

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.

Prev | Home | Next
mailparse Functions | Up | mailparse_msg_create


mailparse_msg_create

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

resource mailparse_msg_create ( void )

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.

Prev | Home | Next
mailparse_determine_best_xfer_encoding | Up | mailparse_msg_extract_part_file


mailparse_msg_extract_part_file

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, callback callbackfunc] )

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.

Prev | Home | Next
mailparse_msg_create | Up | mailparse_msg_extract_part


mailparse_msg_extract_part

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_extract_part -- Extracts/decodes a message section

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, callback callbackfunc] )

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.

If callbackfunc is not specified, the contents will be sent to "stdout".

Prev | Home | Next
mailparse_msg_extract_part_file | Up | mailparse_msg_free


mailparse_msg_free

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()

Description

bool mailparse_msg_free ( resource rfc2045buf )

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.

Prev | Home | Next
mailparse_msg_extract_part | Up | mailparse_msg_get_part_data


mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_part_data -- Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource rfc2045 )

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.

Prev | Home | Next
mailparse_msg_free | Up | mailparse_msg_get_part


mailparse_msg_get_part

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

resource mailparse_msg_get_part ( resource rfc2045, string mimesection )

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.

Prev | Home | Next
mailparse_msg_get_part_data | Up | mailparse_msg_get_structure


mailparse_msg_get_structure

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource rfc2045 )

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.

Prev | Home | Next
mailparse_msg_get_part | Up | mailparse_msg_parse_file


mailparse_msg_parse_file

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_parse_file -- Parse file and return a resource representing the structure

Description

resource mailparse_msg_parse_file ( string filename )

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.

Prev | Home | Next
mailparse_msg_get_structure | Up | mailparse_msg_parse


mailparse_msg_parse

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

bool mailparse_msg_parse ( resource rfc2045buf, string data )

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.

Prev | Home | Next
mailparse_msg_parse_file | Up | mailparse_rfc822_parse_addresses


mailparse_rfc822_parse_addresses

(4.1.0 - 4.1.2 only, PECL)

mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that data

Description

array mailparse_rfc822_parse_addresses ( string addresses )

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.

Prev | Home | Next
mailparse_msg_parse | Up | mailparse_stream_encode


mailparse_stream_encode

(4.1.0 - 4.1.2 only, PECL)

mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource sourcefp, resource destfp, string encoding )

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.

Prev | Home | Next
mailparse_rfc822_parse_addresses | Up | mailparse_uudecode_all


mailparse_uudecode_all

(PECL)

mailparse_uudecode_all -- Scans the data from fp and extract each embedded uuencoded file

Description

array mailparse_uudecode_all ( resource fp )

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.

Returns an array listing filename information.

Prev | Home | Next
mailparse_stream_encode | Up | Mathematical Functions


Mathematical Functions

PHP Manual
Prev Next

LXXIX. Mathematical Functions

Introduction

These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.

See also the manual page on arithmetic operators.

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.

Table 1. Math constants

Constant | Value | Description
M_PI | 3.14159265358979323846 | Pi
M_E | 2.7182818284590452354 | e
M_LOG2E | 1.4426950408889634074 | log_2 e
M_LOG10E | 0.43429448190325182765 | log_10 e
M_LN2 | 0.69314718055994530942 | log_e 2
M_LN10 | 2.30258509299404568402 | log_e 10
M_PI_2 | 1.57079632679489661923 | pi/2
M_PI_4 | 0.78539816339744830962 | pi/4
M_1_PI | 0.31830988618379067154 | 1/pi
M_2_PI | 0.63661977236758134308 | 2/pi
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) [5.2.0]
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi)
M_SQRT2 | 1.41421356237309504880 | sqrt(2)
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [5.2.0]
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2)
M_LNPI | 1.14472988584940017414 | log_e(pi) [5.2.0]
M_EULER | 0.57721566490153286061 | Euler constant [5.2.0]
Only M_PI is available in PHP versions up to and including PHP 4.0.0. All other constants are available starting with PHP 4.0.0. Constants labeled [5.2.0] were added in PHP 5.2.0.

Table of Contents
abs -- Absolute value
acos -- Arc cosine
acosh -- Inverse hyperbolic cosine
asin -- Arc sine
asinh -- Inverse hyperbolic sine
atan2 -- Arc tangent of two variables
atan -- Arc tangent
atanh -- Inverse hyperbolic tangent
base_convert -- Convert a number between arbitrary bases
bindec -- Binary to decimal
ceil -- Round fractions up
cos -- Cosine
cosh -- Hyperbolic cosine
decbin -- Decimal to binary
dechex -- Decimal to hexadecimal
decoct -- Decimal to octal
deg2rad -- Converts the number in degrees to the radian equivalent
exp -- Calculates the exponent of e
expm1 -- Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
floor -- Round fractions down
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- Show largest possible random value
hexdec -- Hexadecimal to decimal
hypot -- Calculate the length of the hypotenuse of a right-angle triangle
is_finite -- Finds whether a value is a legal finite number
is_infinite -- Finds whether a value is infinite
is_nan -- Finds whether a value is not a number
lcg_value -- Combined linear congruential generator
log10 -- Base-10 logarithm
log1p -- Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
log -- Natural logarithm
max -- Find highest value
min -- Find lowest value
mt_getrandmax -- Show largest possible random value
mt_rand -- Generate a better random value
mt_srand -- Seed the better random number generator
octdec -- Octal to decimal
pi -- Get value of pi
pow -- Exponential expression
rad2deg -- Converts the radian number to the equivalent number in degrees
rand -- Generate a random integer
round -- Rounds a float
sin -- Sine
sinh -- Hyperbolic sine
sqrt -- Square root
srand -- Seed the random number generator
tan -- Tangent
tanh -- Hyperbolic tangent

Prev | Home | Next
mailparse_uudecode_all | Up | abs


abs

(PHP 3, PHP 4, PHP 5)

abs -- Absolute value

Description

number abs ( mixed number )

Returns the absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Example 1. abs() example

&#60;?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?&#62;

Prev | Home | Next
Mathematical Functions | Up | acos


acos

(PHP 3, PHP 4, PHP 5)

acos -- Arc cosine

Description

float acos ( float arg )

Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range.

See also:
acosh(),
asin(), and
atan().

Prev | Home | Next
abs | Up | acosh


acosh

(PHP 4 >= 4.1.0, PHP 5)

acosh -- Inverse hyperbolic cosine

Description

float acosh ( float arg )

Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.

Note: This function is not implemented on Windows platforms.

See also:
acos(),
asinh(), and
atanh().

Prev | Home | Next
acos | Up | asin


asin

(PHP 3, PHP 4, PHP 5)

asin -- Arc sine

Description

float asin ( float arg )

Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range.

See also:
asinh(),
acos(), and
atan().

Prev | Home | Next
acosh | Up | asinh


asinh

(PHP 4 >= 4.1.0, PHP 5)

asinh -- Inverse hyperbolic sine

Description

float asinh ( float arg )

Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.

Note: This function is not implemented on Windows platforms.

See also:
asin(),
acosh(), and
atanh().

Prev | Home | Next
asin | Up | atan2


atan2

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

atan2 -- Arc tangent of two variables

Description

float atan2 ( float y, float x )

This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

See also acos() and atan().

Prev | Home | Next
asinh | Up | atan


atan

(PHP 3, PHP 4, PHP 5)

atan -- Arc tangent

Description

float atan ( float arg )

Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range.

See also:
atanh(),
asin(), and
acos().

Prev | Home | Next
atan2 | Up | atanh


atanh

(PHP 4 >= 4.1.0, PHP 5)

atanh -- Inverse hyperbolic tangent

Description

float atanh ( float arg )

Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.

Note: This function is not implemented on Windows platforms.

See also:
atan(),
asinh(), and
acosh().

Prev | Home | Next
atan | Up | base_convert


base_convert

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

base_convert -- Convert a number between arbitrary bases

Description

string base_convert ( string number, int frombase, int tobase )

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.

Example 1. base_convert() example

&#60;?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?&#62;

Outputs:

101000110111001100110100

Warning

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

See also: intval().

Prev | Home | Next
atanh | Up | bindec


bindec

(PHP 3, PHP 4, PHP 5)

bindec -- Binary to decimal

Description

number bindec ( string binary_string )

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer. The largest number that can be converted is 31 bits of 1's or 2147483647 in decimal. As of PHP 4.1.0, this function can also convert larger numbers. It returns float in that case.

Example 1. bindec() example

&#60;?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?&#62;

The above example will output:

51
51
7

See also decbin(),
octdec(),
hexdec() and
base_convert().

Prev | Home | Next
base_convert | Up | ceil


ceil

(PHP 3, PHP 4, PHP 5)

ceil -- Round fractions up

Description

float ceil ( float value )

Returns the next highest integer value by rounding up value if necessary. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

Example 1. ceil() example

&#60;?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?&#62;

See also floor() and round().

Prev | Home | Next
bindec | Up | cos


cos

(PHP 3, PHP 4, PHP 5)

cos -- Cosine

Description

float cos ( float arg )

cos() returns the cosine of the arg parameter. The arg parameter is in radians.

Example 1. cos() example

&#60;?php

echo cos(M_PI); // -1

?&#62;

See also:
acos(),
sin(),
tan(), and
deg2rad().

Prev | Home | Next
ceil | Up | cosh


cosh

(PHP 4 >= 4.1.0, PHP 5)

cosh -- Hyperbolic cosine

Description

float cosh ( float arg )

Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.

See also:
cos(),
acosh(),
sin(), and
tan().

Prev | Home | Next
cos | Up | decbin


decbin

(PHP 3, PHP 4, PHP 5)

decbin -- Decimal to binary

Description

string decbin ( int number )

Returns a string containing a binary representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to a string of 32 1's.

Example 1. decbin() example

&#60;?php
echo decbin(12) . "\n";
echo decbin(26);
?&#62;

The above example will output:

1100
11010

See also bindec(),
decoct(),
dechex() and
base_convert().

Prev | Home | Next
cosh | Up | dechex


dechex

(PHP 3, PHP 4, PHP 5)

dechex -- Decimal to hexadecimal

Description

string dechex ( int number )

Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to "ffffffff".

Example 1. dechex() example

&#60;?php
echo dechex(10) . "\n";
echo dechex(47);
?&#62;

The above example will output:

a
2f

See also hexdec(),
decbin(),
decoct() and
base_convert().

Prev | Home | Next
decbin | Up | decoct


decoct

(PHP 3, PHP 4, PHP 5)

decoct -- Decimal to octal

Description

string decoct ( int number )

Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to "37777777777".

Example 1. decoct() example

&#60;?php
echo decoct(15) . "\n";
echo decoct(264);
?&#62;

The above example will output:

17
410

See also octdec(),
decbin(),
dechex() and
base_convert().

Prev | Home | Next
dechex | Up | deg2rad


deg2rad

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

deg2rad -- Converts the number in degrees to the radian equivalent

Description

float deg2rad ( float number )

This function converts number from degrees to the radian equivalent.

Example 1. deg2rad() example

&#60;?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?&#62;

See also rad2deg().

Prev | Home | Next
decoct | Up | exp


exp

(PHP 3, PHP 4, PHP 5)

exp -- Calculates the exponent of e

Description

float exp ( float arg )

Returns e raised to the power of arg.

Note: 'e' is the base of the natural system of logarithms, or approximately 2.718282.

Example 1. exp() example

&#60;?php
echo exp(12) . "\n";
echo exp(5.7);
?&#62;

The above example will output:

1.6275E+005
298.87

See also log() and pow().

Prev | Home | Next
deg2rad | Up | expm1


expm1

(PHP 4 >= 4.1.0, PHP 5)

expm1 -- Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

Description

float expm1 ( float number )

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.

expm1() returns the equivalent to 'exp(number) - 1' computed in a way that is accurate even if the value of number is near zero, a case where 'exp (number) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

Note: This function is not implemented on Windows platforms.

See also log1p() and exp().

Prev | Home | Next
exp | Up | floor


floor

(PHP 3, PHP 4, PHP 5)

floor -- Round fractions down

Description

float floor ( float value )

Returns the next lowest integer value by rounding down value if necessary. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

Example 1. floor() example

&#60;?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?&#62;

See also ceil() and round().

Prev | Home | Next
expm1 | Up | fmod


fmod

(PHP 4 >= 4.2.0, PHP 5)

fmod -- Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float x, float y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Example 1. Using fmod()

&#60;?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?&#62;

Prev | Home | Next
floor | Up | getrandmax


getrandmax

(PHP 3, PHP 4, PHP 5)

getrandmax -- Show largest possible random value

Description

int getrandmax ( void )

Returns the maximum value that can be returned by a call to rand().

See also rand(), srand() and mt_getrandmax().

Prev | Home | Next
fmod | Up | hexdec


hexdec

(PHP 3, PHP 4, PHP 5)

hexdec -- Hexadecimal to decimal

Description

number hexdec ( string hex_string )

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number. The largest number that can be converted is 7fffffff or 2147483647 in decimal. As of PHP 4.1.0, this function can also convert larger numbers. It returns float in that case.

hexdec() will ignore any non-hexadecimal characters it encounters.

Example 1. hexdec() example

&#60;?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?&#62;

See also dechex(),
bindec(),
octdec() and
base_convert().

Prev | Home | Next
getrandmax | Up | hypot


hypot

(PHP 4 >= 4.1.0, PHP 5)

hypot -- Calculate the length of the hypotenuse of a right-angle triangle

Description

float hypot ( float x, float y )

hypot() returns the length of the hypotenuse of a right-angle triangle with sides of length x and y, or the distance of the point (x, y) from the origin. This is equivalent to sqrt(x*x + y*y).

Prev | Home | Next
hexdec | Up | is_finite


is_finite

(PHP 4 >= 4.2.0, PHP 5)

is_finite -- Finds whether a value is a legal finite number

Description

bool is_finite ( float val )

Returns TRUE if val is a legal finite number within the allowed range for a PHP float on this platform.

See also is_infinite() and is_nan().

Prev | Home | Next
hypot | Up | is_infinite


is_infinite

(PHP 4 >= 4.2.0, PHP 5)

is_infinite -- Finds whether a value is infinite

Description

bool is_infinite ( float val )

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

See also is_finite() and is_nan().

Prev | Home | Next
is_finite | Up | is_nan


is_nan

(PHP 4 >= 4.2.0, PHP 5)

is_nan -- Finds whether a value is not a number

Description

bool is_nan ( float val )

Returns TRUE if val is 'not a number', like the result of acos(1.01).

See also is_finite() and is_infinite().

Prev | Home | Next
is_infinite | Up | lcg_value


lcg_value

(PHP 4, PHP 5)

lcg_value -- Combined linear congruential generator

Description

float lcg_value ( void )

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.

Prev | Home | Next
is_nan | Up | log10


log10

(PHP 3, PHP 4, PHP 5)

log10 -- Base-10 logarithm

Description

float log10 ( float arg )

Returns the base-10 logarithm of arg.

See Also: log()

Prev | Home | Next
lcg_value | Up | log1p


log1p

(PHP 4 >= 4.1.0, PHP 5)

log1p -- Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

Description

float log1p ( float number )

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.

log1p() returns log(1 + number) computed in a way that is accurante even when the value of number is close to zero.

Note: This function is not implemented on Windows platforms.

See also expm1() and log().

Prev | Home | Next
log10 | Up | log


log

(PHP 3, PHP 4, PHP 5)

log -- Natural logarithm

Description

float log ( float arg [, float base] )

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

Note: The base parameter became available with PHP 4.3.0.

As always you can calculate the logarithm in base b of a number n, but using the mathematical identity: logb(n) = log(n)/log(b), where log is the neperian (or natural) logarithm.

See also exp().

Prev | Home | Next
log1p | Up | max


max

(PHP 3, PHP 4, PHP 5)

max -- Find highest value

Description

mixed max ( number arg1, number arg2 [, number ...] )

mixed max ( array numbers )

max() returns the numerically highest of the parameter values.

If the first and only parameter is an array, max() returns the highest value in that array. If the first parameter is an integer, string or float, you need at least two parameters and max() returns the biggest of these values. You can compare an unlimited number of values.

Note: PHP will evaluate a non-numeric string as 0, but still return the string if it's seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.

Example 1. Example uses of max()

&#60;?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello
echo max(-1, 'hello');    // hello

// With multiple arrays, max compares from left to right
// so in our example: 2 == 2, but 4 &#60; 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// If both an array and non-array are given, the array
// is always returned as it's seen as the largest
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
?&#62;

See also min() and count().

Prev | Home | Next
log | Up | min


min

(PHP 3, PHP 4, PHP 5)

min -- Find lowest value

Description

mixed min ( number arg1, number arg2 [, number ...] )

mixed min ( array numbers )

min() returns the numerically lowest of the parameter values.

If the first and only parameter is an array, min() returns the lowest value in that array. If the first parameter is an integer, string or float, you need at least two parameters and min() returns the smallest of these values. You can compare an unlimited number of values.

Note: PHP will evaluate a non-numeric string as 0, but still return the string if it's seen as the numerically lowest value. If multiple arguments evaluate to 0, min() will return the lowest alphanumerical string value if any strings are given, else a numeric 0 is returned.

Example 1. Example uses of min()

&#60;?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
echo min('hello', -1);    // -1

// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 &#60; 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// If both an array and non-array are given, the array
// is never returned as it's considered the largest
$val = min('string', array(2, 5, 7), 42);   // string
?&#62;

See also max() and count().

Prev | Home | Next
max | Up | mt_getrandmax


mt_getrandmax

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_getrandmax -- Show largest possible random value

Description

int mt_getrandmax ( void )

Returns the maximum value that can be returned by a call to mt_rand().

See also:
mt_rand(),
mt_srand(), and
getrandmax().

Prev | Home | Next
min | Up | mt_rand


mt_rand

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_rand -- Generate a better random value

Description

int mt_rand ( [int min, int max] )

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15).

Example 1. mt_rand() example

&#60;?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?&#62;

The above example will output something similar to:

1604716014
1478613278
6

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.

Note: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short example should be mt_rand (5, 11) to get a random number between 5 and 15.

See also:
mt_srand(),
mt_getrandmax(), and
rand().

Prev | Home | Next
mt_getrandmax | Up | mt_srand


mt_srand

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_srand -- Seed the better random number generator

Description

void mt_srand ( [int seed] )

Seeds the random number generator with seed. Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.

Example 1. mt_srand() example

&#60;?php
// seed with microseconds
function make_seed()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?&#62;

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:
mt_rand(),
mt_getrandmax(), and
srand().

Prev | Home | Next
mt_rand | Up | octdec


octdec

(PHP 3, PHP 4, PHP 5)

octdec -- Octal to decimal

Description

number octdec ( string octal_string )

Returns the decimal equivalent of the octal number represented by the octal_string argument. The largest number that can be converted is 17777777777 or 2147483647 in decimal. As of PHP 4.1.0, this function can also convert larger numbers. It returns float in that case.

Example 1. octdec() example

&#60;?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?&#62;

The above example will output:

63
45

See also:
decoct(),
bindec(),
hexdec(), and
base_convert().

Prev | Home | Next
mt_srand | Up | pi


pi

(PHP 3, PHP 4, PHP 5)

pi -- Get value of pi

Description

float pi ( void )

Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().

Example 1. pi() example

&#60;?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?&#62;

Prev | Home | Next
octdec | Up | pow


pow

(PHP 3, PHP 4, PHP 5)

pow -- Exponential expression

Description

number pow ( number base, number exp )

Returns base raised to the power of exp. If possible, this function will return an integer.

If the power cannot be computed, a warning will be issued, and pow() will return FALSE. Since PHP 4.2.0 pow() doesn't issue any warning.

Note: PHP cannot handle negative bases.

Example 1. Some examples of pow()

&#60;?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // error

?&#62;

Warning

In PHP 4.0.6 and earlier pow() always returned a float, and did not issue warnings.

See also:
exp(),
sqrt(),
bcpow(), and
gmp_pow(),

Prev | Home | Next
pi | Up | rad2deg


rad2deg

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

rad2deg -- Converts the radian number to the equivalent number in degrees

Description

float rad2deg ( float number )

This function converts number from radian to degrees.

Example 1. rad2deg() example

&#60;?php

echo rad2deg(M_PI_4); // 45

?&#62;

See also deg2rad().

Prev | Home | Next
pow | Up | rand


rand

(PHP 3, PHP 4, PHP 5)

rand -- Generate a random integer

Description

int rand ( [int min, int max] )

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use rand (5, 15).

Example 1. rand() example

&#60;?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?&#62;

The above example will output something similar to:

7771
22264
11

Note: On some platforms (such as Windows) RAND_MAX is only 32768. If you require a range larger than 32768, specifying min and max will allow you to create a range larger than RAND_MAX, or consider using mt_rand() instead.

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.

Note: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short example should be rand (5, 11) to get a random number between 5 and 15.

See also:
srand(),
getrandmax(), and
mt_rand().

Prev | Home | Next
rad2deg | Up | round


round

(PHP 3, PHP 4, PHP 5)

round -- Rounds a float

Description

float round ( float val [, int precision] )

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Example 1. round() examples

&#60;?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?&#62;

Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

Note: The precision parameter was introduced in PHP 4.

See also:
ceil(),
floor(), and
number_format().

Prev | Home | Next
rand | Up | sin


sin

(PHP 3, PHP 4, PHP 5)

sin -- Sine

Description

float sin ( float arg )

sin() returns the sine of the arg parameter. The arg parameter is in radians.

Example 1. sin() example

&#60;?php

// Precision depends on your precision directive
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?&#62;

See also:
asin(),
cos(),
tan(), and
deg2rad().

Prev | Home | Next
round | Up | sinh


sinh

(PHP 4 >= 4.1.0, PHP 5)

sinh -- Hyperbolic sine

Description

float sinh ( float arg )

Returns the hyperbolic sine of arg, defined as (exp(arg) - exp(-arg))/2.

See also:
sin(),
asinh(),
cos(), and
tan().

Prev | Home | Next
sin | Up | sqrt


sqrt

(PHP 3, PHP 4, PHP 5)

sqrt -- Square root

Description

float sqrt ( float arg )

Returns the square root of arg.

Example 1. sqrt() example

&#60;?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?&#62;

See also pow().

Prev | Home | Next
sinh | Up | srand


srand

(PHP 3, PHP 4, PHP 5)

srand -- Seed the random number generator

Description

void srand ( [int seed] )

Seeds the random number generator with seed. Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.

Example 1. srand() example

&#60;?php
// seed with microseconds
function make_seed()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?&#62;

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:
rand(),
getrandmax(), and
mt_srand().

Prev | Home | Next
sqrt | Up | tan


tan

(PHP 3, PHP 4, PHP 5)

tan -- Tangent

Description

float tan ( float arg )

tan() returns the tangent of the arg parameter. The arg parameter is in radians.

Example 1. tan() example

&#60;?php

echo tan(M_PI_4); // 1

?&#62;

See also:
atan(),
sin(),
cos(), and
deg2rad().

Prev | Home | Next
srand | Up | tanh


tanh

(PHP 4 >= 4.1.0, PHP 5)

tanh -- Hyperbolic tangent

Description

float tanh ( float arg )

Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).

See also:
tan(),
atanh(),
sin(), and
cos().

Prev | Home | Next
tan | Up | MaxDB PHP Extension


MaxDB PHP Extension

PHP Manual
Prev Next

LXXX. MaxDB PHP Extension

Introduction

The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at http://www.mysql.com/products/maxdb/.

The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.

The main differences to mysqli are in the following functions:

maxdb_character_set_name() - Returns only ascii or unicode.
maxdb_get_client_info() - Returns a different version string.
maxdb_get_client_version() - Returns a different version string.
maxdb_get_host_info() - Returns localhost or hostname.
maxdb_get_server_info() - Returns a different version string.
maxdb_get_server_version() - Returns a different version string.
maxdb_kill() - Only disconnects the session.
maxdb_multi_query() - Can not handle multiple SQL statements.
maxdb_next_result() - Function returns always false.
maxdb_options() - Supports a different set of options.
maxdb_report() - Supports a different report mode.
maxdb_stat() - Returns a different system status string.
maxdb_stmt_store_result() - Is not necessary for MaxDB.
maxdb_store_result() - Is not necessary for MaxDB.

Documentation for MaxDB can be found at http://dev.mysql.com/doc/maxdb/.

Requirements

In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.

Documentation for MaxDB SQLDBC can be found at http://dev.mysql.com/doc/maxdb/.

Download the MaxDB SQLDBC package from http://dev.mysql.com/downloads/maxdb/clients.html.

Installation

By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.

Windows users will need to enable php_maxdb.dll inside of php.ini.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. MaxDB Configuration Options

Name | Default | Changeable | Changelog
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

maxdb.default_host string

The default server host to use when connecting to the database server if no other host is specified.

maxdb.default_db string

The default server database to use when connecting if no other database is specified.

maxdb.default_user string

The default user name to use when connecting to the database server if no other name is specified.

maxdb.default_pw string

The default password to use when connecting to the database server if no other password is specified.

maxdb.long_readlen integer

The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.

Predefined Classes

maxdb

Represents a connection between PHP and a MaxDB database.

Constructor

  • maxdb - construct a new maxdb object

Methods

  • autocommit - turns on or off auto-commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MaxDB database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MaxDB server

  • get_server_version - returns version of the MaxDB server

  • init - initializes maxdb object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a MaxDB thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi-query

  • next_result - reads next result from currently executed multi-query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares a SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MaxDB database server

  • escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init- initializes a statement for use with maxdb_stmt_prepare

  • store_result - transfers a resultset from last query

  • use_result - transfers an unbuffered resultset from last query

  • thread-safe - returns whether thread safety is given or not

Properties

  • affected_rows - gets the number of affected rows in a previous MaxDB operation

  • client_info - returns the MaxDB client version as a string

  • client_version - returns the MaxDB client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MaxDB protocol used

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

maxdb_stmt

Represents a prepared statement.

Methods

  • bind_param - binds variables to a prepared statement

  • bind_result - binds variables to a prepared statement for result storage

  • close - closes a prepared statement

  • data-seek - seeks to an arbitrary row in a statement result set

  • execute - executes a prepared statement

  • fetch - fetches result from a prepared statement into bound variables

  • free_result - frees stored result memory for the given statement handle

  • result_metadata - retrieves a resultset from a prepared statement for metadata information

  • prepare - prepares a SQL query

  • send_long_data - sends data in chunks

  • close_long_data - end sending long data

  • reset - resets a prepared statement

  • store_result - buffers complete resultset from a prepared statement

Properties

  • affected_rows - returns affected rows from last statement execution

  • errno - returns errorcode for last statement function

  • errno - returns errormessage for last statement function

  • param_count - returns number of parameter for a given prepare statement

  • sqlstate - returns a string containing the SQLSTATE error code for the last statement function

maxdb_result

Represents the result set obtained from a query against the database.

Methods

  • close - closes resultset

  • data_seek - moves internal result pointer

  • fetch_field - gets column information from a resultset

  • fetch_fields - gets information for all columns from a resulset

  • fetch_field_direct - gets column information for specified column

  • fetch_array - fetches a result row as an associative array, a numeric array, or both.

  • fetch_assoc - fetches a result row as an associative array

  • fetch_object - fetches a result row as an object

  • fetch_row - gets a result row as an enumerated array

  • close - frees result memory

  • field_seek - set result pointer to a specified field offset

Properties

  • current_field - returns offset of current fieldpointer

  • field_count - returns number of fields in resultset

  • lengths - returns an array of columnlengths

  • num_rows - returns number of rows in resultset

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 to use with maxdb_options() are defined. For further description of these constants see http://dev.mysql.com/doc/maxdb/.

Table 2. MaxDB PHP client constants

Constant | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

Table 3. MaxDB fetch constants

Constant | Description
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index.
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index.
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index.
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MAXDB_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Examples

All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at http://dev.mysql.com/doc/maxdb/en/98/11b83fa6b33c17e10000000a114084/frameset.htm.

To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.

Example 1. MaxDB extension overview example

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$query = "SELECT * FROM hotel.city";
$result = maxdb_query($link, $query) or die("Query failed : " . maxdb_error());

/* Printing results in HTML */
echo "&#60;table&#62;\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  &#60;tr&#62;\n";
    foreach ($line as $col_value) {
        echo "    &#60;td&#62;$col_value&#60;/td&#62;\n";
    }
    echo "  &#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?&#62;

The following example shows how to bind variables to a SELECT INTO statement.

Example 2. Example for use of SELECT INTO statements

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT percentage INTO ? FROM hotel.countrylanguage where language = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$name = "Mbundu";

maxdb_stmt_bind_param($stmt, 'ds', $percentage, $name);
maxdb_stmt_execute($stmt);

printf ("%f\n", $percentage);

maxdb_stmt_close ($stmt);
?&#62;

The following example shows how to use MaxDB database procedures.

Example 3. Example fore using database procedures

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?&#62;

Table of Contents
maxdb_affected_rows -- Gets the number of affected rows in a previous MaxDB operation
maxdb_autocommit -- Turns on or off auto-commiting database modifications
maxdb_bind_param -- Alias of maxdb_stmt_bind_param()
maxdb_bind_result -- Alias of maxdb_stmt_bind_result()
maxdb_change_user -- Changes the user of the specified database connection
maxdb_character_set_name -- Returns the default character set for the database connection
maxdb_client_encoding -- Alias of maxdb_character_set_name()
maxdb_close_long_data -- Alias of maxdb_stmt_close_long_data()
maxdb_close -- Closes a previously opened database connection
maxdb_commit -- Commits the current transaction
maxdb_connect_errno -- Returns the error code from last connect call
maxdb_connect_error -- Returns a string description of the last connect error
maxdb_connect -- Open a new connection to the MaxDB server
maxdb_data_seek -- Adjusts the result pointer to an arbitary row in the result
maxdb_debug -- Performs debugging operations
maxdb_disable_reads_from_master -- Disable reads from master
maxdb_disable_rpl_parse -- Disable RPL parse
maxdb_dump_debug_info -- Dump debugging information into the log
maxdb_embedded_connect -- Open a connection to an embedded MaxDB server
maxdb_enable_reads_from_master -- Enable reads from master
maxdb_enable_rpl_parse -- Enable RPL parse
maxdb_errno -- Returns the error code for the most recent function call
maxdb_error -- Returns a string description of the last error
maxdb_escape_string -- Alias of maxdb_real_escape_string()
maxdb_execute -- Alias of maxdb_stmt_execute()
maxdb_fetch_array -- Fetch a result row as an associative, a numeric array, or both
maxdb_fetch_assoc -- Fetch a result row as an associative array
maxdb_fetch_field_direct -- Fetch meta-data for a single field
maxdb_fetch_field -- Returns the next field in the result set
maxdb_fetch_fields -- Returns an array of resources representing the fields in a result set
maxdb_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
maxdb_fetch_object -- Returns the current row of a result set as an object
maxdb_fetch_row -- Get a result row as an enumerated array
maxdb_fetch -- Alias of maxdb_stmt_fetch()
maxdb_field_count -- Returns the number of columns for the most recent query
maxdb_field_seek -- Set result pointer to a specified field offset
maxdb_field_tell -- Get current field offset of a result pointer
maxdb_free_result -- Frees the memory associated with a result
maxdb_get_client_info -- Returns the MaxDB client version as a string
maxdb_get_client_version -- Get MaxDB client info
maxdb_get_host_info -- Returns a string representing the type of connection used
maxdb_get_metadata -- Alias of maxdb_stmt_result_metadata()
maxdb_get_proto_info -- Returns the version of the MaxDB protocol used
maxdb_get_server_info -- Returns the version of the MaxDB server
maxdb_get_server_version -- Returns the version of the MaxDB server as an integer
maxdb_info -- Retrieves information about the most recently executed query
maxdb_init -- Initializes MaxDB and returns an resource for use with maxdb_real_connect
maxdb_insert_id -- Returns the auto generated id used in the last query
maxdb_kill -- Disconnects from a MaxDB server
maxdb_master_query -- Enforce execution of a query on the master in a master/slave setup
maxdb_more_results -- Check if there any more query results from a multi query
maxdb_multi_query -- Performs a query on the database
maxdb_next_result -- Prepare next result from multi_query
maxdb_num_fields -- Get the number of fields in a result
maxdb_num_rows -- Gets the number of rows in a result
maxdb_options -- Set options
maxdb_param_count -- Alias of maxdb_stmt_param_count()
maxdb_ping -- Pings a server connection, or tries to reconnect if the connection has gone down
maxdb_prepare -- Prepare a SQL statement for execution
maxdb_query -- Performs a query on the database
maxdb_real_connect -- Opens a connection to a MaxDB server
maxdb_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
maxdb_real_query -- Execute an SQL query
maxdb_report -- Enables or disables internal report functions
maxdb_rollback -- Rolls back current transaction
maxdb_rpl_parse_enabled -- Check if RPL parse is enabled
maxdb_rpl_probe -- RPL probe
maxdb_rpl_query_type -- Returns RPL query type
maxdb_select_db -- Selects the default database for database queries
maxdb_send_long_data -- Alias of maxdb_stmt_send_long_data()
maxdb_send_query -- Send the query and return
maxdb_server_end -- Shut down the embedded server
maxdb_server_init -- Initialize embedded server
maxdb_set_opt -- Alias of maxdb_options()
maxdb_sqlstate -- Returns the SQLSTATE error from previous MaxDB operation
maxdb_ssl_set -- Used for establishing secure connections using SSL
maxdb_stat -- Gets the current system status
maxdb_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
maxdb_stmt_bind_param -- Binds variables to a prepared statement as parameters
maxdb_stmt_bind_result -- Binds variables to a prepared statement for result storage
maxdb_stmt_close_long_data -- Ends a sequence of maxdb_stmt_send_long_data()
maxdb_stmt_close -- Closes a prepared statement
maxdb_stmt_data_seek -- Seeks to an arbitray row in statement result set
maxdb_stmt_errno -- Returns the error code for the most recent statement call
maxdb_stmt_error -- Returns a string description for last statement error
maxdb_stmt_execute -- Executes a prepared Query
maxdb_stmt_fetch -- Fetch results from a prepared statement into the bound variables
maxdb_stmt_free_result -- Frees stored result memory for the given statement handle
maxdb_stmt_init -- Initializes a statement and returns an resource for use with maxdb_stmt_prepare
maxdb_stmt_num_rows -- Return the number of rows in statements result set
maxdb_stmt_param_count -- Returns the number of parameter for the given statement
maxdb_stmt_prepare -- Prepare a SQL statement for execution
maxdb_stmt_reset -- Resets a prepared statement
maxdb_stmt_result_metadata -- Returns result set metadata from a prepared statement
maxdb_stmt_send_long_data -- Send data in blocks
maxdb_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
maxdb_stmt_store_result -- Transfers a result set from a prepared statement
maxdb_store_result -- Transfers a result set from the last query
maxdb_thread_id -- Returns the thread ID for the current connection
maxdb_thread_safe -- Returns whether thread safety is given or not
maxdb_use_result -- Initiate a result set retrieval
maxdb_warning_count -- Returns the number of warnings from the last query for the given link

Prev | Home | Next
tanh | Up | maxdb_affected_rows


maxdb_affected_rows

(PECL)

maxdb_affected_rows

(no version information, might be only in CVS)

maxdb->affected_rows -- Gets the number of affected rows in a previous MaxDB operation

Description

Procedural style:

int maxdb_affected_rows ( resource link )

Object oriented style (property):

class maxdb {

int affected_rows

}

maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.

Note: For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().

The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the number of rows affected can not be determined.

See also

maxdb_num_rows(), maxdb_info().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb-&#62;query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb-&#62;query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb-&#62;affected_rows);

$maxdb-&#62;query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb-&#62;query("UPDATE mycustomer SET Status=1 WHERE cno &#62; 50");
printf("Affected rows (UPDATE): %d\n", $maxdb-&#62;affected_rows);

/* delete rows */
$maxdb-&#62;query("DELETE FROM mycustomer WHERE cno &#60; 50");
printf("Affected rows (DELETE): %d\n", $maxdb-&#62;affected_rows);

/* select all rows */
$result = $maxdb-&#62;query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb-&#62;affected_rows);

$result-&#62;close();

/* Delete table Language */
$maxdb-&#62;query("DROP TABLE mycustomer");

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
maxdb_query($link, "CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", maxdb_affected_rows($link));

maxdb_query($link, "ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
maxdb_query($link, "UPDATE mycustomer SET Status=1 WHERE cno &#62; 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno &#60; 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));

/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));

maxdb_free_result($result);

/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

Prev | Home | Next
MaxDB PHP Extension | Up | maxdb_autocommit


maxdb_autocommit

(PECL)

maxdb_autocommit

(no version information, might be only in CVS)

maxdb->auto_commit -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool maxdb_autocommit ( resource link, bool mode )

Object oriented style (method)

class maxdb {

bool auto_commit ( bool mode )

}

maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_commit(), maxdb_rollback().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
$maxdb-&#62;autocommit(TRUE);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
maxdb_autocommit($link, TRUE);

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce no output.

Prev | Home | Next
maxdb_affected_rows | Up | maxdb_bind_param


maxdb_bind_param

(PECL)

maxdb_bind_param -- Alias of maxdb_stmt_bind_param()

Description

This function is an alias of: maxdb_stmt_bind_param()

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.

Prev | Home | Next
maxdb_autocommit | Up | maxdb_bind_result


maxdb_bind_result

(PECL)

maxdb_bind_result -- Alias of maxdb_stmt_bind_result()

Description

This function is an alias of: maxdb_stmt_bind_result().

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.

Prev | Home | Next
maxdb_bind_param | Up | maxdb_change_user


maxdb_change_user

(PECL)

maxdb_change_user

(no version information, might be only in CVS)

maxdb->change_user -- Changes the user of the specified database connection

Description

Procedural style:

bool maxdb_change_user ( resource link, string user, string password, string database )

Object oriented style (method):

class maxdb {

bool change_user ( string user, string password, string database )

}

maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Note: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Return Values

Returns TRUE on success or FALSE on failure.

See also:

maxdb_connect() maxdb_select_db()

Example

Example 1. Object oriented style

&#60;?php

/* connect database test */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb-&#62;query("SELECT * FROM dual")) {
   $row = $result-&#62;fetch_row();
   printf("Result: %s\n", $row[0]);
   $result-&#62;free();
}

/* reset all and select a new database */
if (!$maxdb-&#62;change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM dual")) {
   $row = maxdb_fetch_row($result);
   printf("Result: %s\n", $row[0]);
   maxdb_free_result($result);
}

/* reset all and select a new database */
if (!maxdb_change_user($link, "DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Result: a
Database running

Prev | Home | Next
maxdb_bind_result | Up | maxdb_character_set_name


maxdb_character_set_name

(PECL)

maxdb_character_set_name

(no version information, might be only in CVS)

maxdb->character_set_name -- Returns the default character set for the database connection

Description

Procedural style:

string maxdb_character_set_name ( resource link )

Object oriented style (method):

class maxdb {

string character_set_name ( void )

}

Returns the current character set for the database connection specified by the link parameter.

Return values

The default character set for the current connection, either ascii or unicode.

See also

maxdb_client_encoding(). maxdb_real_escape_string().

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = $maxdb-&#62;character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = maxdb_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
maxdb_close($link);
?&#62;

The above examples would be produce the following output:

Current character set is ascii

Prev | Home | Next
maxdb_change_user | Up | maxdb_client_encoding


maxdb_client_encoding

(PECL)

maxdb_client_encoding -- Alias of maxdb_character_set_name()

Description

This function is an alias of: maxdb_character_set_name().

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.

Prev | Home | Next
maxdb_character_set_name | Up | maxdb_close_long_data


maxdb_close_long_data

(PECL)

maxdb_close_long_data

(no version information, might be only in CVS)

maxdb->close_long_data -- Alias of maxdb_stmt_close_long_data()

Description

This function is an alias of: maxdb_stmt_close_long_data().

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.

Prev | Home | Next
maxdb_client_encoding | Up | maxdb_close


maxdb_close

(PECL)

maxdb_close

(no version information, might be only in CVS)

maxdb->close -- Closes a previously opened database connection

Description

Procedural style:

bool maxdb_close ( resource link )

Object oriented style (method):

class maxdb {

bool close ( void )

}

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_connect(),
maxdb_init(),
maxdb_real_connect().

Prev | Home | Next
maxdb_close_long_data | Up | maxdb_commit


maxdb_commit

(PECL)

maxdb_commit

(no version information, might be only in CVS)

maxdb->commit -- Commits the current transaction

Description

Procedural style:

bool maxdb_commit ( resource link )

Object oriented style (method)

class maxdb {

bool commit ( void )

}

Commits the current transaction for the database connection specified by the link parameter.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_autocommit(), maxdb_rollback().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
$maxdb-&#62;autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb-&#62;query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb-&#62;query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb-&#62;query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb-&#62;query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb-&#62;commit();

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
maxdb_autocommit($link, FALSE);

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
maxdb_query($link, "INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
maxdb_query($link, "INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
maxdb_commit($link);

/* close connection */
maxdb_close($link);
?&#62;

The above examples produces no output.

Prev | Home | Next
maxdb_close | Up | maxdb_connect_errno


maxdb_connect_errno

(PECL)

maxdb_connect_errno -- Returns the error code from last connect call

Description

int maxdb_connect_errno ( void )

The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occured, this function will return zero.

Return values

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

See also

maxdb_connect(),
maxdb_connect_error(),
maxdb_errno(),
maxdb_error(),
maxdb_sqlstate()

Example

Example 1. maxdb_connect_errno sample

&#60;?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?&#62;

The above example would produce the following output:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

Prev | Home | Next
maxdb_commit | Up | maxdb_connect_error


maxdb_connect_error

(PECL)

maxdb_connect_error -- Returns a string description of the last connect error

Description

string maxdb_connect_error ( void )

The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occured, this function will return an empty string.

Return values

A string that describes the error. An empty string if no error occurred.

See also

maxdb_connect(),
maxdb_connect_errno(),
maxdb_errno(),
maxdb_error(),
maxdb_sqlstate()

Example

Example 1. maxdb_connect_error sample

&#60;?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?&#62;

The above example would produce the following output:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...>
Can't connect to localhost. Error: POS(1) Unknown user name/password combination

Prev | Home | Next
maxdb_connect_errno | Up | maxdb_connect


maxdb_connect

(PECL)

maxdb_connect

(no version information, might be only in CVS)

maxdb() -- Open a new connection to the MaxDB server

Description

Procedural style

resource maxdb_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

Object oriented style (constructor):

class maxdb {

__construct ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database, or FALSE on failure.

The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.

The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.

The port and socket parameters are ignored for the MaxDB server.

Return values

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", $maxdb-&#62;host_info);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Host information: localhost

Prev | Home | Next
maxdb_connect_error | Up | maxdb_data_seek


maxdb_data_seek

(PECL)

maxdb_data_seek

(no version information, might be only in CVS)

result->data_seek -- Adjusts the result pointer to an arbitary row in the result

Description

Procedural style:

bool maxdb_data_seek ( resource result, int offset )

Object oriented style (method):

class result {

bool data_seek ( int offset )

}

The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_store_result(),
maxdb_fetch_row(),
maxdb_num_rows().

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";
if ($result = $maxdb-&#62;query( $query)) {

   /* seek to row no. 10 */
   $result-&#62;data_seek(10);

   /* fetch row */
   $row = $result-&#62;fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* seek to row no. 400 */
   maxdb_data_seek($result, 10);

   /* fetch row */
   $row = maxdb_fetch_row($result);

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

City: Irvine  State: CA

Prev | Home | Next
maxdb_connect | Up | maxdb_debug


maxdb_dump_debug_info

(PECL)

maxdb_dump_debug_info -- Dump debugging information into the log

Description

bool maxdb_dump_debug_info ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_disable_rpl_parse | Up | maxdb_embedded_connect


maxdb_debug

(PECL)

maxdb_debug -- Performs debugging operations

Description

void maxdb_debug ( string debug )

The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():

TRACE SHORT ON|OFF - Enables/disables method call trace.
TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace.
TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified.
TRACE SQL ON|OFF - Enables/disables high level api trace.
TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced.
TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required.

Return values

maxdb_debug() doesn't return any value.

Example

Example 1. Procedural style

&#60;?php

maxdb_debug("trace packet 200");

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* close connection */
maxdb_close($link);
?&#62;

The above example produces no output.

Prev | Home | Next
maxdb_data_seek | Up | maxdb_disable_reads_from_master


maxdb_disable_reads_from_master

(PECL)

maxdb_disable_reads_from_master

(no version information, might be only in CVS)

maxdb->disable_reads_from_master -- Disable reads from master

Description

Procedural style:

bool maxdb_disable_reads_from_master ( resource link )

Object oriented style (method):

class maxdb {

void disable_reads_from_master ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_debug | Up | maxdb_disable_rpl_parse


maxdb_disable_rpl_parse

(PECL)

maxdb_disable_rpl_parse -- Disable RPL parse

Description

bool maxdb_disable_rpl_parse ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_disable_reads_from_master | Up | maxdb_dump_debug_info


maxdb_embedded_connect

(PECL)

maxdb_embedded_connect -- Open a connection to an embedded MaxDB server

Description

resource maxdb_embedded_connect ( [string dbname] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_dump_debug_info | Up | maxdb_enable_reads_from_master


maxdb_enable_reads_from_master

(PECL)

maxdb_enable_reads_from_master -- Enable reads from master

Description

bool maxdb_enable_reads_from_master ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_embedded_connect | Up | maxdb_enable_rpl_parse


maxdb_enable_rpl_parse

(PECL)

maxdb_enable_rpl_parse -- Enable RPL parse

Description

bool maxdb_enable_rpl_parse ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_enable_reads_from_master | Up | maxdb_errno


maxdb_errno

(PECL)

maxdb_errno

(no version information, might be only in CVS)

maxdb->errno -- Returns the error code for the most recent function call

Description

Procedural style:

int maxdb_errno ( resource link )

Object oriented style (property):

class maxdb {

int errno

}

The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.

Return values

An error code value for the last call, if it failed. zero means no error occurred.

See also

maxdb_connect_errno(),
maxdb_connect_error(),
maxdb_error(),
maxdb_sqlstate()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb-&#62;query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb-&#62;errno);
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", maxdb_errno($link));
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

Prev | Home | Next
maxdb_enable_rpl_parse | Up | maxdb_error


maxdb_error

(PECL)

maxdb_error -- Returns a string description of the last error

Description

Procedural style:

string maxdb_error ( resource link )

Object oriented style (property)

class maxdb {

string error

}

The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.

Return values

A string that describes the error. An empty string if no error occurred.

See also

maxdb_connect_errno(),
maxdb_connect_error(),
maxdb_errno(),
maxdb_sqlstate()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb-&#62;query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb-&#62;error);
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errormessgae: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

Prev | Home | Next
maxdb_errno | Up | maxdb_escape_string


maxdb_escape_string

(PECL)

maxdb_escape_string -- Alias of maxdb_real_escape_string()

Description

This function is an alias of: maxdb_real_escape_string().

Prev | Home | Next
maxdb_error | Up | maxdb_execute


maxdb_execute

(PECL)

maxdb_execute -- Alias of maxdb_stmt_execute()

Description

This function is an alias of: maxdb_stmt_execute().

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.

Prev | Home | Next
maxdb_escape_string | Up | maxdb_fetch_array


maxdb_fetch_array

(PECL)

maxdb_fetch_array

(no version information, might be only in CVS)

result->fetch_array -- Fetch a result row as an associative, a numeric array, or both

Description

Procedural style:

mixed maxdb_fetch_array ( resource result [, int resulttype] )

Object oriented style (method):

class result {

mixed fetch_array ( [int resulttype] )

}

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.

By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.

By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.

By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

See also

maxdb_fetch_assoc(),
maxdb_fetch_row(),
maxdb_fetch_resource().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = $maxdb-&#62;query($query);

/* numeric array */
$row = $result-&#62;fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result-&#62;fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = $result-&#62;fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
$result-&#62;close();

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = maxdb_query($link, $query);

/* numeric array */
$row = maxdb_fetch_array($result, MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = maxdb_fetch_array($result, MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = maxdb_fetch_array($result, MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

New York (NY)
New York (NY)
Long Island (NY)

Prev | Home | Next
maxdb_execute | Up | maxdb_fetch_assoc


maxdb_fetch_assoc

(PECL)

maxdb_fetch_assoc

(no version information, might be only in CVS)

maxdb->fetch_assoc -- Fetch a result row as an associative array

Description

Procedural style:

array maxdb_fetch_assoc ( resource result )

Object oriented style (method):

class result {

array fetch_assoc ( void )

}

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.

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 maxdb_fetch_row() or add alias names.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

See also

maxdb_fetch_array(),
maxdb_fetch_row(),
maxdb_fetch_resource().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb-&#62;query($query)) {

   /* fetch associative array */
   while ($row = $result-&#62;fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_assoc($result)) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Prev | Home | Next
maxdb_fetch_array | Up | maxdb_fetch_field_direct


maxdb_fetch_field_direct

(PECL)

maxdb_fetch_field_direct

(no version information, might be only in CVS)

result->fetch_field_direct -- Fetch meta-data for a single field

Description

Procedural style:

mixed maxdb_fetch_field_direct ( resource result, int fieldnr )

Object oriented style (method):

class result {

mixed fetch_field_direct ( int fieldnr )

}

maxdb_fetch_field_direct() returns an resource which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.

Return values

Returns an resource which contains field definition informations or FALSE if no field information for specified fieldnr is available.

Table 1. Object attributes

Attribute | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

See also

maxdb_num_fields()
maxdb_fetch_field()
maxdb_fetch_fields()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = $maxdb-&#62;query($query)) {

   /* Get field information for column 'SurfaceArea' */
   $finfo = $result-&#62;fetch_field_direct(1);

   printf("Name:     %s\n", $finfo-&#62;name);
   printf("Table:    %s\n", $finfo-&#62;table);
   printf("max. Len: %d\n", $finfo-&#62;max_length);
   printf("Flags:    %d\n", $finfo-&#62;flags);
   printf("Type:     %d\n", $finfo-&#62;type);

   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for column 'cno' */
   $finfo = maxdb_fetch_field_direct($result, 1);

   printf("Name:     %s\n", $finfo-&#62;name);
   printf("Table:    %s\n", $finfo-&#62;table);
   printf("max. Len: %d\n", $finfo-&#62;max_length);
   printf("Flags:    %d\n", $finfo-&#62;flags);
   printf("Type:     %d\n", $finfo-&#62;type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Prev | Home | Next
maxdb_fetch_assoc | Up | maxdb_fetch_field


maxdb_fetch_field

(PECL)

maxdb_fetch_field

(no version information, might be only in CVS)

result->fetch_field -- Returns the next field in the result set

Description

Procedural style:

mixed maxdb_fetch_field ( resource result )

Object oriented style (method):

class result {

mixed fetch_field ( void )

}

The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.

Return values

Returns an resource which contains field definition informations or FALSE if no field information is available.

Table 1. Object properties

Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

See also

maxdb_num_fields()
maxdb_fetch_field_direct()
maxdb_fetch_fields()
maxdb_field_seek()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb-&#62;query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result-&#62;fetch_field()) {

       printf("Name:     %s\n", $finfo-&#62;name);
       printf("Table:    %s\n", $finfo-&#62;table);
       printf("max. Len: %d\n", $finfo-&#62;max_length);
       printf("Flags:    %d\n", $finfo-&#62;flags);
       printf("Type:     %d\n\n", $finfo-&#62;type);
   }
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       printf("Name:     %s\n", $finfo-&#62;name);
       printf("Table:    %s\n", $finfo-&#62;table);
       printf("max. Len: %d\n", $finfo-&#62;max_length);
       printf("Flags:    %d\n", $finfo-&#62;flags);
       printf("Type:     %d\n\n", $finfo-&#62;type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Prev | Home | Next
maxdb_fetch_field_direct | Up | maxdb_fetch_fields


maxdb_fetch_fields

(PECL)

maxdb_fetch_fields

(no version information, might be only in CVS)

result->fetch_fields -- Returns an array of resources representing the fields in a result set

Description

Procedural Style:

mixed maxdb_fetch_fields ( resource result )

Object oriented style (method):

class result {

mixed fetch_fields ( void )

}

This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.

Return values

Returns an array of resources which contains field definition informations or FALSE if no field information is available.

Table 1. Object properties

Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

See also

maxdb_num_fields()
maxdb_fetch_field()
maxdb_fetch_field_direct()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb-&#62;query($query)) {

   /* Get field information for all columns */
   $finfo = $result-&#62;fetch_fields();

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val-&#62;name);
       printf("Table:    %s\n", $val-&#62;table);
       printf("max. Len: %d\n", $val-&#62;max_length);
       printf("Flags:    %d\n", $val-&#62;flags);
       printf("Type:     %d\n\n", $val-&#62;type);
   }
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all columns */
   $finfo = maxdb_fetch_fields($result);

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val-&#62;name);
       printf("Table:    %s\n", $val-&#62;table);
       printf("max. Len: %d\n", $val-&#62;max_length);
       printf("Flags:    %d\n", $val-&#62;flags);
       printf("Type:     %d\n\n", $val-&#62;type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Prev | Home | Next
maxdb_fetch_field | Up | maxdb_fetch_lengths


maxdb_fetch_lengths

(PECL)

maxdb_fetch_lengths

(no version information, might be only in CVS)

result->lengths -- Returns the lengths of the columns of the current row in the result set

Description

Procedural style:

array maxdb_fetch_lengths ( resource result )

Object oriented style (property):

class result {

array lengths

}

The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.

Return values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = $maxdb-&#62;query($query)) {

   $row = $result-&#62;fetch_row();

   /* display column lengths */
   foreach ($result-&#62;lengths as $i =&#62; $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = maxdb_query($link, $query)) {

   $row = maxdb_fetch_row($result);

   /* display column lengths */
   foreach (maxdb_fetch_lengths($result) as $i =&#62; $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Field  1 has Length  4
Field  2 has Length  3
Field  3 has Length  5
Field  4 has Length  6
Field  5 has Length  5
Field  6 has Length 21

Prev | Home | Next
maxdb_fetch_fields | Up | maxdb_fetch_object


maxdb_fetch_object

(PECL)

maxdb_fetch_object

(no version information, might be only in CVS)

result->fetch_object -- Returns the current row of a result set as an object

Description

Procedural style:

object maxdb_fetch_object ( object result )

Object oriented style (method):

class result {

object fetch_object ( void )

}

The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.

Return values

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See also

maxdb_fetch_array(),
maxdb_fetch_assoc(),
maxdb_fetch_row().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb-&#62;query($query)) {

   /* fetch object array */
   while ($obj = $result-&#62;fetch_object()) {
       printf ("%s (%s)\n", $obj-&#62;NAME, $obj-&#62;STATE);
   }

   /* free result set */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch object array */
   while ($obj = maxdb_fetch_object($result)) {
       printf ("%s (%s)\n", $obj-&#62;NAME, $obj-&#62;STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Prev | Home | Next
maxdb_fetch_lengths | Up | maxdb_fetch_row


maxdb_fetch_row

(PECL)

maxdb_fetch_row

(no version information, might be only in CVS)

result->fetch_row -- Get a result row as an enumerated array

Description

Procedural style:

mixed maxdb_fetch_row ( resource result )

Object oriented style (method):

class result {

mixed fetch_row ( void )

}

Returns an array that corresponds to the fetched row, or NULL if there are no more rows.

maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.

Return values

maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to PHP NULL value.

See also

maxdb_fetch_array(),
maxdb_fetch_assoc(),
maxdb_fetch_resource().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb-&#62;query($query)) {

   /* fetch enumerated array */
   while ($row = $result-&#62;fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch enumerated array */
   while ($row = maxdb_fetch_row($result)) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Prev | Home | Next
maxdb_fetch_object | Up | maxdb_fetch


maxdb_fetch

(PECL)

maxdb_fetch -- Alias of maxdb_stmt_fetch()

Description

This function is an alias of: maxdb_stmt_fetch().

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.

Prev | Home | Next
maxdb_fetch_row | Up | maxdb_field_count


maxdb_field_count

(PECL)

maxdb_field_count

(no version information, might be only in CVS)

maxdb->field_count -- Returns the number of columns for the most recent query

Description

Procedural style:

int maxdb_field_count ( resource link )

Object oriented style (method):

class maxdb {

int field_count ( void )

}

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Return values

An integer representing the number of fields in a result set

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb-&#62;query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb-&#62;query( "CREATE TABLE friends (id int, name varchar(20))");

$maxdb-&#62;query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb-&#62;query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb-&#62;field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb-&#62;store_result();

   /* process resultset */
   $row = $result-&#62;fetch_row();

   /* free resultset */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO friends VALUES (2, 'Ulf')");

if (maxdb_field_count($link)) {
   /* this was a select/show or describe query */
   $result = maxdb_store_result($link);

   /* process resultset */
   $row = maxdb_fetch_row($result);

   /* free resultset */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above example produces no output.

Prev | Home | Next
maxdb_fetch | Up | maxdb_field_seek


maxdb_field_seek

(PECL)

maxdb_field_seek

(no version information, might be only in CVS)

result->field_seek -- Set result pointer to a specified field offset

Description

Procedural style:

bool maxdb_field_seek ( resource result, int fieldnr )

Object oriented style (method):

class result {

bool field_seek ( int fieldnr )

}

Sets the field cursor to the given offset. The next call to maxdb_fetch_field() will retrieve the field definition of the column associated with that offset.

Note: To seek to the beginning of a row, pass an offset value of zero.

Return values

maxdb_field_seek() returns previuos value of field cursor.

See also

maxdb_fetch_field()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb-&#62;query($query)) {

   /* Get field information for 2nd column */
   $result-&#62;field_seek(1);
   $finfo = $result-&#62;fetch_field();

   printf("Name:     %s\n", $finfo-&#62;name);
   printf("Table:    %s\n", $finfo-&#62;table);
   printf("max. Len: %d\n", $finfo-&#62;max_length);
   printf("Flags:    %d\n", $finfo-&#62;flags);
   printf("Type:     %d\n\n", $finfo-&#62;type);

   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for 2nd column */
   maxdb_field_seek($result, 1);
   $finfo = maxdb_fetch_field($result);

   printf("Name:     %s\n", $finfo-&#62;name);
   printf("Table:    %s\n", $finfo-&#62;table);
   printf("max. Len: %d\n", $finfo-&#62;max_length);
   printf("Flags:    %d\n", $finfo-&#62;flags);
   printf("Type:     %d\n\n", $finfo-&#62;type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Prev | Home | Next
maxdb_field_count | Up | maxdb_field_tell


maxdb_field_tell

(PECL)

maxdb_field_tell

(no version information, might be only in CVS)

result->current_field -- Get current field offset of a result pointer

Description

Procedural style:

int maxdb_field_tell ( resource result )

Object oriented style (property):

class result {

int current_field

}

Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().

Return Values

Returns current offset of field cursor.

See Also

maxdb_fetch_field(), maxdb_field_seek()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb-&#62;query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result-&#62;fetch_field()) {

       /* get fieldpointer offset */
       $currentfield = $result-&#62;current_field;

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo-&#62;name);
       printf("Table:    %s\n", $finfo-&#62;table);
       printf("max. Len: %d\n", $finfo-&#62;max_length);
       printf("Flags:    %d\n", $finfo-&#62;flags);
       printf("Type:     %d\n\n", $finfo-&#62;type);
   }
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       /* get fieldpointer offset */
       $currentfield = maxdb_field_tell($result);

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo-&#62;name);
       printf("Table:    %s\n", $finfo-&#62;table);
       printf("max. Len: %d\n", $finfo-&#62;max_length);
       printf("Flags:    %d\n", $finfo-&#62;flags);
       printf("Type:     %d\n\n", $finfo-&#62;type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Prev | Home | Next
maxdb_field_seek | Up | maxdb_free_result


maxdb_free_result

(PECL)

maxdb_free_result

(no version information, might be only in CVS)

result->free -- Frees the memory associated with a result

Description

Procedural style:

void maxdb_free_result ( resource result )

Object oriented style (method):

class result {

void free ( void )

}

The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().

Note: You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.

Return Values

This function doesn't return any value.

See Also

maxdb_query(),
maxdb_stmt_store_result(),
maxdb_store_result(),
maxdb_use_result().

Prev | Home | Next
maxdb_field_tell | Up | maxdb_get_client_info


maxdb_get_client_info

(PECL)

maxdb_get_client_info -- Returns the MaxDB client version as a string

Description

string maxdb_get_client_info ( void )

The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.

Return Values

A string that represents the MaxDB client library version

See also

maxdb_get_client_version(),
maxdb_get_server_info(),
maxdb_get_server_version()

Example

Example 1. maxdb_get_client_info

&#60;?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %s\n", maxdb_get_client_info());
?&#62;

The above examples would produce the following output:

Client library version: libSQLDBC <...>

Prev | Home | Next
maxdb_free_result | Up | maxdb_get_client_version


maxdb_get_client_version

(PECL)

maxdb_get_client_version -- Get MaxDB client info

Description

int maxdb_get_client_version ( void )

Returns client version number as an integer.

Return values

A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.

This is useful to quickly determine the version of the client library to know if some capability exists.

See also

maxdb_get_client_info(),
maxdb_get_server_info(),
maxdb_get_server_version()

Example

Example 1. maxdb_get_client_version

&#60;?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %d\n", maxdb_get_client_version());
?&#62;

The above examples would produce the following output:

Client library version: 7.<...>

Prev | Home | Next
maxdb_get_client_info | Up | maxdb_get_host_info


maxdb_get_host_info

(PECL)

maxdb_get_host_info

(no version information, might be only in CVS)

maxdb->get_host_info -- Returns a string representing the type of connection used

Description

Procdural style:

string maxdb_get_host_info ( resource link )

Object oriented style (property):

class maxdb {

string host_info

}

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Return Values

A character string representing the server hostname and the connection type.

See also

maxdb_get_proto_info()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", $maxdb-&#62;host_info);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Host info: localhost

Prev | Home | Next
maxdb_get_client_version | Up | maxdb_get_metadata


maxdb_get_metadata

(PECL)

maxdb_get_metadata -- Alias of maxdb_stmt_result_metadata()

Description

This function is an alias of: maxdb_stmt_result_metadata().

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.

Prev | Home | Next
maxdb_get_host_info | Up | maxdb_get_proto_info


maxdb_get_proto_info

(PECL)

maxdb_get_proto_info

(no version information, might be only in CVS)

maxdb->protocol_version -- Returns the version of the MaxDB protocol used

Description

Procedural style:

int maxdb_get_proto_info ( resource link )

Object oriented style (property):

class maxdb {

string protocol_version

}

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Return Values

Returns an integer representing the protocol version (constant 10).

See also

maxdb_get_host_info()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $maxdb-&#62;protocol_version);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", maxdb_get_proto_info($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Protocol version: 10

Prev | Home | Next
maxdb_get_metadata | Up | maxdb_get_server_info


maxdb_get_server_info

(PECL)

maxdb_get_server_info

(no version information, might be only in CVS)

maxdb->server_info -- Returns the version of the MaxDB server

Description

Procedural style:

string maxdb_get_server_info ( resource link )

Object oriented style (property):

class maxdb {

string server_info

}

Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).

Return Values

A character string representing the server version.

See also

maxdb_get_client_info(),
maxdb_get_client_version(),
maxdb_get_server_version()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", $maxdb-&#62;server_info);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", maxdb_get_server_info($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Server version: Kernel    7<...>

Prev | Home | Next
maxdb_get_proto_info | Up | maxdb_get_server_version


maxdb_get_server_version

(PECL)

maxdb_get_server_version -- Returns the version of the MaxDB server as an integer

Description

Procedural style:

int maxdb_get_server_version ( resource link )

Object oriented style (property):

class maxdb {

int server_version

}

The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).

Return Values

An integer representing the server version.

See also

maxdb_get_client_info(),
maxdb_get_client_version(),
maxdb_get_server_info()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", $maxdb-&#62;server_version);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", maxdb_get_server_version($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Server version: 7<...>

Prev | Home | Next
maxdb_get_server_info | Up | maxdb_info


maxdb_info

(PECL)

maxdb_info

(no version information, might be only in CVS)

maxdb->info -- Retrieves information about the most recently executed query

Description

Procedural style:

string maxdb_info ( resource link )

Object oriented style (property)

class maxdb {

string info

}

The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Table 1. Possible maxdb_info return values

Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Note: Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.

Return Values

A character string representing additional information about the most recently executed query.

See Also

maxdb_affected_rows(),
maxdb_warning_count(),
maxdb_num_rows()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb-&#62;query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb-&#62;info);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
maxdb_query($link, "INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", maxdb_info($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Records: 25 Duplicates: 0 Warnings: 0

Prev | Home | Next
maxdb_get_server_version | Up | maxdb_init


maxdb_init

(PECL)

maxdb_init -- Initializes MaxDB and returns an resource for use with maxdb_real_connect

Description

resource maxdb_init ( void )

Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().

Note: Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.

Return Values

Returns an resource.

See Also

maxdb_options(),
maxdb_close(),
maxdb_real_connect(),
maxdb_connect()

Prev | Home | Next
maxdb_info | Up | maxdb_insert_id


maxdb_insert_id

(PECL)

maxdb_insert_id

(no version information, might be only in CVS)

maxdb->insert_id -- Returns the auto generated id used in the last query

Description

Procedural style:

mixed maxdb_insert_id ( resource link )

Object oriented style (property):

class maxdb {

mixed insert_id

}

The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.

Return Values

The value of the DEFAULT SERIAL field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an DEFAULT_SERIAL value.

Note: If the number is greater than maximal int value, maxdb_insert_id() will return a string.

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb-&#62;query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb-&#62;query("CREATE TABLE mycity LIKE hotel.city");
$maxdb-&#62;query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb-&#62;query($query);

printf ("New Record has id %d.\n", $maxdb-&#62;insert_id);

/* drop table */
$maxdb-&#62;query("DROP TABLE mycity");

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city");
maxdb_query($link, "ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
maxdb_query($link, $query);

printf ("New Record has id %d.\n", maxdb_insert_id($link));

/* drop table */
maxdb_query($link, "DROP TABLE mycity");

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

New Record has id 1.

Prev | Home | Next
maxdb_init | Up | maxdb_kill


maxdb_kill

(PECL)

maxdb_kill

(no version information, might be only in CVS)

maxdb->kill -- Disconnects from a MaxDB server

Description

Procedural style:

bool maxdb_kill ( resource link, int processid )

Object oriented style (method)

class maxdb {

bool kill ( int processid )

}

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_thread_id()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb-&#62;thread_id;

/* Kill connection */
$maxdb-&#62;kill($thread_id);

/* This should produce an error */
if (!$maxdb-&#62;query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb-&#62;error);
   exit;
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Error: Session not connected

Prev | Home | Next
maxdb_insert_id | Up | maxdb_master_query


maxdb_master_query

(PECL)

maxdb_master_query -- Enforce execution of a query on the master in a master/slave setup

Description

bool maxdb_master_query ( resource link, string query )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_kill | Up | maxdb_more_results


maxdb_more_results

(PECL)

maxdb_more_results

(no version information, might be only in CVS)

maxdb->more_results -- Check if there any more query results from a multi query

Description

bool maxdb_more_results ( resource link )

maxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().

Return values

Always FALSE.

See also

maxdb_multi_query(),
maxdb_next_result(),
maxdb_store_result(),
maxdb_use_result()

Example

See maxdb_multi_query().

Prev | Home | Next
maxdb_master_query | Up | maxdb_multi_query


maxdb_multi_query

(PECL)

maxdb_multi_query

(no version information, might be only in CVS)

maxdb->multi_query -- Performs a query on the database

Description

Procedural style:

bool maxdb_multi_query ( resource link, string query )

Object oriented style (method):

class maxdb {

bool multi_query ( string query )

}

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_use_result(),
maxdb_store_result(),
maxdb_next_result(),
maxdb_more_results()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM dual";

/* execute multi query */
if ($maxdb-&#62;multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb-&#62;store_result()) {
           while ($row = $result-&#62;fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result-&#62;close();
       }
       /* print divider */
       if ($maxdb-&#62;more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb-&#62;next_result());
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * FROM dual";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_store_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

a

Prev | Home | Next
maxdb_more_results | Up | maxdb_next_result


maxdb_next_result

(PECL)

maxdb_next_result

(no version information, might be only in CVS)

maxdb->next_result -- Prepare next result from multi_query

Description

bool maxdb_next_result ( resource link )

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Return values

FALSE

See also

maxdb_multi_query(),
maxdb_more_results(),
maxdb_store_result(),
maxdb_use_result()

Prev | Home | Next
maxdb_multi_query | Up | maxdb_num_fields


maxdb_num_fields

(PECL)

maxdb_num_fields

(no version information, might be only in CVS)

result->field_count -- Get the number of fields in a result

Description

Procedural style:

int maxdb_num_fields ( resource result )

Object oriented style (property):

class result {

int field_count

}

maxdb_num_fields() returns the number of fields from specified result set.

Return Values

The number of fields from a result set

See Also

maxdb_fetch_field()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb-&#62;query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result-&#62;field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = maxdb_num_fields($result);

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Result set has 3 fields.

Prev | Home | Next
maxdb_next_result | Up | maxdb_num_rows


maxdb_num_rows

(PECL)

maxdb_num_rows -- Gets the number of rows in a result

Description

Procedural style:

int maxdb_num_rows ( resource result )

Object oriented style (property):

class maxdb {

int num_rows

}

Returns the number of rows in the result set.

The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Return Values

Returns number of rows in the result set.

Note: If the number of rows is greater than maximal int value, the number will be returned as a string.

See Also

maxdb_affected_rows()
maxdb_store_result()
maxdb_use_result()
maxdb_query()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb-&#62;query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result-&#62;num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = maxdb_num_rows($result);

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Result set has 15 rows.

Prev | Home | Next
maxdb_num_fields | Up | maxdb_options


maxdb_options

(PECL)

maxdb_options

(no version information, might be only in CVS)

maxdb->options -- Set options

Description

Procedural style:

bool maxdb_options ( resource link, int option, mixed value )

Object oriented style (method)

class maxdb {

bool options ( int option, mixed value )

}

maxdb_options() can be used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().

The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see http://dev.mysql.com/doc/maxdb/ The parameter option can be one of the following values:

Table 1. Valid options

Name | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_init(), maxdb_real_connect()

Example

See maxdb_real_connect().

Prev | Home | Next
maxdb_num_rows | Up | maxdb_param_count


maxdb_param_count

(PECL)

maxdb_param_count -- Alias of maxdb_stmt_param_count()

Description

This function is an alias of: maxdb_stmt_param_count().

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.

Prev | Home | Next
maxdb_options | Up | maxdb_ping


maxdb_ping

(PECL)

maxdb_ping

(no version information, might be only in CVS)

maxdb->ping -- Pings a server connection, or tries to reconnect if the connection has gone down

Description

Procedural style:

bool maxdb_ping ( resource link )

Object oriented style (method):

class maxdb {

bool ping ( void )

}

Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Return values

Returns TRUE on success or FALSE on failure.

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if ($maxdb-&#62;ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb-&#62;error);
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if (maxdb_ping($link)) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Our connection is ok!

Prev | Home | Next
maxdb_param_count | Up | maxdb_prepare


maxdb_prepare

(PECL)

maxdb_prepare

(no version information, might be only in CVS)

maxdb->prepare -- Prepare a SQL statement for execution

Description

Procedure style:

resource maxdb_prepare ( resource link, string query )

Object oriented style (method)

class stmt {

resource prepare ( string query )

}

maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

Note: You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

maxdb_prepare() returns a statement resource or FALSE if an error occured.

See Also

maxdb_stmt_execute(),
maxdb_stmt_fetch(),
maxdb_stmt_bind_param(),
maxdb_stmt_bind_result(),
maxdb_stmt_close()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = $maxdb-&#62;prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt-&#62;bind_param("s", $city);

   /* execute query */
   $stmt-&#62;execute();

   /* bind result variables */
   $stmt-&#62;bind_result($district);

   /* fetch value */
   $stmt-&#62;fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = maxdb_prepare($link, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

  /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Rosemont is in district IL

Prev | Home | Next
maxdb_ping | Up | maxdb_query


maxdb_query

(PECL)

maxdb_query

(no version information, might be only in CVS)

maxdb->query -- Performs a query on the database

Description

Procedural style:

mixed maxdb_query ( resource link, string query [, int resultmode] )

Object oriented style (method):

class maxdb {

mixed query ( string query )

}

The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Return values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

See also

maxdb_real_query(),
maxdb_multi_query(),
maxdb_free_result()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if ($maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb-&#62;query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result-&#62;num_rows);

   /* free result set */
   $result-&#62;close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb-&#62;query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result-&#62;close();
}

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if (maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = maxdb_query($link, "SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", maxdb_num_rows($result));

   /* free result set */
   maxdb_free_result($result);
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = maxdb_query($link, "SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   maxdb_free_result($result);
}

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Table mycity successfully created.
Select returned 25 rows.

Prev | Home | Next
maxdb_prepare | Up | maxdb_real_connect


maxdb_real_connect

(PECL)

maxdb_real_connect

(no version information, might be only in CVS)

maxdb->real_connect -- Opens a connection to a MaxDB server

Description

Procedural style

bool maxdb_real_connect ( resource link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

Object oriented style (method)

class maxdb {

bool real_connect ( [string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname.

This function differs from maxdb_connect():

  • maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()

  • With function maxdb_options() you can set various options for connection.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_connect(),
maxdb_init(),
maxdb_options(),
maxdb_ssl_set(),
maxdb_close().

Example

Example 1. Object oriented style

&#60;?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb-&#62;options(MAXDB_UNICODE, "FALSE");
$maxdb-&#62;options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb-&#62;real_connect('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", $maxdb-&#62;host_info);

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php

/* create a connection object which is not connected */
$link = maxdb_init();

/* set connection options */
maxdb_options($link, MAXDB_UNICODE, "FALSE");
maxdb_options($link, MAXDB_TIMEOUT, 5);

/* connect to server */
maxdb_real_connect($link, 'localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", maxdb_get_host_info($link));

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Connection: localhost <...>

Prev | Home | Next
maxdb_query | Up | maxdb_real_escape_string


maxdb_real_escape_string

(PECL)

maxdb_real_escape_string

(no version information, might be only in CVS)

maxdb->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

Description

Procedural style:

string maxdb_real_escape_string ( resource link, string escapestr )

Object oriented style (method):

class maxdb {

string real_escape_sring ( string escapestr )

}

This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.

Characters encoded are ', ".

Return values

Returns an escaped string.

See also

maxdb_character_set_name().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb-&#62;query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb-&#62;sqlstate);
}

$city = $maxdb-&#62;real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb-&#62;query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb-&#62;affected_rows);
}

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!maxdb_query($link, "INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", maxdb_sqlstate($link));
}

$city = maxdb_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (maxdb_query($link, "INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", maxdb_affected_rows($link));
}

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

Prev | Home | Next
maxdb_real_connect | Up | maxdb_real_query


maxdb_real_query

(PECL)

maxdb_real_query

(no version information, might be only in CVS)

maxdb->real_query -- Execute an SQL query

Description

Procedural style

bool maxdb_real_query ( resource link, string query )

Object oriented style (method):

class maxdb {

bool real_query ( string query )

}

The maxdb_real_query() is functionally identical with the maxdb_query().

Note: In order to determine if a given query should return a result set or not, see maxdb_field_count().

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_query()
maxdb_store_result()
maxdb_use_result()

Prev | Home | Next
maxdb_real_escape_string | Up | maxdb_report


maxdb_report

(PECL)

maxdb_report -- Enables or disables internal report functions

Description

bool maxdb_report ( int flags )

Example

Example 1. Procedural style

&#60;?php
/* activate reporting */
maxdb_report(MAXDB_REPORT_ERROR);

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* this query should report an error */
$result = maxdb_query($link,"SELECT Name FROM Nonexistingtable WHERE population &#62; 50000");

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>

Prev | Home | Next
maxdb_real_query | Up | maxdb_rollback


maxdb_rollback

(PECL)

maxdb_rollback

(no version information, might be only in CVS)

maxdb->rollback -- Rolls back current transaction

Description

bool maxdb_rollback ( resource link )

class maxdb {

bool rollback ( void )

}

Rollbacks the current transaction for the database specified by the link parameter.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_commit() maxdb_autocommit()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
$maxdb-&#62;autocommit(FALSE);

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb-&#62;commit();

/* delete all rows */
$maxdb-&#62;query("DELETE FROM temp.mycity");

if ($result = $maxdb-&#62;query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result-&#62;fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result-&#62;close();
}

/* Rollback */
$maxdb-&#62;rollback();

if ($result = $maxdb-&#62;query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result-&#62;fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result-&#62;close();
}

/* Drop table myCity */
$maxdb-&#62;query("DROP TABLE temp.mycity");

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
maxdb_autocommit($link, FALSE);

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
maxdb_commit($link);

/* delete all rows */
maxdb_query($link, "DELETE FROM temp.mycity");

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Rollback */
maxdb_rollback($link);

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Drop table myCity */
maxdb_query($link, "DROP TABLE temp.mycity");

maxdb_close($link);
?&#62;

The above examples would produce the following output:

0 rows in table mycity.
25 rows in table mycity (after rollback).

Prev | Home | Next
maxdb_report | Up | maxdb_rpl_parse_enabled


maxdb_rpl_parse_enabled

(PECL)

maxdb_rpl_parse_enabled -- Check if RPL parse is enabled

Description

int maxdb_rpl_parse_enabled ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_rollback | Up | maxdb_rpl_probe


maxdb_rpl_probe

(PECL)

maxdb_rpl_probe -- RPL probe

Description

bool maxdb_rpl_probe ( resource link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_rpl_parse_enabled | Up | maxdb_rpl_query_type


maxdb_rpl_query_type

(PECL)

maxdb_rpl_query_type

(no version information, might be only in CVS)

maxdb->rpl_query_type -- Returns RPL query type

Description

int maxdb_rpl_query_type ( resource link )

Object oriented style (method)

class maxdb {

int rpl_query_type ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_rpl_probe | Up | maxdb_select_db


maxdb_select_db

(PECL)

maxdb_select_db

(no version information, might be only in CVS)

maxdb->select_db -- Selects the default database for database queries

Description

bool maxdb_select_db ( resource link, string dbname )

The maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.

Note: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in maxdb_connect().

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_connect() maxdb_real_connect()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = $maxdb-&#62;query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result-&#62;fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result-&#62;close();
}

/* change db to non existing db */
$maxdb-&#62;select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb-&#62;query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result-&#62;fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result-&#62;close();
}

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

/* change db to non existing db */
maxdb_select_db($link, "XXXXXXXX");

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Default database is <...>.

Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...>

Warning: maxdb_query(): -10821 Session not connected [] <...>

Warning: maxdb_close(): -10821 Session not connected [] <...>

Prev | Home | Next
maxdb_rpl_query_type | Up | maxdb_send_long_data


maxdb_send_long_data

(PECL)

maxdb_send_long_data -- Alias of maxdb_stmt_send_long_data()

Description

This function is an alias of: maxdb_stmt_send_long_data().

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.

Prev | Home | Next
maxdb_select_db | Up | maxdb_send_query


maxdb_send_query

(PECL)

maxdb_send_query

(no version information, might be only in CVS)

maxdb->send_query -- Send the query and return

Description

bool maxdb_send_query ( resource link, string query )

Object oriented style (method)

class maxdb {

bool send_query ( string query )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_send_long_data | Up | maxdb_server_end


maxdb_server_end

(PECL)

maxdb_server_end -- Shut down the embedded server

Description

void maxdb_server_end ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_send_query | Up | maxdb_server_init


maxdb_server_init

(PECL)

maxdb_server_init -- Initialize embedded server

Description

bool maxdb_server_init ( [array server [, array groups]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_server_end | Up | maxdb_set_opt


maxdb_set_opt

(PECL)

maxdb_set_opt -- Alias of maxdb_options()

Description

This function is an alias of: maxdb_options().

Prev | Home | Next
maxdb_server_init | Up | maxdb_sqlstate


maxdb_sqlstate

(PECL)

maxdb_sqlstate

(no version information, might be only in CVS)

maxdb->sqlstate -- Returns the SQLSTATE error from previous MaxDB operation

Description

Procedural style:

string maxdb_sqlstate ( resource link )

Object oriented style (property):

class maxdb {

string sqlstate

}

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Note: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Return values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

See also

maxdb_errno(), maxdb_error()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!$maxdb-&#62;query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb-&#62;sqlstate);
}

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!maxdb_query($link, "CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", maxdb_sqlstate($link));
}

maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

Prev | Home | Next
maxdb_set_opt | Up | maxdb_ssl_set


maxdb_ssl_set

(PECL)

maxdb_ssl_set

(no version information, might be only in CVS)

maxdb->ssl_set -- Used for establishing secure connections using SSL

Description

Procedural style:

bool maxdb_ssl_set ( resource link, string key, string cert, string ca, string capath, string cipher )

Object oriented style (method):

class maxdb {

bool ssl_set ( string key, string cert, string ca, string capath, string cipher )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_sqlstate | Up | maxdb_stat


maxdb_stat

(PECL)

maxdb_stat

(no version information, might be only in CVS)

maxdb->stat -- Gets the current system status

Description

Procedural style:

string maxdb_stat ( resource link )

Object oriented style (method):

class maxdb {

string maxdb->stat ( void )

}

maxdb_stat() returns a string containing several information about the MaxDB server running.

Return values

A string describing the server status. FALSE if an error occurred.

See also

maxdb_get_server_info()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("System status: %s\n", $maxdb-&#62;stat());

$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("System status: %s\n", maxdb_stat($link));

maxdb_close($link);
?&#62;

The above examples would produce the following output:

System status: Kernel    7<...>

Prev | Home | Next
maxdb_ssl_set | Up | maxdb_stmt_affected_rows


maxdb_stmt_affected_rows

(PECL)

maxdb_stmt_affected_rows

(no version information, might be only in CVS)

maxdb_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Procedural style :

int maxdb_stmt_affected_rows ( resource stmt )

Object oriented style (property):

class stmt {

int affected_rows

}

maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.

See also

maxdb_stmt_num_rows(), maxdb_prepare()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt-&#62;bind_param("s", $code);

   /* execute statement */
   $stmt-&#62;execute();

   printf("rows inserted: %d\n", $stmt-&#62;affected_rows);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = maxdb_prepare($link, $query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   maxdb_stmt_bind_param($stmt, "s", $code);

   /* execute statement */
   maxdb_stmt_execute($stmt);

   printf("rows inserted: %d\n", maxdb_stmt_affected_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

rows inserted: 4

Prev | Home | Next
maxdb_stat | Up | maxdb_stmt_bind_param


maxdb_stmt_bind_param

(PECL)

maxdb_stmt_bind_param

(no version information, might be only in CVS)

stmt->bind_param -- Binds variables to a prepared statement as parameters

Description

Procedural style:

bool maxdb_stmt_bind_param ( resource stmt, string types, mixed &var1 [, mixed &...] )

Object oriented style (method):

class stmt {

bool bind_param ( string types, mixed &var1 [, mixed &...] )

}

Procedural style (extended syntax):

bool maxdb_stmt_bind_param ( resource stmt, string types, array &var )

Object oriented style (method) (extended syntax):

class stmt {

bool bind_param ( string types, array &var )

}

maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.

The extended syntax of maxdb_stmt_bind_param() allows to give the parameters as an array instead of a variable list of PHP variables to the function. If the array variable has not been used before calling maxdb_stmt_bind_param(), it has to be initialized as an emtpy array. See the examples how to use maxdb_stmt_bind_param() with extended syntax.

Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.

If a variable bound as INTO variable to a SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

Table 1. Type specification chars

Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packages

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_stmt_bind_result(),
maxdb_stmt_execute(),
maxdb_stmt_fetch(),
maxdb_prepare(),
maxdb_stmt_send_long_data(),
maxdb_stmt_errno(),
maxdb_stmt_error()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb-&#62;prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt-&#62;bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt-&#62;execute();

printf("%d Row inserted.\n", $stmt-&#62;affected_rows);

/* close statement and connection */
$stmt-&#62;close();

/* Clean up table CountryLanguage */
$maxdb-&#62;query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb-&#62;affected_rows);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query ($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query ($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = maxdb_prepare($link, "INSERT INTO temp.mycity VALUES (?, ?, ?)");
maxdb_stmt_bind_param($stmt, 'sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
maxdb_stmt_execute($stmt);

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

/* close statement and connection */
maxdb_stmt_close($stmt);

/* Clean up table CountryLanguage */
maxdb_query($link, "DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", maxdb_affected_rows($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

1 Row inserted.
1 Row deleted.

Example 3. Procedural style (SELECT INTO)

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT price INTO ? FROM hotel.room where hno = ? and type = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$hno = "50";
$rtype = "suite";

maxdb_stmt_bind_param($stmt, 'dss', $price, $hno, $rtype);
maxdb_stmt_execute($stmt);

printf ("%f\n", $price);

maxdb_stmt_close ($stmt);
?&#62;

The above examples would produce the following output:

21.600000

Example 4. Procedural style (DB procedure)

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?&#62;

The above examples would produce the following output:

a

Example 5. Object oriented style (extended syntax)

&#60;?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb-&#62;prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");

$arr = array();

$stmt-&#62;bind_param('iss', $arr);

$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';

/* execute prepared statement */
$stmt-&#62;execute();

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

$arr[0] = 22222;
$arr[1] = 'New Orleans';
$arr[2] = 'LA';

/* execute prepared statement */
$stmt-&#62;execute();

printf("%d Row inserted.\n", $stmt-&#62;affected_rows);

/* close statement and connection */
$stmt-&#62;close();

$result = $maxdb-&#62;query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
  while ($row = $result-&#62;fetch_row()) {
    printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
  }
}

/* Clean up table CountryLanguage */
$maxdb-&#62;query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb-&#62;query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb-&#62;affected_rows);

/* close connection */
$maxdb-&#62;close();
?&#62;

The above examples would produce the following output:

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

Prev | Home | Next
maxdb_stmt_affected_rows | Up | maxdb_stmt_bind_result


maxdb_stmt_bind_result

(PECL)

maxdb_stmt_bind_result

(no version information, might be only in CVS)

stmt->bind_result -- Binds variables to a prepared statement for result storage

Description

Procedural style:

bool maxdb_stmt_bind_result ( resource stmt, mixed &var1 [, mixed &...] )

Object oriented style (method):

class stmt {

bool bind_result ( mixed &var1 [, mixed &...] )

}

maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ....

Note: Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time maxdb_stmt_fetch() is called.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_stmt_bind_param(),
maxdb_stmt_execute(),
maxdb_stmt_fetch(),
maxdb_prepare(),
maxdb_stmt_prepare(),
maxdb_stmt_init(),
maxdb_stmt_errno(),
maxdb_stmt_error()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = $maxdb-&#62;prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt-&#62;execute();

   /* bind variables to prepared statement */
   $stmt-&#62;bind_result($col1, $col2);

   /* fetch values */
   while ($stmt-&#62;fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt-&#62;close();
}
/* close connection */
$maxdb-&#62;close();

?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = maxdb_prepare($link, "SELECT zip, name FROM hotel.city ORDER BY name")) {
   maxdb_stmt_execute($stmt);

   /* bind variables to prepared statement */
   maxdb_stmt_bind_result($stmt, $col1, $col2);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

12203 Albany
60601 Chicago
60615 Chicago
45211 Cincinnati
33575 Clearwater
75243 Dallas
32018 Daytona Beach
33441 Deerfield Beach
48226 Detroit
90029 Hollywood
92714 Irvine
90804 Long Beach
11788 Long Island
90018 Los Angeles
70112 New Orleans
10019 New York
10580 New York
92262 Palm Springs
97213 Portland
60018 Rosemont
95054 Santa Clara
20903 Silver Spring
20005 Washington
20019 Washington
20037 Washington

Prev | Home | Next
maxdb_stmt_bind_param | Up | maxdb_stmt_close_long_data


maxdb_stmt_close_long_data

(PECL)

maxdb_stmt_close_long_data

(no version information, might be only in CVS)

stmt->close_long_data -- Ends a sequence of maxdb_stmt_send_long_data()

Description

Procedural style:

bool maxdb_stmt_close_long_data ( resource stmt, int param_nr )

Object oriented style (method):

class maxdb_stmt {

bool maxdb_stmt->close_long_data ( void )

}

This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().

param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_prepare(), maxdb_stmt_bind_param()

Prev | Home | Next
maxdb_stmt_bind_result | Up | maxdb_stmt_close


maxdb_stmt_close

(PECL)

maxdb_stmt_close

(no version information, might be only in CVS)

maxdb_stmt->close -- Closes a prepared statement

Description

Procedural style:

bool maxdb_stmt_close ( resource stmt )

Object oriented style (method):

class maxdb_stmt {

bool maxdb_stmt->close ( void )

}

Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_prepare(),

Prev | Home | Next
maxdb_stmt_close_long_data | Up | maxdb_stmt_data_seek


maxdb_stmt_data_seek

(PECL)

maxdb_stmt_data_seek

(no version information, might be only in CVS)

stmt->data_seek -- Seeks to an arbitray row in statement result set

Description

Procedural style:

bool maxdb_stmt_data_seek ( resource statement, int offset )

Object oriented style (method):

class stmt {

bool data_seek ( int offset )

}

The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_prepare()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* execute query */
   $stmt-&#62;execute();

   /* bind result variables */
   $stmt-&#62;bind_result($name, $code);

   /* store result */
   $stmt-&#62;store_result();

   /* seek to row no. 5 */
   $stmt-&#62;data_seek(5);

   /* fetch values */
   $stmt-&#62;fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* store result */
   maxdb_stmt_store_result($stmt);

   /* seek to row no. 5 */
   maxdb_stmt_data_seek($stmt, 5);

   /* fetch values */
   maxdb_stmt_fetch($stmt);

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

City: Dallas  Zip: 75243

Prev | Home | Next
maxdb_stmt_close | Up | maxdb_stmt_errno


maxdb_stmt_errno

(PECL)

maxdb_stmt_errno

(no version information, might be only in CVS)

maxdb_stmt->errno -- Returns the error code for the most recent statement call

Description

Procedural style :

int maxdb_stmt_errno ( resource stmt )

Object oriented style (property):

class stmt {

int errno

}

For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.

Note: For possible error codes see documentation of SQLDBC: http://dev.mysql.com/doc/maxdb/.

Return values

An error code value. Zero means no error occurred.

See also

maxdb_stmt_error(), maxdb_stmt_sqlstate()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* drop table */
   $maxdb-&#62;query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt-&#62;execute();

   printf("Error: %d.\n", $stmt-&#62;errno);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %d.\n", maxdb_stmt_errno($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

Prev | Home | Next
maxdb_stmt_data_seek | Up | maxdb_stmt_error


maxdb_stmt_error

(PECL)

maxdb_stmt_error

(no version information, might be only in CVS)

maxdb_stmt->error -- Returns a string description for last statement error

Description

Procedural style:

string maxdb_stmt_error ( resource stmt )

Object oriented style (property):

class stmt {

string error

}

For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Return values

A string that describes the error. An empty string if no error occurred.

See also

maxdb_stmt_errno(), maxdb_stmt_sqlstate()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* drop table */
   $maxdb-&#62;query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt-&#62;execute();

   printf("Error: %s.\n", $stmt-&#62;error);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_error($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

Prev | Home | Next
maxdb_stmt_errno | Up | maxdb_stmt_execute


maxdb_stmt_execute

(PECL)

maxdb_stmt_execute

(no version information, might be only in CVS)

stmt->execute -- Executes a prepared Query

Description

Procedural style:

bool maxdb_stmt_execute ( resource stmt )

Object oriented style (method):

class stmt {

bool execute ( void )

}

The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropiate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.

Note: When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_prepare() maxdb_stmt_bind_param().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb-&#62;prepare($query);

$stmt-&#62;bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
$stmt-&#62;execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
$stmt-&#62;execute();

/* close statement */
$stmt-&#62;close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb-&#62;query($query)) {
   while ($row = $result-&#62;fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result-&#62;close();
}

/* remove table */
$maxdb-&#62;query("DROP TABLE temp.mycity");

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = maxdb_prepare($link, $query);

maxdb_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
maxdb_stmt_execute($stmt);

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
maxdb_stmt_execute($stmt);

/* close statement */
maxdb_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = maxdb_query($link, $query)) {
   while ($row = maxdb_fetch_row($result)) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   maxdb_free_result($result);
}

/* remove table */
maxdb_query($link, "DROP TABLE temp.mycity");

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

Prev | Home | Next
maxdb_stmt_error | Up | maxdb_stmt_fetch


maxdb_stmt_fetch

(PECL)

maxdb_stmt_fetch

(no version information, might be only in CVS)

stmt->fetch -- Fetch results from a prepared statement into the bound variables

Description

Procedural style:

bool maxdb_stmt_fetch ( resource stmt )

Object oriented style (method):

class stmt {

bool fetch ( void )

}

maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().

Note: Note that all columns must be bound by the application before calling maxdb_stmt_fetch().

Return values

Table 1. Return values

Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occured
NULL | No more rows/data exists

See also

maxdb_prepare(),
maxdb_stmt_errno(),
maxdb_stmt_error(),
maxdb_stmt_bind_result()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = $maxdb-&#62;prepare($query)) {

   /* execute statement */
   $stmt-&#62;execute();

   /* bind result variables */
   $stmt-&#62;bind_result($name, $code);

   /* fetch values */
   while ($stmt-&#62;fetch()) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = maxdb_prepare($link, $query)) {

   /* execute statement */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

12203 (Albany)
60601 (Chicago)
60615 (Chicago)
45211 (Cincinnati)
33575 (Clearwater)
75243 (Dallas)
32018 (Daytona Beach)
33441 (Deerfield Beach)
48226 (Detroit)
90029 (Hollywood)
92714 (Irvine)
90804 (Long Beach)
11788 (Long Island)
90018 (Los Angeles)
70112 (New Orleans)
10019 (New York)
10580 (New York)
92262 (Palm Springs)
97213 (Portland)
60018 (Rosemont)
95054 (Santa Clara)
20903 (Silver Spring)
20005 (Washington)
20019 (Washington)
20037 (Washington)

Prev | Home | Next
maxdb_stmt_execute | Up | maxdb_stmt_free_result


maxdb_stmt_free_result

(PECL)

maxdb_stmt_free_result

(no version information, might be only in CVS)

stmt->free_result -- Frees stored result memory for the given statement handle

Description

Procedural style:

void maxdb_stmt_free_result ( resource stmt )

Object oriented style (method):

class stmt {

void free_result ( void )

}

The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().

Return Values

This function doesn't return any value.

See Also

maxdb_stmt_store_result()

Prev | Home | Next
maxdb_stmt_fetch | Up | maxdb_stmt_init


maxdb_stmt_init

(PECL)

maxdb_stmt_init

(no version information, might be only in CVS)

maxdb->stmt_init -- Initializes a statement and returns an resource for use with maxdb_stmt_prepare

Description

Procedural style :

resource maxdb_stmt_init ( resource link )

Object oriented style (property):

class maxdb {

object stmt_init ( void )

}

Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().

Note: Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.

Return Values

Returns an resource.

See Also

maxdb_stmt_prepare()

Prev | Home | Next
maxdb_stmt_free_result | Up | maxdb_stmt_num_rows


maxdb_stmt_num_rows

(PECL)

maxdb_stmt_num_rows

(no version information, might be only in CVS)

stmt->num_rows -- Return the number of rows in statements result set

Description

Procedural style :

int maxdb_stmt_num_rows ( resource stmt )

Object oriented style (property):

class stmt {

int num_rows

}

Returns the number of rows in the result set.

Return values

An integer representing the number of rows in result set.

See also

maxdb_stmt_affected_rows(),
maxdb_prepare(),
maxdb_stmt_store_result()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* execute query */
   $stmt-&#62;execute();

   /* store result */
   $stmt-&#62;store_result();

   printf("Number of rows: %d.\n", $stmt-&#62;num_rows);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Number of rows: 25.

Prev | Home | Next
maxdb_stmt_init | Up | maxdb_stmt_param_count


maxdb_stmt_param_count

(PECL)

maxdb_stmt_param_count

(no version information, might be only in CVS)

stmt->param_count -- Returns the number of parameter for the given statement

Description

Procedural style:

int maxdb_stmt_param_count ( resource stmt )

Object oriented style (property):

class stmt {

int param_count

}

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Return Values

returns an integer representing the number of parameters.

See Also

maxdb_prepare()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = $maxdb-&#62;prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt-&#62;param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = maxdb_prepare($link, "SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = maxdb_stmt_param_count($stmt);
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Statement has 2 markers.

Prev | Home | Next
maxdb_stmt_num_rows | Up | maxdb_stmt_prepare


maxdb_stmt_prepare

(PECL)

maxdb_stmt_prepare

(no version information, might be only in CVS)

stmt->prepare -- Prepare a SQL statement for execution

Description

Procedure style:

bool maxdb_stmt_prepare ( resource stmt, string query )

Object oriented style (method)

class stmt {

mixed prepare ( string query )

}

maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.

Note: You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_stmt_init(),
maxdb_stmt_execute(),
maxdb_stmt_fetch(),
maxdb_stmt_bind_param(),
maxdb_stmt_bind_result(),
maxdb_stmt_close()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt =  $maxdb-&#62;stmt_init();
if ($stmt-&#62;prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt-&#62;bind_param("s", $city);

   /* execute query */
   $stmt-&#62;execute();

   /* bind result variables */
   $stmt-&#62;bind_result($district);

   /* fetch value */
   $stmt-&#62;fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt = maxdb_stmt_init($link);
if (maxdb_stmt_prepare($stmt, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Portland is in district OR

Prev | Home | Next
maxdb_stmt_param_count | Up | maxdb_stmt_reset


maxdb_stmt_reset

(PECL)

maxdb_stmt_reset

(no version information, might be only in CVS)

stmt->reset -- Resets a prepared statement

Description

Procedural style:

bool maxdb_stmt_reset ( resource stmt )

Object oriented style (method):

class stmt {

bool reset ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
maxdb_stmt_prepare | Up | maxdb_stmt_result_metadata


maxdb_stmt_result_metadata

(PECL)

maxdb_stmt_result_metadata -- Returns result set metadata from a prepared statement

Description

Procedural style:

resource maxdb_stmt_result_metadata ( resource stmt )

Object oriented style (method):

class stmt {

resource result_metadata ( void )

}

If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.

Note: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • maxdb_num_fields()

  • maxdb_fetch_field()

  • maxdb_fetch_field_direct()

  • maxdb_fetch_fields()

  • maxdb_field_count()

  • maxdb_field_seek()

  • maxdb_field_tell()

  • maxdb_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()

Note: The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().

Return Values

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.

See also:

maxdb_prepare(), maxdb_free_result()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb-&#62;query("CREATE TABLE temp.friends (id int, name varchar(20))");

$maxdb-&#62;query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb-&#62;query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb-&#62;prepare("SELECT id, name FROM temp.friends");
$stmt-&#62;execute();

/* get resultset for metadata */
$result = $stmt-&#62;result_metadata();

/* retrieve field information from metadata result set */
$field = $result-&#62;fetch_field();

printf("Fieldname: %s\n", $field-&#62;name);

/* close resultset */
$result-&#62;close();

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_query($link, "CREATE TABLE temp.friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO temp.friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = maxdb_prepare($link, "SELECT id, name FROM temp.friends");
maxdb_stmt_execute($stmt);

/* get resultset for metadata */
$result = maxdb_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = maxdb_fetch_field($result);

printf("Fieldname: %s\n", $field-&#62;name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Fieldname: ID

Prev | Home | Next
maxdb_stmt_reset | Up | maxdb_stmt_send_long_data


maxdb_stmt_send_long_data

(PECL)

maxdb_stmt_send_long_data

(no version information, might be only in CVS)

stmt->send_long_data -- Send data in blocks

Description

Procedural style:

bool maxdb_stmt_send_long_data ( resource stmt, int param_nr, string data )

Object oriented style (method)

class stmt {

bool stmt_send_long_data ( int param_nr, string data )

}

Allows to send parameter data to the server in pieces (or chunks). This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.

Note: For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

maxdb_prepare(), maxdb_stmt_bind_param()

Prev | Home | Next
maxdb_stmt_result_metadata | Up | maxdb_stmt_sqlstate


maxdb_stmt_sqlstate

(PECL)

maxdb_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation

Description

string maxdb_stmt_sqlstate ( resource stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Note: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Return values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

See also

maxdb_stmt_errno(), maxdb_stmt_error()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb-&#62;query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* drop table */
   $maxdb-&#62;query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt-&#62;execute();

   printf("Error: %s.\n", $stmt-&#62;sqlstate);

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_sqlstate($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

Prev | Home | Next
maxdb_stmt_send_long_data | Up | maxdb_stmt_store_result


maxdb_stmt_store_result

(PECL)

maxdb_stmt_store_result

(no version information, might be only in CVS)

maxdb->store_result -- Transfers a result set from a prepared statement

Description

Procedural style:

bool maxdb_stmt_store_result ( resource stmt )

Object oriented style (method):

class maxdb {

object store_result ( void )

}

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Return values

Returns TRUE on success or FALSE on failure.

See also

maxdb_prepare(),
maxdb_stmt_result_metadata(),
maxdb_fetch()

Example

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb-&#62;prepare($query)) {

   /* execute query */
   $stmt-&#62;execute();

   /* store result */
   $stmt-&#62;store_result();

   printf("Number of rows: %d.\n", $stmt-&#62;num_rows);

   /* free result */
   $stmt-&#62;free_result();

   /* close statement */
   $stmt-&#62;close();
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* free result */
   maxdb_stmt_free_result($stmt);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Number of rows: 25.

Prev | Home | Next
maxdb_stmt_sqlstate | Up | maxdb_store_result


maxdb_store_result

(PECL)

maxdb_store_result

(no version information, might be only in CVS)

maxdb->store_result -- Transfers a result set from the last query

Description

Procedural style:

resource maxdb_store_result ( resource link )

Object oriented style (method):

class maxdb {

object store_result ( void )

}

This function has no functionally effect.

Return values

Returns a result resource or FALSE if an error occurred.

See also

maxdb_real_query(), maxdb_use_result().

Example

See maxdb_multi_query().

Prev | Home | Next
maxdb_stmt_store_result | Up | maxdb_thread_id


maxdb_thread_id

(PECL)

maxdb_thread_id

(no version information, might be only in CVS)

maxdb->thread_id -- Returns the thread ID for the current connection

Description

Procedural style:

int maxdb_thread_id ( resource link )

Object oriented style (property):

class maxdb {

int thread_id

}

The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Note: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

Return values

maxdb_thread_id() returns the Thread ID for the current connection.

See also

maxdb_kill()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb-&#62;thread_id;

/* Kill connection */
$maxdb-&#62;kill($thread_id);

/* This should produce an error */
if (!$maxdb-&#62;query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb-&#62;error);
   exit;
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

Prev | Home | Next
maxdb_store_result | Up | maxdb_thread_safe


maxdb_thread_safe

(no version information, might be only in CVS)

maxdb_thread_safe -- Returns whether thread safety is given or not

Description

Procedural style:

bool maxdb_thread_safe ( void )

maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.

Return values

TRUE if the client library is thread-safe, otherwise FALSE.

Prev | Home | Next
maxdb_thread_id | Up | maxdb_use_result


maxdb_use_result

(PECL)

maxdb_use_result

(no version information, might be only in CVS)

maxdb->use_result -- Initiate a result set retrieval

Description

Procedural style:

resource maxdb_use_result ( resource link )

Object oriented style (method):

class maxdb {

resource use_result ( void )

}

maxdb_use_result() has no effect.

Return values

Returns result or FALSE in case of error.

See also

maxdb_real_query(), maxdb_store_result().

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if ($maxdb-&#62;multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb-&#62;use_result()) {
           while ($row = $result-&#62;fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result-&#62;close();
       }
       /* print divider */
       if ($maxdb-&#62;more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb-&#62;next_result());
}

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_use_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

a

Prev | Home | Next
maxdb_thread_safe | Up | maxdb_warning_count


maxdb_warning_count

(PECL)

maxdb_warning_count

(no version information, might be only in CVS)

maxdb->warning_count -- Returns the number of warnings from the last query for the given link

Description

Procedural style:

int maxdb_warning_count ( resource link )

Object oriented style (property):

class maxdb {

int warning_count

}

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Return values

Number of warnings or zero if there are no warnings.

See also

maxdb_errno(),
maxdb_error(),
maxdb_sqlstate()

Example

Example 1. Object oriented style

&#60;?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb-&#62;query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb-&#62;query($query);

printf ("Number of warning: %d\n", $maxdb-&#62;warning_count);

/* close connection */
$maxdb-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable long city name in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

maxdb_query($link, $query);

printf ("Number of warning: %d\n", maxdb_warning_count($link));

/* close connection */
maxdb_close($link);
?&#62;

The above examples would produce the following output:

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

Prev | Home | Next
maxdb_use_result | Up | MCAL Functions


Multibyte String Functions

PHP Manual
Prev Next

XCIV. Multibyte String Functions

Introduction

While there are many languages in which every necessary character can be represented by a one-to-one mapping to an 8-bit value, there are also several languages which require so many characters for written communication that they cannot be contained within the range a mere byte can code (A byte is made up of eight bits. Each bit can contain only two distinct values, one or zero. Because of this, a byte can only represent 256 unique values (two to the power of eight)). Multibyte character encoding schemes were developed to express more than 256 characters in the regular bytewise coding system.

When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.

mbstring provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs. mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below).

PHP Character Encoding Requirements

Encodings of the following types are safely used with PHP.

  • A singlebyte encoding,

    • which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.

  • A multibyte encoding,

    • which has ASCII-compatible mappings for the characters in range of 00h to 7fh.

    • which don't use ISO2022 escape sequences.

    • which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.

These are examples of character encodings that are unlikely to work with PHP.

JIS, SJIS, ISO-2022-JP, BIG-5

Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.

Note: It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.

Note: If you are connecting to a database with PHP, it is recommended that you use the same character encoding for both the database and the internal encoding for ease of use and better performance.

If you are using PostgreSQL, the character encoding used in the database and the one used in PHP may differ as it supports automatic character set conversion between the backend and the frontend.

Installation

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring: Enable mbstring functions. This option is required to use mbstring functions.

    libmbfl is necesarry for mbstring. libmbfl is bundled with mbstring. If libmbfl is already installed on the system, --with-libmbfl[=DIR] can be specified to use the installed library.

    As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese.

    For PHP 4.3.3 or before,
To enable that feature, you will have to supply either one of the
following options to the LANG parameter
of --enable-mbstring=LANG;
--enable-mbstring=cn for Simplified Chinese support,
--enable-mbstring=tw for Traditional Chinese support,
--enable-mbstring=kr for Korean support,
--enable-mbstring=ru for Russian support, and
--enable-mbstring=ja for Japanese support (default).
 To enable all supported encoding, use --enable-mbstring=all.

    Note: As of PHP 4.3.4, all supported encoding by libmbfl is enabled with --enable-mbstring.

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    Note: As of PHP 4.3.0, the option --enable-mbstr-enc-trans was eliminated and replaced with the runtime setting mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --disable-mbregex: Disable regular expression functions with multibyte character support.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. mbstring configuration options

Name | Default | Changeable | Changelog
mbstring.language | "neutral" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.2.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.
For the definition of the PHP_INI_* constants, please refer to ini_set().

Here's a short explanation of the configuration directives.

mbstring.language string

The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini

mbstring.encoding_translation boolean

Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.

mbstring.internal_encoding string

Defines the default internal character encoding.

mbstring.http_input string

Defines the default HTTP input character encoding.

mbstring.http_output string

Defines the default HTTP output character encoding.

mbstring.detect_order string

Defines default character code detection order. See also mb_detect_order().

mbstring.substitute_character string

Defines character to substitute for invalid character encoding.

mbstring.func_overload string

Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.

mbstring.strict_detection boolean

Enables the strict encoding detection.

According to the HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.

Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.

Example 1. php.ini setting examples

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion.
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Example 2. php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

Example 3. php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto

;; Convert to SJIS
mbstring.http_output = SJIS

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

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.

MB_OVERLOAD_MAIL (integer)

MB_OVERLOAD_STRING (integer)

MB_OVERLOAD_REGEX (integer)

HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

Note: In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.

Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.

  • HTTP Input

    There is no way to control HTTP input character conversion from a PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    Example 4. Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
    mbstring.http_input = pass
    ;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
    mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

  • HTTP Output

    There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as the ob_start callback function.

    Note: PHP3-i18n users should note that mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using an output buffer.

Example 5. php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

Example 6. Script example

&#60;?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?&#62;

Supported Character Encodings

Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.

The following character encodings are supported in this PHP extension:

  • UCS-4

  • UCS-4BE

  • UCS-4LE

  • UCS-2

  • UCS-2BE

  • UCS-2LE

  • UTF-32

  • UTF-32BE

  • UTF-32LE

  • UTF-16

  • UTF-16BE

  • UTF-16LE

  • UTF-7

  • UTF7-IMAP

  • UTF-8

  • ASCII

  • EUC-JP

  • SJIS

  • eucJP-win

  • SJIS-win

  • ISO-2022-JP

  • JIS

  • ISO-8859-1

  • ISO-8859-2

  • ISO-8859-3

  • ISO-8859-4

  • ISO-8859-5

  • ISO-8859-6

  • ISO-8859-7

  • ISO-8859-8

  • ISO-8859-9

  • ISO-8859-10

  • ISO-8859-13

  • ISO-8859-14

  • ISO-8859-15

  • byte2be

  • byte2le

  • byte4be

  • byte4le

  • BASE64

  • HTML-ENTITIES

  • 7bit

  • 8bit

  • EUC-CN

  • CP936

  • HZ

  • EUC-TW

  • CP950

  • BIG-5

  • EUC-KR

  • UHC (CP949)

  • ISO-2022-KR

  • Windows-1251 (CP1251)

  • Windows-1252 (CP1252)

  • CP866 (IBM866)

  • KOI8-R

Any php.ini entry which accepts an encoding name can also use the values "auto" and "pass". mbstring functions which accept an encoding name can also use the value "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

Function Overloading Feature

You might often find it difficult to get an existing PHP application to work in a given multibyte environment. This happens because most PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.

mbstring supports a 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.

To use function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if it is set to 7, mail, strings and regular expression functions will be overloaded. The list of overloaded functions are shown below.

Table 2. Functions to be overloaded

value of mbstring.func_overload | original function | overloaded function
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
2 | strtolower() | mb_strtolower()
2 | strtoupper() | mb_strtoupper()
2 | substr_count() | mb_substr_count()
4 | ereg() | mb_ereg()
4 | eregi() | mb_eregi()
4 | ereg_replace() | mb_ereg_replace()
4 | eregi_replace() | mb_eregi_replace()
4 | split() | mb_split()

Note: It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.

Basics of Japanese multi-byte encodings

Japanese characters can only be represented by multibyte encodings, and multiple encoding standards are used depending on platform and text purpose. To make matters worse, these encoding standards differ slightly from one another. In order to create a web application which would be usable in a Japanese environment, a developer has to keep these complexities in mind to ensure that the proper character encodings are used.

  • Storage for a character can be up to six bytes

  • Most Japanese multibyte characters appear twice as wide as single-byte characters. These characters are called "zen-kaku" in Japanese, which means "full width". Other, narrower, characters are called "han-kaku", which means "half width". The graphical properties of the characters, however, depends upon the type faces used to display them.

  • Some character encodings use shift(escape) sequences defined in ISO-2022 to switch the code map of the specific code area (00h to 7fh).

  • ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.

  • Webpages created for mobile phone services such as i-mode, Vodafone live!, or EZweb are supposed to use Shift_JIS.

References

Multibyte character encoding schemes and their related issues are fairly complicated, and are beyond the scope of this documentation. Please refer to the following URLs and other resources for further information regarding these topics.

  • Unicode materials

    http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    http://examples.oreilly.com/cjkvinfo/doc/cjk.inf

Summaries of supported encodings

Summaries of supported encodings

Name in the IANA character set registry: ISO-10646-UCS-4

Underlying character set: ISO 10646

Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.

Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.

Name in the IANA character set registry: ISO-10646-UCS-4

Underlying character set: UCS-4

Description: See above.

Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.

Name in the IANA character set registry: ISO-10646-UCS-4

Underlying character set: UCS-4

Description: See above.

Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.

Name in the IANA character set registry: ISO-10646-UCS-2

Underlying character set: UCS-2

Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.

Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.

Name in the IANA character set registry: ISO-10646-UCS-2

Underlying character set: UCS-2

Description: See above.

Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.

Name in the IANA character set registry: ISO-10646-UCS-2

Underlying character set: UCS-2

Description: See above.

Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.

Name in the IANA character set registry: UTF-32

Underlying character set: Unicode

Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.

Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.

Name in the IANA character set registry: UTF-32BE

Underlying character set: Unicode

Description: See above

Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.

Name in the IANA character set registry: UTF-32LE

Underlying character set: Unicode

Description: See above

Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.

Name in the IANA character set registry: UTF-16

Underlying character set: Unicode

Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.

Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.

Name in the IANA character set registry: UTF-16BE

Underlying character set: Unicode

Description: See above.

Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.

Name in the IANA character set registry: UTF-16LE

Underlying character set: Unicode

Description: See above.

Additional note: In contrast to UTF-16, strings are always assumed to be in little endian form.

Name in the IANA character set registry: UTF-8

Underlying character set: Unicode / UCS

Description: Unicode Transformation Format of 8-bit unit width.

Additional note: none

Name in the IANA character set registry: UTF-7

Underlying character set: Unicode

Description: A mail-safe transformation format of Unicode, specified in RFC2152.

Additional note: none

Name in the IANA character set registry: (none)

Underlying character set: Unicode

Description: A variant of UTF-7 which is specialized for use in the IMAP protocol.

Additional note: none

Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII

Underlying character set: ASCII / ISO 646

Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.

Additional note: (none)

Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese

Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990

Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.

Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.

Name in the IANA character set registry: Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS

Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997

Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.

Additional note: For the CP932 codemap, use SJIS-WIN instead.

Name in the IANA character set registry: (none)

Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions

Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.

Additional note: none

Name in the IANA character set registry: Windows-31J / csWindows31J

Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions

Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.

Additional note: (none)

Name in the IANA character set registry: ISO-2022-JP (preferred MIME name) / csISO2022JP

Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983

Description: RFC1468

Additional note: (none)

Name in the IANA character set registry: JIS

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-1

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-2

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-3

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-4

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-5

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-6

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-7

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-8

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-9

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-10

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-13

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-14

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-8859-15

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: byte2be

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: byte2le

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: byte4be

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: byte4le

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: BASE64

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: HTML-ENTITIES

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: 7bit

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: 8bit

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: EUC-CN

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: CP936

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: HZ

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: EUC-TW

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: CP950

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: BIG-5

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: EUC-KR

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: UHC (CP949)

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: ISO-2022-KR

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: Windows-1251 (CP1251)

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: Windows-1252 (CP1252)

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: CP866 (IBM866)

Underlying character set:

Description:

Additional note:

Name in the IANA character set registry: KOI8-R

Underlying character set:

Description:

Additional note:

Table of Contents
mb_check_encoding -- Check if the string is valid for the specified encoding
mb_convert_case -- Perform case folding on a string
mb_convert_encoding -- Convert character encoding
mb_convert_kana -- Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
mb_convert_variables -- Convert character code in variable(s)
mb_decode_mimeheader -- Decode string in MIME header field
mb_decode_numericentity -- Decode HTML numeric string reference to character
mb_detect_encoding -- Detect character encoding
mb_detect_order -- Set/Get character encoding detection order
mb_encode_mimeheader -- Encode string for MIME header
mb_encode_numericentity -- Encode character to HTML numeric string reference
mb_ereg_match -- Regular expression match for multibyte string
mb_ereg_replace -- Replace regular expression with multibyte support
mb_ereg_search_getpos -- Returns start point for next regular expression match
mb_ereg_search_getregs -- Retrieve the result from the last multibyte regular expression match
mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression match
mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte string
mb_ereg_search_regs -- Returns the matched part of multibyte regular expression
mb_ereg_search_setpos -- Set start point of next regular expression match
mb_ereg_search -- Multibyte regular expression match for predefined multibyte string
mb_ereg -- Regular expression match with multibyte support
mb_eregi_replace -- Replace regular expression with multibyte support ignoring case
mb_eregi -- Regular expression match ignoring case with multibyte support
mb_get_info -- Get internal settings of mbstring
mb_http_input -- Detect HTTP input character encoding
mb_http_output -- Set/Get HTTP output character encoding
mb_internal_encoding -- Set/Get internal character encoding
mb_language -- Set/Get current language
mb_list_encodings_alias_names -- Returns an array of all supported alias encodings
mb_list_encodings -- Returns an array of all supported encodings
mb_list_mime_names -- Returns an array or string of all supported mime names
mb_output_handler -- Callback function converts character encoding in output buffer
mb_parse_str -- Parse GET/POST/COOKIE data and set global variable
mb_preferred_mime_name -- Get MIME charset string
mb_regex_encoding -- Returns current encoding for multibyte regex as string
mb_regex_set_options -- Set/Get the default options for mbregex functions
mb_send_mail -- Send encoded mail
mb_split -- Split multibyte string using regular expression
mb_strcut -- Get part of string
mb_strimwidth -- Get truncated string with specified width
mb_stripos -- Finds position of first occurrence of a string within another, case insensitive
mb_stristr -- Finds first occurrence of a string within another, case insensitive
mb_strlen -- Get string length
mb_strpos -- Find position of first occurrence of string in a string
mb_strrchr -- Finds the last occurrence of a character in a string within another
mb_strrichr -- Finds the last occurrence of a character in a string within another, case insensitive
mb_strripos -- Finds position of last occurrence of a string within another, case insensitive
mb_strrpos -- Find position of last occurrence of a string in a string
mb_strstr -- Finds first occurrence of a string within another
mb_strtolower -- Make a string lowercase
mb_strtoupper -- Make a string uppercase
mb_strwidth -- Return width of string
mb_substitute_character -- Set/Get substitution character
mb_substr_count -- Count the number of substring occurrences
mb_substr -- Get part of string

Prev | Home | Next
msql | Up | mb_check_encoding


mb_convert_case

(PHP 4 >= 4.3.0, PHP 5)

mb_convert_case -- Perform case folding on a string

Description

string mb_convert_case ( string str, int mode [, string encoding] )

mb_convert_case() returns case folded version of string converted in the way specified by mode.

mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

The return value is str with the appropriate case folding applied.

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Example 1. mb_convert_case() example

&#60;?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Mary Had A Little Lamb And She Loved It So
?&#62;

See also mb_strtolower(),
mb_strtoupper(),
strtolower(),
strtoupper(),
ucfirst() and
ucwords()

Prev | Home | Next
mb_check_encoding | Up | mb_convert_encoding


mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_encoding -- Convert character encoding

Description

string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )

mb_convert_encoding() converts character encoding of string str from from_encoding to to_encoding.

str : String to be converted.

from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.

Example 1. mb_convert_encoding() example

&#60;?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?&#62;

See also mb_detect_order().

Prev | Home | Next
mb_convert_case | Up | mb_convert_kana


mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_kana -- Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Description

string mb_convert_kana ( string str [, string option [, string encoding]] )

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

Specify with combination of following options. Default value is KV.

Table 1. Applicable Conversion Options

Option | Meaning
r | Convert "zen-kaku" alphabets to "han-kaku"
R | Convert "han-kaku" alphabets to "zen-kaku"
n | Convert "zen-kaku" numbers to "han-kaku"
N | Convert "han-kaku" numbers to "zen-kaku"
a | Convert "zen-kaku" alphabets and numbers to "han-kaku"
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
V | Collapse voiced sound notation and convert them into a character. Use with "K","H"

Example 1. mb_convert_kana() example

&#60;?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?&#62;

Prev | Home | Next
mb_convert_encoding | Up | mb_convert_variables


mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_variables -- Convert character code in variable(s)

Description

string mb_convert_variables ( string to_encoding, mixed from_encoding, mixed &vars [, mixed &...] )

mb_convert_variables() convert character encoding of variables vars in encoding from_encoding to encoding to_encoding. It returns character encoding before conversion for success, FALSE for failure.

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

It from_encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.

vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

Example 1. mb_convert_variables() example

&#60;?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?&#62;

Prev | Home | Next
mb_convert_kana | Up | mb_decode_mimeheader


mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_mimeheader -- Decode string in MIME header field

Description

string mb_decode_mimeheader ( string str )

mb_decode_mimeheader() decodes encoded-word string str in MIME header.

It returns decoded string in internal character encoding.

See also mb_encode_mimeheader().

Prev | Home | Next
mb_convert_variables | Up | mb_decode_numericentity


mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_numericentity -- Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string str, array convmap [, string encoding] )

Convert numeric string reference of string str in specified block to character. It returns converted string.

convmap is array to specifies code area to convert.

encoding is character encoding. If it is omitted, internal character encoding is used.

Example 1. convmap example

$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.

See also mb_encode_numericentity().

Prev | Home | Next
mb_decode_mimeheader | Up | mb_detect_encoding


mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_encoding -- Detect character encoding

Description

string mb_detect_encoding ( string str [, mixed encoding_list [, bool strict]] )

mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.

encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

strict specifies whether to use the strict encoding detection or not. Default is FALSE.

Example 1. mb_detect_encoding() example

&#60;?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?&#62;

See also mb_detect_order().

Prev | Home | Next
mb_decode_numericentity | Up | mb_detect_order


mb_detect_order

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_order -- Set/Get character encoding detection order

Description

mixed mb_detect_order ( [mixed encoding_list] )

mb_detect_order() sets automatic character encoding detection order to encoding_list. It returns TRUE for success, FALSE for failure.

encoding_list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding_list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

Note: mbstring currently implements following encoding detection filters. If there is an invalid byte sequence for following encoding, encoding detection will fail.

Note: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

Example 1. Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Example 2. mb_detect_order() examples

&#60;?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());
?&#62;

See also mb_internal_encoding(),
mb_http_input(),
mb_http_output() and
mb_send_mail().

Prev | Home | Next
mb_detect_encoding | Up | mb_encode_mimeheader


mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_mimeheader -- Encode string for MIME header

Description

string mb_encode_mimeheader ( string str [, string charset [, string transfer_encoding [, string linefeed [, string indent]]]] )

mb_encode_mimeheader() encodes a given string str by the MIME header encoding scheme. Returns a converted version of the string represented in ASCII.

charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language).

transfer_encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.

linefeed specifies the EOL (end-of-line) marker with which mb_encode_mimeheader() performs line-folding (a RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.

Example 1. mb_encode_mimeheader() example

&#60;?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " &#60;" . $mbox . "@" . $doma . "&#62;";
echo $addr;
?&#62;

Note: This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.

The indent was added as of PHP 5.

See also mb_decode_mimeheader().

Prev | Home | Next
mb_detect_order | Up | mb_encode_numericentity


mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_numericentity -- Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string str, array convmap [, string encoding] )

mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.

convmap is array specifies code area to convert.

encoding is character encoding.

Example 1. convmap example

$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.

Example 2. mb_encode_numericentity() example

&#60;?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?&#62;

See also mb_decode_numericentity().

Prev | Home | Next
mb_encode_mimeheader | Up | mb_ereg_match


mb_ereg_match

(PHP 4 >= 4.2.0)

mb_ereg_match -- Regular expression match for multibyte string

Description

bool mb_ereg_match ( string pattern, string string [, string option] )

mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg().

Prev | Home | Next
mb_encode_numericentity | Up | mb_ereg_replace


mb_ereg_replace

(PHP 4 >= 4.2.0)

mb_ereg_replace -- Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string pattern, string replacement, string string [, string option] )

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.

Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_eregi_replace().

Prev | Home | Next
mb_ereg_match | Up | mb_ereg_search_getpos


mb_ereg_search_getpos

(PHP 4 >= 4.2.0)

mb_ereg_search_getpos -- Returns start point for next regular expression match

Description

int mb_ereg_search_getpos ( void )

mb_ereg_search_getpos() returns
the point to start regular expression match for
mb_ereg_search(),
mb_ereg_search_pos(),
mb_ereg_search_regs(). The position is
represented by bytes from the head of string.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_setpos().

Prev | Home | Next
mb_ereg_replace | Up | mb_ereg_search_getregs


mb_ereg_search_getregs

(PHP 4 >= 4.2.0)

mb_ereg_search_getregs -- Retrieve the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void )

mb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

Prev | Home | Next
mb_ereg_search_getpos | Up | mb_ereg_search_init


mb_ereg_search_init

(PHP 4 >= 4.2.0)

mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression match

Description

bool mb_ereg_search_init ( string string [, string pattern [, string option]] )

mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_regs().

Prev | Home | Next
mb_ereg_search_getregs | Up | mb_ereg_search_pos


mb_ereg_search_pos

(PHP 4 >= 4.2.0)

mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte string

Description

array mb_ereg_search_pos ( [string pattern [, string option]] )

mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

Prev | Home | Next
mb_ereg_search_init | Up | mb_ereg_search_regs


mb_ereg_search_regs

(PHP 4 >= 4.2.0)

mb_ereg_search_regs -- Returns the matched part of multibyte regular expression

Description

array mb_ereg_search_regs ( [string pattern [, string option]] )

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

Prev | Home | Next
mb_ereg_search_pos | Up | mb_ereg_search_setpos


mb_ereg_search_setpos

(PHP 4 >= 4.2.0)

mb_ereg_search_setpos -- Set start point of next regular expression match

Description

bool mb_ereg_search_setpos ( int position )

mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

Prev | Home | Next
mb_ereg_search_regs | Up | mb_ereg_search


mb_ereg_search

(PHP 4 >= 4.2.0)

mb_ereg_search -- Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ( [string pattern [, string option]] )

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

Prev | Home | Next
mb_ereg_search_setpos | Up | mb_ereg


mb_ereg

(PHP 4 >= 4.2.0)

mb_ereg -- Regular expression match with multibyte support

Description

int mb_ereg ( string pattern, string string [, array regs] )

mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_eregi()

Prev | Home | Next
mb_ereg_search | Up | mb_eregi_replace


mb_eregi_replace

(PHP 4 >= 4.2.0)

mb_eregi_replace -- Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string pattern, string replace, string string [, string option] )

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored. option has the same meaning as in mb_ereg_replace().

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_replace().

Prev | Home | Next
mb_ereg | Up | mb_eregi


mb_eregi

(PHP 4 >= 4.2.0)

mb_eregi -- Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string pattern, string string [, array regs] )

mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg().

Prev | Home | Next
mb_eregi_replace | Up | mb_get_info


mb_get_info

(PHP 4 >= 4.2.0, PHP 5)

mb_get_info -- Get internal settings of mbstring

Description

mixed mb_get_info ( [string type] )

mb_get_info() returns internal setting parameter of mbstring.

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload", "mail_charset", "mail_header_encoding", "mail_body_encoding" will be returned. The last three elements are available since PHP 5.1.3.

If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

See also mb_internal_encoding(), mb_http_output().

Prev | Home | Next
mb_eregi | Up | mb_http_input


mb_http_input

(PHP 4 >= 4.0.6, PHP 5)

mb_http_input -- Detect HTTP input character encoding

Description

mixed mb_http_input ( [string type] )

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE, "S" for string, "L" for list, "I" for whole list (will return array). If type is omitted, it returns last input type processed.

Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See also mb_internal_encoding(),
mb_http_output(),
mb_detect_order().

Prev | Home | Next
mb_get_info | Up | mb_http_output


mb_http_output

(PHP 4 >= 4.0.6, PHP 5)

mb_http_output -- Set/Get HTTP output character encoding

Description

mixed mb_http_output ( [string encoding] )

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(),
mb_http_input(),
mb_detect_order().

Prev | Home | Next
mb_http_input | Up | mb_internal_encoding


mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_internal_encoding -- Set/Get internal character encoding

Description

mixed mb_internal_encoding ( [string encoding] )

mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.

encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.

encoding: Character encoding name

Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.

Example 1. mb_internal_encoding() example

&#60;?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();
?&#62;

See also mb_http_input(),
mb_http_output() and
mb_detect_order().

Prev | Home | Next
mb_http_output | Up | mb_language


mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language -- Set/Get current language

Description

mixed mb_language ( [string language] )

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

Prev | Home | Next
mb_internal_encoding | Up | mb_list_encodings_alias_names


mb_list_encodings

(PHP 5)

mb_list_encodings -- Returns an array of all supported encodings

Description

array mb_list_encodings ( void )

mb_list_encodings() returns an array with all supported encodings.

Example 1. mb_list_encodings() example

&#60;?php

print_r(mb_list_encodings());

?&#62;

The above example will output:

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => SJIS-win
    [33] => JIS
    [34] => ISO-2022-JP
    [35] => Windows-1252
    [36] => ISO-8859-1
    [37] => ISO-8859-2
    [38] => ISO-8859-3
    [39] => ISO-8859-4
    [40] => ISO-8859-5
    [41] => ISO-8859-6
    [42] => ISO-8859-7
    [43] => ISO-8859-8
    [44] => ISO-8859-9
    [45] => ISO-8859-10
    [46] => ISO-8859-13
    [47] => ISO-8859-14
    [48] => ISO-8859-15
    [49] => EUC-CN
    [50] => CP936
    [51] => HZ
    [52] => EUC-TW
    [53] => BIG-5
    [54] => EUC-KR
    [55] => UHC
    [56] => ISO-2022-KR
    [57] => Windows-1251
    [58] => CP866
    [59] => KOI8-R
)

Prev | Home | Next
mb_list_encodings_alias_names | Up | mb_list_mime_names


mb_output_handler

(PHP 4 >= 4.0.6, PHP 5)

mb_output_handler -- Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string contents, int status )

mb_output_handler() is
ob_start() callback
function. mb_output_handler() converts
characters in output buffer from internal character encoding to
HTTP output character encoding.

4.1.0 or later version, this handler adds charset HTTP header when following conditions are met:

  • Does not set Content-Type by header()

  • Default MIME type begins with text/

  • http_output setting is other than pass

contents : Output buffer contents

status : Output buffer status

Return Value: String converted

Example 1. mb_output_handler() example

&#60;?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?&#62;

Note: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See also ob_start().

Prev | Home | Next
mb_list_mime_names | Up | mb_parse_str


mb_parse_str

(PHP 4 >= 4.0.6, PHP 5)

mb_parse_str -- Parse GET/POST/COOKIE data and set global variable

Description

bool mb_parse_str ( string encoded_string [, array &result] )

mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.

encoded_string: URL encoded data.

result: Array contains decoded and character encoding converted values.

Return Value: It returns TRUE for success or FALSE for failure.

See also mb_detect_order(), mb_internal_encoding().

Prev | Home | Next
mb_output_handler | Up | mb_preferred_mime_name


mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5)

mb_preferred_mime_name -- Get MIME charset string

Description

string mb_preferred_mime_name ( string encoding )

mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.

Example 1. mb_preferred_mime_string() example

&#60;?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?&#62;

Prev | Home | Next
mb_parse_str | Up | mb_regex_encoding


mb_regex_encoding

(PHP 4 >= 4.2.0)

mb_regex_encoding -- Returns current encoding for multibyte regex as string

Description

mixed mb_regex_encoding ( [string encoding] )

mb_regex_encoding() returns the character encoding used by multibyte regex functions.

If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is the internal character encoding.

See also: mb_internal_encoding(), mb_ereg()

Prev | Home | Next
mb_preferred_mime_name | Up | mb_regex_set_options


mb_regex_set_options

(PHP 4 >= 4.3.0)

mb_regex_set_options -- Set/Get the default options for mbregex functions

Description

string mb_regex_set_options ( [string options] )

mb_regex_set_options() sets the default options described by options for multibyte regex functions.

Returns the previous options. If options is omitted, it returns the string that describes the current options.

See also
mb_split(),
mb_ereg() and
mb_eregi()

Prev | Home | Next
mb_regex_encoding | Up | mb_send_mail


mb_send_mail

(PHP 4 >= 4.0.6, PHP 5)

mb_send_mail -- Send encoded mail

Description

bool mb_send_mail ( string to, string subject, string message [, string additional_headers [, string additional_parameter]] )

mb_send_mail() sends email. Headers and
message are converted and encoded according to
mb_language() setting.
mb_send_mail() is wrapper
function of mail(). See
mail() for details.

to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject is subject of mail.

message is mail message.

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

Note: Content-Type and Content-Transfer-Encoding headers can be redefined as of PHP 5.0.0. In PHP 4, values defined by mb_language() are always used.

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Returns TRUE on success or FALSE on failure.

See also mail(),
mb_encode_mimeheader(), and
mb_language().

Prev | Home | Next
mb_regex_set_options | Up | mb_split


mb_split

(PHP 4 >= 4.2.0)

mb_split -- Split multibyte string using regular expression

Description

array mb_split ( string pattern, string string [, int limit] )

mb_split() split multibyte string using regular expression pattern and returns the result as an array.

If optional parameter limit is specified, it will be split in limit elements as maximum.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg().

Prev | Home | Next
mb_send_mail | Up | mb_strcut


mb_strcut

(PHP 4 >= 4.0.6, PHP 5)

mb_strcut -- Get part of string

Description

string mb_strcut ( string str, int start [, int length [, string encoding]] )

mb_strcut() returns the portion of str specified by the start and length parameters.

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

encoding is character encoding. If it is not set, internal character encoding is used.

See also mb_substr(), mb_internal_encoding().

Prev | Home | Next
mb_split | Up | mb_strimwidth


mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strimwidth -- Get truncated string with specified width

Description

string mb_strimwidth ( string str, int start, int width [, string trimmarker [, string encoding]] )

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

Example 1. mb_strimwidth() example

&#60;?php
$str = mb_strimwidth($str, 0, 40, "..&#62;");
?&#62;

See also mb_strwidth() and mb_internal_encoding().

Prev | Home | Next
mb_strcut | Up | mb_stripos


mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen -- Get string length

Description

int mb_strlen ( string str [, string encoding] )

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

Prev | Home | Next
mb_stristr | Up | mb_strpos


mb_strpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strpos -- Find position of first occurrence of string in a string

Description

int mb_strpos ( string haystack, string needle [, int offset [, string encoding]] )

mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal character encoding is used.

offset is search offset. If it is not specified, 0 is used.

encoding is character encoding name. If it is omitted, internal character encoding is used.

See also mb_strrpos(),
mb_internal_encoding(),
strpos()

Prev | Home | Next
mb_strlen | Up | mb_strrchr


mb_strrpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strrpos -- Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string haystack, string needle [, int offset [, string encoding]] )

mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is not specified, internal character encoding is used.

Note: As of PHP 5.2.0 offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.

Note: As of PHP 5.2.0 encoding can be specified as the third parameter for backward compatibility, but not recommended. It is deprecated and will be removed from the future release of PHP.

ChangeLog

Version | Description
5.2.0 | Added the optional parameter offset.

See Also

mb_strpos()
mb_internal_encoding()
strrpos()

Prev | Home | Next
mb_strripos | Up | mb_strstr


mb_strtolower

(PHP 4 >= 4.3.0, PHP 5)

mb_strtolower -- Make a string lowercase

Description

string mb_strtolower ( string str [, string encoding] )

mb_strtolower() returns str with all alphabetic characters converted to lowercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Example 1. mb_strtolower() example

&#60;?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?&#62;

See also strtolower(),
mb_strtoupper() and
mb_convert_case().

Prev | Home | Next
mb_strstr | Up | mb_strtoupper


mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5)

mb_strtoupper -- Make a string uppercase

Description

string mb_strtoupper ( string str [, string encoding] )

mb_strtoupper() returns str with all alphabetic characters converted to uppercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Example 1. mb_strtoupper() example

&#60;?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?&#62;

See also strtoupper(),
mb_strtolower() and
mb_convert_case().

Prev | Home | Next
mb_strtolower | Up | mb_strwidth


mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth -- Return width of string

Description

int mb_strwidth ( string str [, string encoding] )

mb_strwidth() returns width of string str.

Multi-byte character usually twice of width compare to single byte character.

Table 1. Characters width

Chars | Width
U+0000 - U+0019 | 0
U+0020 - U+1FFF | 1
U+2000 - U+FF60 | 2
U+FF61 - U+FF9F | 1
U+FFA0 - | 2

encoding is character encoding. If it is omitted, internal encoding is used.

See also: mb_strimwidth(), mb_internal_encoding().

Prev | Home | Next
mb_strtoupper | Up | mb_substitute_character


mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5)

mb_substitute_character -- Set/Get substitution character

Description

mixed mb_substitute_character ( [mixed substrchar] )

mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).

This setting affects mb_convert_encoding(),
mb_convert_variables(),
mb_output_handler(),
and mb_send_mail().

substchar : Specify Unicode value as integer or specify as string as follows

  • "none" : no output

  • "long" : Output character code value (Example: U+3000,JIS+7E7E)

Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".

Example 1. mb_substitute_character() example

&#60;?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();
?&#62;

Prev | Home | Next
mb_strwidth | Up | mb_substr_count


mb_substr_count

(PHP 4 >= 4.3.0, PHP 5)

mb_substr_count -- Count the number of substring occurrences

Description

int mb_substr_count ( string haystack, string needle [, string encoding] )

mb_substr_count() returns the number of times the needle substring occurs in the haystack string.

encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.

Example 1. mb_substr_count() example

&#60;?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?&#62;

See also substr_count(), mb_strpos(), mb_substr().

Prev | Home | Next
mb_substitute_character | Up | mb_substr


mb_substr

(PHP 4 >= 4.0.6, PHP 5)

mb_substr -- Get part of string

Description

string mb_substr ( string str, int start [, int length [, string encoding]] )

mb_substr() returns the portion of str specified by the start and length parameters.

mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is omitted, internal character encoding is used.

See also mb_strcut(), mb_internal_encoding().

Prev | Home | Next
mb_substr_count | Up | muscat Functions


MCAL Functions

PHP Manual
Prev Next

LXXXI. MCAL Functions

Introduction

MCAL stands for Modular Calendar Access Library.

Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.

With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.

Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.

With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.

Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure values.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Note: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.

Note: This extension is not available on Windows platforms.

Requirements

This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.

Installation

After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].

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.

MCAL_SUNDAY (integer)

MCAL_MONDAY (integer)

MCAL_TUESDAY (integer)

MCAL_WEDNESDAY (integer)

MCAL_THURSDAY (integer)

MCAL_FRIDAY (integer)

MCAL_SATURDAY (integer)

MCAL_JANUARY (integer)

MCAL_FEBRUARY (integer)

MCAL_MARCH (integer)

MCAL_APRIL (integer)

MCAL_MAY (integer)

MCAL_JUNE (integer)

MCAL_JULY (integer)

MCAL_AUGUST (integer)

MCAL_SEPTEMBER (integer)

MCAL_OCTOBER (integer)

MCAL_NOVEMBER (integer)

MCAL_DECEMBER (integer)

MCAL_RECUR_NONE (integer)

MCAL_RECUR_DAILY (integer)

MCAL_RECUR_WEEKLY (integer)

MCAL_RECUR_MONTHLY_MDAY (integer)

MCAL_RECUR_MONTHLY_WDAY (integer)

MCAL_RECUR_YEARLY (integer)

MCAL_M_SUNDAY (integer)

MCAL_M_MONDAY (integer)

MCAL_M_TUESDAY (integer)

MCAL_M_WEDNESDAY (integer)

MCAL_M_THURSDAY (integer)

MCAL_M_FRIDAY (integer)

MCAL_M_SATURDAY (integer)

MCAL_M_WEEKDAYS (integer)

MCAL_M_WEEKEND (integer)

MCAL_M_ALLDAYS (integer)

Table of Contents
mcal_append_event -- Store a new event into an MCAL calendar
mcal_close -- Close an MCAL stream
mcal_create_calendar -- Create a new MCAL calendar
mcal_date_compare -- Compares two dates
mcal_date_valid -- Returns TRUE if the given year, month, day is a valid date
mcal_day_of_week -- Returns the day of the week of the given date
mcal_day_of_year -- Returns the day of the year of the given date
mcal_days_in_month -- Returns the number of days in a month
mcal_delete_calendar -- Delete an MCAL calendar
mcal_delete_event -- Delete an event from an MCAL calendar
mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structure
mcal_event_init -- Initializes a streams global event structure
mcal_event_set_alarm -- Sets the alarm of the streams global event structure
mcal_event_set_category -- Sets the category of the streams global event structure
mcal_event_set_class -- Sets the class of the streams global event structure
mcal_event_set_description -- Sets the description of the streams global event structure
mcal_event_set_end -- Sets the end date and time of the streams global event structure
mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structure
mcal_event_set_recur_none -- Sets the recurrence of the streams global event structure
mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structure
mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structure
mcal_event_set_start -- Sets the start date and time of the streams global event structure
mcal_event_set_title -- Sets the title of the streams global event structure
mcal_expunge -- Deletes all events marked for being expunged
mcal_fetch_current_stream_event -- Returns an object containing the current streams event structure
mcal_fetch_event -- Fetches an event from the calendar stream
mcal_is_leap_year -- Returns if the given year is a leap year or not
mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetime
mcal_list_events -- Return a list of IDs for a date or a range of dates
mcal_next_recurrence -- Returns the next recurrence of the event
mcal_open -- Opens up an MCAL connection
mcal_popen -- Opens up a persistent MCAL connection
mcal_rename_calendar -- Rename an MCAL calendar
mcal_reopen -- Reopens an MCAL connection
mcal_snooze -- Turn off an alarm for an event
mcal_store_event -- Modify an existing event in an MCAL calendar
mcal_time_valid -- Returns TRUE if the given hour, minutes and seconds is a valid time
mcal_week_of_year -- Returns the week number of the given date

Prev | Home | Next
maxdb_warning_count | Up | mcal_append_event


mcal_append_event

(PHP 4, PECL)

mcal_append_event -- Store a new event into an MCAL calendar

Description

int mcal_append_event ( int mcal_stream )

mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.

Returns the id of the newly inserted event.

Prev | Home | Next
MCAL Functions | Up | mcal_close


mcal_close

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_close -- Close an MCAL stream

Description

bool mcal_close ( int mcal_stream [, int flags] )

Closes the given mcal stream.

Prev | Home | Next
mcal_append_event | Up | mcal_create_calendar


mcal_create_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_create_calendar -- Create a new MCAL calendar

Description

bool mcal_create_calendar ( int stream, string calendar )

Creates a new calendar named calendar.

Prev | Home | Next
mcal_close | Up | mcal_date_compare


mcal_date_compare

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day )

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

Prev | Home | Next
mcal_create_calendar | Up | mcal_date_valid


mcal_date_valid

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_date_valid -- Returns TRUE if the given year, month, day is a valid date

Description

bool mcal_date_valid ( int year, int month, int day )

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

Prev | Home | Next
mcal_date_compare | Up | mcal_day_of_week


mcal_day_of_week

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_day_of_week -- Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day )

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

Prev | Home | Next
mcal_date_valid | Up | mcal_day_of_year


mcal_day_of_year

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_day_of_year -- Returns the day of the year of the given date

Description

int mcal_day_of_year ( int year, int month, int day )

mcal_day_of_year() returns the day of the year of the given date.

Prev | Home | Next
mcal_day_of_week | Up | mcal_days_in_month


mcal_days_in_month

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_days_in_month -- Returns the number of days in a month

Description

int mcal_days_in_month ( int month, int leap_year )

mcal_days_in_month() returns the number of days in the month month, taking into account if the considered year is a leap year or not.

Prev | Home | Next
mcal_day_of_year | Up | mcal_delete_calendar


mcal_delete_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_delete_calendar -- Delete an MCAL calendar

Description

bool mcal_delete_calendar ( int stream, string calendar )

Deletes the calendar named calendar.

Prev | Home | Next
mcal_days_in_month | Up | mcal_delete_event


mcal_delete_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_delete_event -- Delete an event from an MCAL calendar

Description

bool mcal_delete_event ( int mcal_stream, int event_id )

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

Prev | Home | Next
mcal_delete_calendar | Up | mcal_event_add_attribute


mcal_event_add_attribute

(PHP 3 >= 3.0.15, PHP 4, PECL)

mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structure

Description

bool mcal_event_add_attribute ( int stream, string attribute, string value )

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

Prev | Home | Next
mcal_delete_event | Up | mcal_event_init


mcal_event_init

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_init -- Initializes a streams global event structure

Description

void mcal_event_init ( int stream )

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

Prev | Home | Next
mcal_event_add_attribute | Up | mcal_event_set_alarm


mcal_event_set_alarm

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_alarm -- Sets the alarm of the streams global event structure

Description

void mcal_event_set_alarm ( int stream, int alarm )

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

Prev | Home | Next
mcal_event_init | Up | mcal_event_set_category


mcal_event_set_category

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_category -- Sets the category of the streams global event structure

Description

void mcal_event_set_category ( int stream, string category )

mcal_event_set_category() sets the streams global event structure's category to the given string.

Prev | Home | Next
mcal_event_set_alarm | Up | mcal_event_set_class


mcal_event_set_class

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_class -- Sets the class of the streams global event structure

Description

void mcal_event_set_class ( int stream, int class )

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

Prev | Home | Next
mcal_event_set_category | Up | mcal_event_set_description


mcal_event_set_description

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_description -- Sets the description of the streams global event structure

Description

void mcal_event_set_description ( int stream, string description )

mcal_event_set_description() sets the streams global event structure's description to the given string.

Prev | Home | Next
mcal_event_set_class | Up | mcal_event_set_end


mcal_event_set_end

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_end -- Sets the end date and time of the streams global event structure

Description

void mcal_event_set_end ( int stream, int year, int month, int day [, int hour [, int min [, int sec]]] )

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

Prev | Home | Next
mcal_event_set_description | Up | mcal_event_set_recur_daily


mcal_event_set_recur_daily

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.

Prev | Home | Next
mcal_event_set_end | Up | mcal_event_set_recur_monthly_mday


mcal_event_set_recur_monthly_mday

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by month day basis, ending at the given date.

Prev | Home | Next
mcal_event_set_recur_daily | Up | mcal_event_set_recur_monthly_wday


mcal_event_set_recur_monthly_wday

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.

Prev | Home | Next
mcal_event_set_recur_monthly_mday | Up | mcal_event_set_recur_none


mcal_event_set_recur_none

(PHP 3 >= 3.0.15, PHP 4, PECL)

mcal_event_set_recur_none -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_none ( int stream )

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

Prev | Home | Next
mcal_event_set_recur_monthly_wday | Up | mcal_event_set_recur_weekly


mcal_event_set_recur_weekly

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays )

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.

Prev | Home | Next
mcal_event_set_recur_none | Up | mcal_event_set_recur_yearly


mcal_event_set_recur_yearly

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.

Prev | Home | Next
mcal_event_set_recur_weekly | Up | mcal_event_set_start


mcal_event_set_start

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_start -- Sets the start date and time of the streams global event structure

Description

void mcal_event_set_start ( int stream, int year, int month, int day [, int hour [, int min [, int sec]]] )

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

Prev | Home | Next
mcal_event_set_recur_yearly | Up | mcal_event_set_title


mcal_event_set_title

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_title -- Sets the title of the streams global event structure

Description

void mcal_event_set_title ( int stream, string title )

mcal_event_set_title() sets the streams global event structure's title to the given string.

Prev | Home | Next
mcal_event_set_start | Up | mcal_expunge


mcal_expunge

(no version information, might be only in CVS)

mcal_expunge -- Deletes all events marked for being expunged

Description

bool mcal_expunge ( int stream )

mcal_expunge() deletes all events which have been previously marked for deletion.

Prev | Home | Next
mcal_event_set_title | Up | mcal_fetch_current_stream_event


mcal_fetch_current_stream_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_fetch_current_stream_event -- Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream )

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

Prev | Home | Next
mcal_expunge | Up | mcal_fetch_event


mcal_fetch_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_fetch_event -- Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options] )

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

Prev | Home | Next
mcal_fetch_current_stream_event | Up | mcal_is_leap_year


mcal_is_leap_year

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_is_leap_year -- Returns if the given year is a leap year or not

Description

bool mcal_is_leap_year ( int year )

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

Prev | Home | Next
mcal_fetch_event | Up | mcal_list_alarms


mcal_list_alarms

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year, int begin_month, int begin_day, int end_year, int end_month, int end_day] )

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

Prev | Home | Next
mcal_is_leap_year | Up | mcal_list_events


mcal_list_events

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_list_events -- Return a list of IDs for a date or a range of dates

Description

array mcal_list_events ( int mcal_stream [, int begin_year, int begin_month, int begin_day, int end_year, int end_month, int end_day] )

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

Prev | Home | Next
mcal_list_alarms | Up | mcal_next_recurrence


mcal_next_recurrence

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_next_recurrence -- Returns the next recurrence of the event

Description

object mcal_next_recurrence ( int stream, int weekstart, array next )

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

Prev | Home | Next
mcal_list_events | Up | mcal_open


mcal_open

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options] )

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

Prev | Home | Next
mcal_next_recurrence | Up | mcal_popen


mcal_popen

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options] )

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

Prev | Home | Next
mcal_open | Up | mcal_rename_calendar


mcal_rename_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_rename_calendar -- Rename an MCAL calendar

Description

bool mcal_rename_calendar ( int stream, string old_name, string new_name )

Renames the calendar old_name to new_name.

Prev | Home | Next
mcal_popen | Up | mcal_reopen


mcal_reopen

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_reopen -- Reopens an MCAL connection

Description

bool mcal_reopen ( int mcal_stream, string calendar [, int options] )

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

Prev | Home | Next
mcal_rename_calendar | Up | mcal_snooze


mcal_snooze

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_snooze -- Turn off an alarm for an event

Description

bool mcal_snooze ( int stream_id, int event_id )

mcal_snooze() turns off an alarm for a calendar event specified by the stream_id and event_id.

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
mcal_reopen | Up | mcal_store_event


mcal_store_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream )

mcal_store_event() stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

Prev | Home | Next
mcal_snooze | Up | mcal_time_valid


mcal_time_valid

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_time_valid -- Returns TRUE if the given hour, minutes and seconds is a valid time

Description

bool mcal_time_valid ( int hour, int minutes, int seconds )

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

Prev | Home | Next
mcal_store_event | Up | mcal_week_of_year


mcal_week_of_year

(PHP 4, PECL)

mcal_week_of_year -- Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year )

mcal_week_of_year() returns the week number of the given date.

Prev | Home | Next
mcal_time_valid | Up | Mcrypt Encryption Functions


Mcrypt Encryption Functions

PHP Manual
Prev Next

LXXXII. Mcrypt Encryption Functions

Introduction

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".

Requirements

These functions work using mcrypt. To use it, download libmcrypt-x.x.tar.gz from http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.

As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

Installation

You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Mcrypt configuration options

Name | Default | Changeable | Changelog
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.

  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.

  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.

  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.

  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.

  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)

Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES

  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)

  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)

  • MCRYPT_BLOWFISH

  • MCRYPT_CAST_128

  • MCRYPT_CAST_256

  • MCRYPT_CRYPT

  • MCRYPT_DES

  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)

  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)

  • MCRYPT_GOST

  • MCRYPT_IDEA (non-free)

  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)

  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)

  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)

  • MCRYPT_RC2

  • MCRYPT_RC4 (libmcrypt 2.2.x only)

  • MCRYPT_RC6 (libmcrypt > 2.4.x only)

  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)

  • MCRYPT_SAFER64

  • MCRYPT_SAFER128

  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)

  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)

  • MCRYPT_TEAN (libmcrypt 2.2.x only)

  • MCRYPT_THREEWAY

  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)

  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )

  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)

  • MCRYPT_TWOFISH192

  • MCRYPT_TWOFISH256

  • MCRYPT_WAKE (libmcrypt > 2.4.x only)

  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

Examples

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Example 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

&#60;?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?&#62;
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Example 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

&#60;?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?&#62;
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Table of Contents
mcrypt_cbc -- Encrypt/decrypt data in CBC mode
mcrypt_cfb -- Encrypt/decrypt data in CFB mode
mcrypt_create_iv -- Create an initialization vector (IV) from a random source
mcrypt_decrypt -- Decrypts crypttext with given parameters
mcrypt_ecb -- Deprecated: Encrypt/decrypt data in ECB mode
mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm
mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm
mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_enc_get_modes_name -- Returns the name of the opened mode
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm
mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks
mcrypt_enc_self_test -- This function runs a self test on the opened module
mcrypt_encrypt -- Encrypts plaintext with given parameters
mcrypt_generic_deinit -- This function deinitializes an encryption module
mcrypt_generic_end -- This function terminates encryption
mcrypt_generic_init -- This function initializes all buffers needed for encryption
mcrypt_generic -- This function encrypts data
mcrypt_get_block_size -- Get the block size of the specified cipher
mcrypt_get_cipher_name -- Get the name of the specified cipher
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combination
mcrypt_get_key_size -- Get the key size of the specified cipher
mcrypt_list_algorithms -- Get an array of all supported ciphers
mcrypt_list_modes -- Get an array of all supported modes
mcrypt_module_close -- Close the mcrypt module
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_module_is_block_algorithm_mode -- Returns if the specified module is a block algorithm or not
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm
mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or not
mcrypt_module_open -- Opens the module of the algorithm and the mode to be used
mcrypt_module_self_test -- This function runs a self test on the specified module
mcrypt_ofb -- Encrypt/decrypt data in OFB mode
mdecrypt_generic -- Decrypt data

Prev | Home | Next
mcal_week_of_year | Up | mcrypt_cbc


mcrypt_cbc

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_cbc -- Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int cipher, string key, string data, int mode [, string iv] )

string mcrypt_cbc ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Prev | Home | Next
Mcrypt Encryption Functions | Up | mcrypt_cfb


mcrypt_cfb

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_cfb -- Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int cipher, string key, string data, int mode, string iv )

string mcrypt_cfb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Prev | Home | Next
mcrypt_cbc | Up | mcrypt_create_iv


mcrypt_create_iv

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_create_iv -- Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int size [, int source] )

mcrypt_create_iv() is used to create an IV.

Parameter size determines the size of the IV, parameter source (defaults to random value) specifies the source of the IV.

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn't have /dev/random or /dev/urandom.

Note: When using MCRYPT_RAND, remember to call srand() before mcrypt_create_iv() to initialize the random number generator; it is not seeded automatically like rand() is.

Example 1. mcrypt_create_iv() example

&#60;?php
    $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?&#62;

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.

More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.

Prev | Home | Next
mcrypt_cfb | Up | mcrypt_decrypt


mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_decrypt -- Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string cipher, string key, string data, string mode [, string iv] )

mcrypt_decrypt() decrypts the data and returns the unencrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Prev | Home | Next
mcrypt_create_iv | Up | mcrypt_ecb


mcrypt_ecb

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_ecb -- Deprecated: Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int cipher, string key, string data, int mode )

string mcrypt_ecb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Prev | Home | Next
mcrypt_decrypt | Up | mcrypt_enc_get_algorithms_name


mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource td )

This function returns the name of the algorithm.

Example 1. mcrypt_enc_get_algorithms_name() example

&#60;?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";

$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?&#62;

The above example will output:

CAST-256
CAST-256

Prev | Home | Next
mcrypt_ecb | Up | mcrypt_enc_get_block_size


mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource td )

This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.

Prev | Home | Next
mcrypt_enc_get_algorithms_name | Up | mcrypt_enc_get_iv_size


mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm

Description

int mcrypt_enc_get_iv_size ( resource td )

This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

Prev | Home | Next
mcrypt_enc_get_block_size | Up | mcrypt_enc_get_key_size


mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource td )

This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.

Prev | Home | Next
mcrypt_enc_get_iv_size | Up | mcrypt_enc_get_modes_name


mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_modes_name -- Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource td )

This function returns the name of the mode.

Example 1. mcrypt_enc_get_modes_name() example

&#60;?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_modes_name($td). "\n";

    $td = mcrypt_module_open ('cast-256', '', 'ecb', '');
    echo mcrypt_enc_get_modes_name($td). "\n";
?&#62;

Prints:

CFB
ECB

Prev | Home | Next
mcrypt_enc_get_key_size | Up | mcrypt_enc_get_supported_key_sizes


mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource td )

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

Example 1. mcrypt_enc_get_supported_key_sizes() example

&#60;?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?&#62;

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

Prev | Home | Next
mcrypt_enc_get_modes_name | Up | mcrypt_enc_is_block_algorithm_mode


mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource td )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

Prev | Home | Next
mcrypt_enc_get_supported_key_sizes | Up | mcrypt_enc_is_block_algorithm


mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource td )

This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.

Prev | Home | Next
mcrypt_enc_is_block_algorithm_mode | Up | mcrypt_enc_is_block_mode


mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource td )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Prev | Home | Next
mcrypt_enc_is_block_algorithm | Up | mcrypt_enc_self_test


mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_self_test -- This function runs a self test on the opened module

Description

int mcrypt_enc_self_test ( resource td )

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

Prev | Home | Next
mcrypt_enc_is_block_mode | Up | mcrypt_encrypt


mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv] )

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Example 1. mcrypt_encrypt() Example

&#60;?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?&#62;

The above example will output:

42
64

See also mcrypt_module_open() for a more advanced API and an example.

Prev | Home | Next
mcrypt_enc_self_test | Up | mcrypt_generic_deinit


mcrypt_generic_deinit

(PHP 4 >= 4.1.1, PHP 5)

mcrypt_generic_deinit -- This function deinitializes an encryption module

Description

bool mcrypt_generic_deinit ( resource td )

This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.) Returns FALSE on error, or TRUE on success.

See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().

Prev | Home | Next
mcrypt_encrypt | Up | mcrypt_generic_end


mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_end -- This function terminates encryption

Description

bool mcrypt_generic_end ( resource td )

Warning

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.

Prev | Home | Next
mcrypt_generic_deinit | Up | mcrypt_generic_init


mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_init -- This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource td, string key, string iv )

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.

The function returns a negative value on error, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. FALSE is returned if incorrect parameters were passed.

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

See for an example mcrypt_module_open().

Prev | Home | Next
mcrypt_generic_end | Up | mcrypt_generic


mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic -- This function encrypts data

Description

string mcrypt_generic ( resource td, string data )

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.

If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim()($str, "\0") to remove the padding.

If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.

The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mdecrypt_generic(),
mcrypt_generic_init(), and
mcrypt_generic_deinit().

Prev | Home | Next
mcrypt_generic_init | Up | mcrypt_get_block_size


mcrypt_get_block_size

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_get_block_size -- Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int cipher )

int mcrypt_get_block_size ( string cipher, string module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

Example 1. mcrypt_get_block_size() example

&#60;?php
    echo mcrypt_get_block_size('tripledes', 'ecb');
?&#62;

Prints:
8

See also: mcrypt_get_key_size(),
mcrypt_enc_get_block_size() and
mcrypt_encrypt().

Prev | Home | Next
mcrypt_generic | Up | mcrypt_get_cipher_name


mcrypt_get_cipher_name

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_get_cipher_name -- Get the name of the specified cipher

Description

string mcrypt_get_cipher_name ( int cipher )

string mcrypt_get_cipher_name ( string cipher )

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

Example 1. mcrypt_get_cipher_name() Example

&#60;?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?&#62;

The above example will output:

3DES

Prev | Home | Next
mcrypt_get_block_size | Up | mcrypt_get_iv_size


mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( string cipher, string mode )

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

Example 1. mcrypt_get_iv_size() example

&#60;?php
    echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

    echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?&#62;

See also
mcrypt_get_block_size(),
mcrypt_enc_get_iv_size() and
mcrypt_create_iv().

Prev | Home | Next
mcrypt_get_cipher_name | Up | mcrypt_get_key_size


mcrypt_get_key_size

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_get_key_size -- Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int cipher )

int mcrypt_get_key_size ( string cipher, string module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

Example 1. mcrypt_get_block_size() example

&#60;?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?&#62;

Prints:
24

See also: mcrypt_get_block_size(),
mcrypt_end_get_key_size() and
mcrypt_encrypt().

Prev | Home | Next
mcrypt_get_iv_size | Up | mcrypt_list_algorithms


mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_algorithms -- Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ( [string lib_dir] )

mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.

mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

Example 1. mcrypt_list_algorithms() Example

&#60;?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher&#60;br /&#62;\n";
    }
?&#62;

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

Prev | Home | Next
mcrypt_get_key_size | Up | mcrypt_list_modes


mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_modes -- Get an array of all supported modes

Description

array mcrypt_list_modes ( [string lib_dir] )

mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.

mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

Example 1. mcrypt_list_modes() Example

&#60;?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode &#60;br /&#62;\n";
    }
?&#62;

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

Prev | Home | Next
mcrypt_list_algorithms | Up | mcrypt_module_close


mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_close -- Close the mcrypt module

Description

bool mcrypt_module_close ( resource td )

This function closes the specified encryption handle.

See mcrypt_module_open() for an example.

Prev | Home | Next
mcrypt_list_modes | Up | mcrypt_module_get_algo_block_size


mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string algorithm [, string lib_dir] )

This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

Prev | Home | Next
mcrypt_module_close | Up | mcrypt_module_get_algo_key_size


mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string algorithm [, string lib_dir] )

This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

Prev | Home | Next
mcrypt_module_get_algo_block_size | Up | mcrypt_module_get_supported_key_sizes


mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_module_get_supported_key_sizes ( string algorithm [, string lib_dir] )

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.

See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.

Prev | Home | Next
mcrypt_module_get_algo_key_size | Up | mcrypt_module_is_block_algorithm_mode


mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm_mode -- Returns if the specified module is a block algorithm or not

Description

bool mcrypt_module_is_block_algorithm_mode ( string mode [, string lib_dir] )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.

Prev | Home | Next
mcrypt_module_get_supported_key_sizes | Up | mcrypt_module_is_block_algorithm


mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm

Description

bool mcrypt_module_is_block_algorithm ( string algorithm [, string lib_dir] )

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Prev | Home | Next
mcrypt_module_is_block_algorithm_mode | Up | mcrypt_module_is_block_mode


mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or not

Description

bool mcrypt_module_is_block_mode ( string mode [, string lib_dir] )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.

Prev | Home | Next
mcrypt_module_is_block_algorithm | Up | mcrypt_module_open


mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_open -- Opens the module of the algorithm and the mode to be used

Description

resource mcrypt_module_open ( string algorithm, string algorithm_directory, string mode, string mode_directory )

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.

The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usually /usr/local/lib/libmcrypt).

Example 1. mcrypt_module_open() examples

&#60;?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?&#62;

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Example 2. Using mcrypt_module_open() in encryption

&#60;?php
    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length, used MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key = substr(md5('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo trim($decrypted) . "\n";
?&#62;

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

See also
mcrypt_module_close(),
mcrypt_generic(),
mdecrypt_generic(),
mcrypt_generic_init(), and
mcrypt_generic_deinit().

Prev | Home | Next
mcrypt_module_is_block_mode | Up | mcrypt_module_self_test


mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_self_test -- This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string algorithm [, string lib_dir] )

This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

The function returns TRUE if the self test succeeds, or FALSE when if fails.

Example 1. mcrypt_module_self_test() example

&#60;?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?&#62;

The above example will output:

bool(true)
bool(false)

Prev | Home | Next
mcrypt_module_open | Up | mcrypt_ofb


mcrypt_ofb

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_ofb -- Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int cipher, string key, string data, int mode, string iv )

string mcrypt_ofb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Prev | Home | Next
mcrypt_module_self_test | Up | mdecrypt_generic


mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mdecrypt_generic -- Decrypt data

Description

string mdecrypt_generic ( resource td, string data )

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

Example 1. mdecrypt_generic() example

&#60;?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';

    /* Open module, and create IV */
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic($td, $plain_text);
        mcrypt_generic_deinit($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init($td, $key, $iv);
        $p_t = mdecrypt_generic($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }

    if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?&#62;

The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mcrypt_generic(),
mcrypt_generic_init(), and
mcrypt_generic_deinit().

Prev | Home | Next
mcrypt_ofb | Up | MCVE (Monetra) Payment Functions


MCVE (Monetra) Payment Functions

PHP Manual
Prev Next

LXXXIII. MCVE (Monetra) Payment Functions

Introduction

These functions interface the MCVE (Monetra) API (libmonetra, formerly known as libmcve), allowing you to work directly with MCVE/Monetra from your PHP scripts. MCVE/Monetra is Main Street Softworks' solution to direct credit/debit/gift card processing for Linux/Unix/MacOSX/Windows ( http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE/Monetra module for PHP, you can process credit cards directly through MCVE/Monetra via your PHP scripts. The following references will outline the process.

Note: MCVE/Monetra is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.

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.

Installation

To enable MCVE (Monetra) Support in PHP, first verify your LibMonetra (formerly libmcve) installation directory. If you are compiling MCVE/Monetra support directly into PHP, you will then need to configure PHP with the --with-mcve option. If you use this option without specifying the path to your libmonetra installation, PHP will attempt to look in the default LibMonetra Install location (/usr/local). If Monetra (MCVE) is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE/Monetra installation. Please note that MCVE/Monetra support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h or monetra.h under the include directory and libmcve.so and/or libmcve.a and/or libmonetra.so and/or libmonetra.a under the lib directory.

If you want to install MCVE/Monetra support as a module, you can do so by using the PECL repository, and issuing the 'pecl install mcve' command if you are running a PEAR version of at least 1.4.0.

Since MCVE/Monetra has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE/Monetra extension in PHP, you may connect to testbox.monetra.com on port 8333 for IP, or port 8444 for SSL using the MCVE/Monetra PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at http://www.mainstreetsoftworks.com/.

See Also

Additional documentation about MCVE/Monetra's PHP API can be found at http://www.mainstreetsoftworks.com/documentation.html. Main Street's documentation is complete and should be the primary reference for 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.

M_PENDING (integer)

M_DONE (integer)

M_ERROR (integer)

M_FAIL (integer)

M_SUCCESS (integer)

Table of Contents
m_checkstatus -- Check to see if a transaction has completed
m_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers
m_connect -- Establish the connection to MCVE
m_connectionerror -- Get a textual representation of why a connection failed
m_deletetrans -- Delete specified transaction from MCVE_CONN structure
m_destroyconn -- Destroy the connection and MCVE_CONN structure
m_destroyengine -- Free memory associated with IP/SSL connectivity
m_getcell -- Get a specific cell from a comma delimited response by column name
m_getcellbynum -- Get a specific cell from a comma delimited response by column number
m_getcommadelimited -- Get the RAW comma delimited data returned from MCVE
m_getheader -- Get the name of the column in a comma-delimited response
m_initconn -- Create and initialize an MCVE_CONN structure
m_initengine -- Ready the client for IP/SSL Communication
m_iscommadelimited -- Checks to see if response is comma delimited
m_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE
m_monitor -- Perform communication with MCVE (send/receive data) Non-blocking
m_numcolumns -- Number of columns returned in a comma delimited response
m_numrows -- Number of rows returned in a comma delimited response
m_parsecommadelimited -- Parse the comma delimited response so m_getcell, etc will work
m_responsekeys -- Returns array of strings which represents the keys that can be used for response parameters on this transaction
m_responseparam -- Get a custom response parameter
m_returnstatus -- Check to see if the transaction was successful
m_setblocking -- Set blocking/non-blocking mode for connection
m_setdropfile -- Set the connection method to Drop-File
m_setip -- Set the connection method to IP
m_setssl_cafile -- Set SSL CA (Certificate Authority) file for verification of server certificate
m_setssl_files -- Set certificate key files and certificates if server requires client certificate verification
m_setssl -- Set the connection method to SSL
m_settimeout -- Set maximum transaction time (per trans)
m_sslcert_gen_hash -- Generate hash for SSL client certificate verification
m_transactionssent -- Check to see if outgoing buffer is clear
m_transinqueue -- Number of transactions in client-queue
m_transkeyval -- Add key/value pair to a transaction. Replaces deprecated transparam()
m_transnew -- Start a new transaction
m_transsend -- Finalize and send the transaction
m_uwait -- Wait x microsecs
m_validateidentifier -- Whether or not to validate the passed identifier on any transaction it is passed to
m_verifyconnection -- Set whether or not to PING upon connect to verify connection
m_verifysslcert -- Set whether or not to verify the server ssl certificate

Prev | Home | Next
mdecrypt_generic | Up | m_checkstatus


Memcache Functions

PHP Manual
Prev Next

LXXXIV. Memcache Functions

Introduction

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

More information about memcached can be found at http://www.danga.com/memcached/.

Requirements

This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.

PHP 4.3.3 or newer is required to use the memcache 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/memcache.

In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option.

Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Memcache Configuration Options

Name | Default | Changeable | Changelog
memcache.allow_failover | "1" | PHP_INI_ALL | Available since Memcache 2.0.2
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since Memcache 2.1.0
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since Memcache 2.0.2
memcache.default_port | "11211" | PHP_INI_ALL | Available since Memcache 2.0.2
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

memcache.allow_failover boolean

Whether to transparently failover to other servers on errors.

memcache.max_failover_attempts integer

Defines how many servers to try when setting and getting data. Used only in conjunction with memcache.allow_failover.

memcache.chunk_size integer

Data will be transferred in chunks of this size, setting the value lower requires more network writes. Try increasing this value to 32768 if noticing otherwise inexplicable slowdowns.

memcache.default_port string

The default TCP port number to use when connecting to the memcached server if no other port is specified.

Resource Types

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

Predefined Constants

Table 2. MemCache Constants

Name | Description
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().

Examples

Example 1. memcache extension overview example

&#60;?php

$memcache = new Memcache;
$memcache-&#62;connect('localhost', 11211) or die ("Could not connect");

$version = $memcache-&#62;getVersion();
echo "Server's version: ".$version."&#60;br/&#62;\n";

$tmp_object = new stdClass;
$tmp_object-&#62;str_attr = 'test';
$tmp_object-&#62;int_attr = 123;

$memcache-&#62;set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)&#60;br/&#62;\n";

$get_result = $memcache-&#62;get('key');
echo "Data from the cache:&#60;br/&#62;\n";

var_dump($get_result);

?&#62;

In the above example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.

Table of Contents
Memcache::add -- Add an item to the server
Memcache::addServer -- Add a memcached server to connection pool
Memcache::close -- Close memcached server connection
Memcache::connect -- Open memcached server connection
memcache_debug -- Turn debug output on/off
Memcache::decrement -- Decrement item's value
Memcache::delete -- Delete item from the server
Memcache::flush -- Flush all existing items at the server
Memcache::get -- Retrieve item from the server
Memcache::getExtendedStats -- Get statistics from all servers in pool
Memcache::getServerStatus -- Returns server status
Memcache::getStats -- Get statistics of the server
Memcache::getVersion -- Return version of the server
Memcache::increment -- Increment item's value
Memcache::pconnect -- Open memcached server persistent connection
Memcache::replace -- Replace value of the existing item
Memcache::set -- Store data at the server
Memcache::setCompressThreshold -- Enable automatic compression of large values
Memcache::setServerParams -- Changes server parameters and status at runtime

Prev | Home | Next
m_verifysslcert | Up | Memcache::add


Memcache::add

(no version information, might be only in CVS)

Memcache::add -- Add an item to the server

Description

bool Memcache::add ( string key, mixed var [, int flag [, int expire]] )

Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Also you can use memcache_add() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure. Returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().

Examples

Example 1. Memcache::add() example

&#60;?php

$memcache_obj = memcache_connect("localhost", 11211);

/* procedural API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* OO API */
$memcache_obj-&#62;add('var_key', 'test variable', false, 30);

?&#62;

See Also

Memcache::set()
Memcache::replace()

Prev | Home | Next
Memcache Functions | Up | Memcache::addServer


Memcache::close

(no version information, might be only in CVS)

Memcache::close -- Close memcached server connection

Description

bool Memcache::close ( void )

Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart. Also you can use memcache_close() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::close() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/*
do something here ..
*/
memcache_close($memcache_obj);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);
/*
do something here ..
*/
$memcache_obj-&#62;close();

?&#62;

See Also

Memcache::connect()
Memcache::pconnect()

Prev | Home | Next
Memcache::addServer | Up | Memcache::connect


Memcache::connect

(no version information, might be only in CVS)

Memcache::connect -- Open memcached server connection

Description

bool Memcache::connect ( string host [, int port [, int timeout]] )

Memcache::connect() establishes a connection to the memcached server. The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close(). Also you can use memcache_connect() function.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::connect() example

&#60;?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache-&#62;connect('memcache_host', 11211);

?&#62;

See Also

Memcache::pconnect()
Memcache::close()

Prev | Home | Next
Memcache::close | Up | memcache_debug


memcache_debug

(PECL)

memcache_debug -- Turn debug output on/off

Description

bool memcache_debug ( bool on_off )

memcache_debug() turns on debug output if parameter on_off is equal to TRUE and turns off if it's FALSE.

Note: memcache_debug() is accessible only if PHP was built with --enable-debug option and always returns TRUE in this case. Otherwise, this function has no effect and always returns FALSE.

Parameters

on_off

Turns debug output on if equals to TRUE. Turns debug output off if equals to FALSE.

Return Values

Returns TRUE if PHP was built with --enable-debug option, otherwise returns FALSE.

Prev | Home | Next
Memcache::connect | Up | Memcache::decrement


Memcache::decrement

(no version information, might be only in CVS)

Memcache::decrement -- Decrement item's value

Description

int Memcache::decrement ( string key [, int value] )

Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is substracted.

Note: New item's value will not be less than zero.

Note: Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.

Memcache::decrement() does not create an item if it didn't exist. Also you can use memcache_decrement() function.

Parameters

key

Key of the item do decrement.

value

Decrement the item by value. Optional and defaults to 1.

Return Values

Returns item's new value on success or FALSE on failure.

Examples

Example 1. Memcache::decrement() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* decrement item by 2 */
$new_value = memcache_decrement($memcache_obj, 'test_item', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj-&#62;decrement('test_item', 3);
?&#62;

See Also

Memcache::increment()
Memcache::replace()

Prev | Home | Next
memcache_debug | Up | Memcache::delete


Memcache::delete

(no version information, might be only in CVS)

Memcache::delete -- Delete item from the server

Description

bool Memcache::delete ( string key [, int timeout] )

Memcache::delete() deletes item with the key. If parameter timeout is specified, the item will expire after timeout seconds. Also you can use memcache_delete() function.

Parameters

key

timeout

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::delete() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* after 10 seconds item will be deleted by the server */
memcache_delete($memcache_obj, 'key_to_delete', 10);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);

$memcache_obj-&#62;delete('key_to_delete', 10);

?&#62;

See Also

Memcache::set()
Memcache::replace()

Prev | Home | Next
Memcache::decrement | Up | Memcache::flush


Memcache::flush

(no version information, might be only in CVS)

Memcache::flush -- Flush all existing items at the server

Description

bool Memcache::flush ( void )

Memcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items. Also you can use memcache_flush() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::flush() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);

$memcache_obj-&#62;flush();

?&#62;

Prev | Home | Next
Memcache::delete | Up | Memcache::get


Memcache::get

(no version information, might be only in CVS)

Memcache::get -- Retrieve item from the server

Description

string Memcache::get ( string key )

array Memcache::get ( array keys )

Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.

You can pass array of keys to Memcache::get() to get array of values. The result array will contain only found key-value pairs.

Parameters

key

Return Values

Returns the string associated with the key or FALSE on failure or if such key was not found.

Examples

Example 1. Memcache::get() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);
$var = $memcache_obj-&#62;get('some_key');

/*
You also can use array of keys as a parameter.
If such item wasn't found at the server, the result
array simply will not include such key.
*/

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);
$var = $memcache_obj-&#62;get(Array('some_key', 'second_key'));

?&#62;

Prev | Home | Next
Memcache::flush | Up | Memcache::getExtendedStats


Memcache::getStats

(no version information, might be only in CVS)

Memcache::getStats -- Get statistics of the server

Description

array Memcache::getStats ( [string type [, int slabid [, int limit]]] )

Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values. Also you can use memcache_get_stats() function.

Parameters

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump. Default value is 100.

Return Values

Returns an associative array of server statistics or FALSE on failure.

See Also

Memcache::getVersion()
Memcache::getExtendedStats()

Prev | Home | Next
Memcache::getServerStatus | Up | Memcache::getVersion


Memcache::getVersion

(no version information, might be only in CVS)

Memcache::getVersion -- Return version of the server

Description

string Memcache::getVersion ( void )

Memcache::getVersion() returns a string with server's version number. Also you can use memcache_get_version() function.

Return Values

Returns a string of server version number or FALSE on failure.

Examples

Example 1. Memcache::getVersion() example

&#60;?php

/* OO API */
$memcache = new Memcache;
$memcache-&#62;connect('memcache_host', 11211);
echo $memcache-&#62;getVersion();

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_version($memcache);

?&#62;

See Also

Memcache::getExtendedStats()
Memcache::getStats()

Prev | Home | Next
Memcache::getStats | Up | Memcache::increment


Memcache::increment

(no version information, might be only in CVS)

Memcache::increment -- Increment item's value

Description

int Memcache::increment ( string key [, int value] )

Memcache::increment() increments value of the item on the specified value. If item with key key was not numeric and cannot be converted to number, it will change it's value to value. Memcache::increment() does not create an item if it didn't exist.

Note: Do not use Memcache::increment() with item, which was stored compressed, because consequent call to Memcache::get() will fail.

Also you can use memcache_increment() function.

Parameters

key

Key of the item to increment.

value

Increment the item by value. Optional and defaults to 1.

Return Values

Returns new item's value on success or FALSE on failure.

Examples

Example 1. Memcache::increment() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj-&#62;connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj-&#62;increment('counter', 3);

?&#62;

See Also

Memcache::decrement()
Memcache::replace()

Prev | Home | Next
Memcache::getVersion | Up | Memcache::pconnect


Memcache::pconnect

(no version information, might be only in CVS)

Memcache::pconnect -- Open memcached server persistent connection

Description

bool Memcache::pconnect ( string host [, int port [, int timeout]] )

Memcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function. Also you can use memcache_pconnect() function.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::pconnect() example

&#60;?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj-&#62;pconnect('memcache_host', 11211);

?&#62;

See Also

Memcache::connect()

Prev | Home | Next
Memcache::increment | Up | Memcache::replace


Memcache::replace

(no version information, might be only in CVS)

Memcache::replace -- Replace value of the existing item

Description

bool Memcache::replace ( string key, mixed var [, int flag [, int expire]] )

Memcache::replace() should be used to replace value of
existing item with key. In case if item with such
key doesn't exists, Memcache::replace() returns
FALSE. For the rest Memcache::replace() behaves
similarly to Memcache::set().
Also you can use memcache_replace() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::replace() example

&#60;?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj-&#62;replace("test_key", "some variable", false, 30);

?&#62;

See Also

Memcache::set()
Memcache::add()

Prev | Home | Next
Memcache::pconnect | Up | Memcache::set


Memcache::set

(no version information, might be only in CVS)

Memcache::set -- Store data at the server

Description

bool Memcache::set ( string key, mixed var [, int flag [, int expire]] )

Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items). You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).

Note: Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.

Also you can use memcache_set() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::set() example

&#60;?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
set value of item with key 'var_key'
using 0 as flag value, compression is not used
expire time is 30 seconds
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo memcache_get($memcache_obj, 'var_key');

?&#62;

Example 2. Memcache::set() example

&#60;?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj-&#62;connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj-&#62;set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj-&#62;get('var_key');

?&#62;

See Also

Memcache::add()
Memcache::replace()

Prev | Home | Next
Memcache::replace | Up | Memcache::setCompressThreshold


Mhash Functions

PHP Manual
Prev Next

LXXXV. Mhash Functions

Introduction

These functions are intended to work with mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.

This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

Requirements

To use it, download the mhash distribution from its web site and follow the included installation instructions.

Installation

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.

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.

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.

  • MHASH_ADLER32

  • MHASH_CRC32

  • MHASH_CRC32B

  • MHASH_GOST

  • MHASH_HAVAL128

  • MHASH_HAVAL160

  • MHASH_HAVAL192

  • MHASH_HAVAL256

  • MHASH_MD4

  • MHASH_MD5

  • MHASH_RIPEMD160

  • MHASH_SHA1

  • MHASH_SHA256

  • MHASH_TIGER

  • MHASH_TIGER128

  • MHASH_TIGER160

Examples

Example 1. Compute the MD5 digest and hmac and print it out as hex

&#60;?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "&#60;br /&#62;\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "&#60;br /&#62;\n";
?&#62;

This will produce:

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

Table of Contents
mhash_count -- Get the highest available hash id
mhash_get_block_size -- Get the block size of the specified hash
mhash_get_hash_name -- Get the name of the specified hash
mhash_keygen_s2k -- Generates a key
mhash -- Compute hash

Prev | Home | Next
Memcache::setServerParams | Up | mhash_count


mhash_count

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_count -- Get the highest available hash id

Description

int mhash_count ( void )

Gets the highest available hash id.

Return Values

Returns the highest available hash id. Hashes are numbered from 0 to this hash id.

Examples

Example 1. Traversing all hashes

&#60;?php

$nr = mhash_count();

for ($i = 0; $i &#60;= $nr; $i++) {
    echo sprintf("The blocksize of %s is %d\n",
        mhash_get_hash_name($i),
        mhash_get_block_size($i));
}
?&#62;

Prev | Home | Next
Mhash Functions | Up | mhash_get_block_size


mhash_get_block_size

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_get_block_size -- Get the block size of the specified hash

Description

int mhash_get_block_size ( int hash )

Gets the size of a block of the specified hash.

Parameters

hash

The hash id. One of the MHASH_XXX constants.

Return Values

Returns the size in bytes or FALSE, if the hash does not exist.

Examples

Example 1. mhash_get_block_size() Example

&#60;?php

echo mhash_get_block_size(MHASH_MD5); // 16

?&#62;

Prev | Home | Next
mhash_count | Up | mhash_get_hash_name


mhash_get_hash_name

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_get_hash_name -- Get the name of the specified hash

Description

string mhash_get_hash_name ( int hash )

Gets the name of the specified hash.

Parameters

hash

The hash id. One of the MHASH_XXX constants.

Return Values

Returns the name of the hash or FALSE, if the hash does not exist.

Examples

Example 1. mhash_get_hash_name() example

&#60;?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?&#62;

Prev | Home | Next
mhash_get_block_size | Up | mhash_keygen_s2k


mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5)

mhash_keygen_s2k -- Generates a key

Description

string mhash_keygen_s2k ( int hash, string password, string salt, int bytes )

Generates a key according to the hash given a user provided password.

This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440).

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.

Parameters

hash

The hash id used to create the key. One of the MHASH_XXX constants.

password

User supplied password.

salt

Must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

bytes

The key length, in bytes.

Return Values

Returns the generated key as a string, or FALSE on error.

Prev | Home | Next
mhash_get_hash_name | Up | mhash


mhash

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash -- Compute hash

Description

string mhash ( int hash, string data [, string key] )

mhash() applies a hash function specified by hash to the data.

Parameters

hash

The hash id. One of the MHASH_XXX constants.

data

The user input, as a string.

key

If specified, the function will return the resulting HMAC instead. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode.

Return Values

Returns the resulting hash (also called digest) or HMAC as a string, or FALSE on errors.

Prev | Home | Next
mhash_keygen_s2k | Up | Mimetype Functions


Mimetype Functions

PHP Manual
Prev Next

LXXXVI. Mimetype Functions

Introduction

Warning

This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.

Requirements

No external libraries are needed to build this extension.

Installation

You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.

Note: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2

Note: This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.

Note to Win32 Users: In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.

Example 1. Setting the path to magic.mime

mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Mimetype configuration options

Name | Default | Changeable | Changelog
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
mime_content_type -- Detect MIME Content-type for a file (deprecated)

Prev | Home | Next
mhash | Up | mime_content_type


mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

mime_content_type -- Detect MIME Content-type for a file (deprecated)

Description

string mime_content_type ( string filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parameters

filename

Path to the tested file.

Return Values

Returns the content type in MIME format, like text/plain or application/octet-stream.

Notes

Warning

This function has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

Examples

Example 1. mime_content_type() Example

&#60;?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?&#62;

The above example will output:

image/gif
text/plain

See Also

Fileinfo for a replacement

Prev | Home | Next
Mimetype Functions | Up | Ming functions for Flash


Ming functions for Flash

PHP Manual
Prev Next

LXXXVII. Ming functions for Flash

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

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know at http://ming.sourceforge.net/.

Ming was added in PHP 4.0.5.

Requirements

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: http://ming.sourceforge.net/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.

Installation

Example 1. built into PHP (Unix)

mkdir <phpdir>/ext/ming
cp php_ext/* <phpdir>/ext/ming
cd <phpdir>
./buildconf
./configure --with-ming <other config options>

Build and install PHP as usual, restart web server if necessary.

Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

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.

MING_NEW (integer)

MING_ZLIB (integer)

SWFBUTTON_HIT (integer)

SWFBUTTON_DOWN (integer)

SWFBUTTON_OVER (integer)

SWFBUTTON_UP (integer)

SWFBUTTON_MOUSEUPOUTSIDE (integer)

SWFBUTTON_DRAGOVER (integer)

SWFBUTTON_DRAGOUT (integer)

SWFBUTTON_MOUSEUP (integer)

SWFBUTTON_MOUSEDOWN (integer)

SWFBUTTON_MOUSEOUT (integer)

SWFBUTTON_MOUSEOVER (integer)

SWFFILL_RADIAL_GRADIENT (integer)

SWFFILL_LINEAR_GRADIENT (integer)

SWFFILL_TILED_BITMAP (integer)

SWFFILL_CLIPPED_BITMAP (integer)

SWFTEXTFIELD_HASLENGTH (integer)

SWFTEXTFIELD_NOEDIT (integer)

SWFTEXTFIELD_PASSWORD (integer)

SWFTEXTFIELD_MULTILINE (integer)

SWFTEXTFIELD_WORDWRAP (integer)

SWFTEXTFIELD_DRAWBOX (integer)

SWFTEXTFIELD_NOSELECT (integer)

SWFTEXTFIELD_HTML (integer)

SWFTEXTFIELD_ALIGN_LEFT (integer)

SWFTEXTFIELD_ALIGN_RIGHT (integer)

SWFTEXTFIELD_ALIGN_CENTER (integer)

SWFTEXTFIELD_ALIGN_JUSTIFY (integer)

SWFACTION_ONLOAD (integer)

SWFACTION_ENTERFRAME (integer)

SWFACTION_UNLOAD (integer)

SWFACTION_MOUSEMOVE (integer)

SWFACTION_MOUSEDOWN (integer)

SWFACTION_MOUSEUP (integer)

SWFACTION_KEYDOWN (integer)

SWFACTION_KEYUP (integer)

SWFACTION_DATA (integer)

Predefined 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.

Classes

SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFFontChar
SWFGradient
SWFMorph
SWFMovie
SWFPrebuiltClip
SWFShape
SWFSound
SWFSoundInstance
SWFSprite
SWFText
SWFTextField
SWFVideoStream

Table of Contents
SWFAction -- SWFAction Class
SWFAction->__construct() -- Creates a new SWFAction
SWFBitmap -- SWFBitmap Class
SWFBitmap->__construct() -- Loads Bitmap object
SWFBitmap->getHeight() -- Returns the bitmap's height
SWFBitmap->getWidth() -- Returns the bitmap's width
SWFButton -- SWFButton Class
SWFButton->__construct() -- Creates a new Button
SWFButton->addAction() -- Adds an action
SWFButton->addASound() -- Associates a sound with a button transition
SWFButton->addShape() -- Adds a shape to a button
SWFButton->setAction() -- Sets the action
SWFButton->setDown() -- Alias for addShape(shape, SWFBUTTON_DOWN)
SWFButton->setHit() -- Alias for addShape(shape, SWFBUTTON_HIT)
SWFButton->setMenu() -- enable track as menu button behaviour
SWFButton->setOver() -- Alias for addShape(shape, SWFBUTTON_OVER)
SWFButton->setUp() -- Alias for addShape(shape, SWFBUTTON_UP)
SWFDisplayItem -- SWFDisplayItem Class
SWFDisplayItem->addAction() -- Adds this SWFAction to the given SWFSprite instance
SWFDisplayItem->addColor() -- Adds the given color to this item's color transform
SWFDisplayItem->endMask() -- Another way of defining a MASK layer
SWFDisplayItem->getRot() --
SWFDisplayItem->getX() --
SWFDisplayItem->getXScale() --
SWFDisplayItem->getXSkew() --
SWFDisplayItem->getY() --
SWFDisplayItem->getYScale() --
SWFDisplayItem->getYSkew() --
SWFDisplayItem->move() -- Moves object in relative coordinates
SWFDisplayItem->moveTo() -- Moves object in global coordinates
SWFDisplayItem->multColor() -- Multiplies the item's color transform
SWFDisplayItem->remove() -- Removes the object from the movie
SWFDisplayItem->rotate() -- Rotates in relative coordinates
SWFDisplayItem->rotateTo() -- Rotates the object in global coordinates
SWFDisplayItem->scale() -- Scales the object in relative coordinates
SWFDisplayItem->scaleTo() -- Scales the object in global coordinates
SWFDisplayItem->setDepth() -- Sets z-order
SWFDisplayItem->setMaskLevel() -- Defines a MASK layer at level
SWFDisplayItem->setMatrix() -- Sets the item's transform matrix
SWFDisplayItem->setName() -- Sets the object's name
SWFDisplayItem->setRatio() -- Sets the object's ratio
SWFDisplayItem->skewX() -- Sets the X-skew
SWFDisplayItem->skewXTo() -- Sets the X-skew
SWFDisplayItem->skewY() -- Sets the Y-skew
SWFDisplayItem->skewYTo() -- Sets the Y-skew
SWFFill -- SWFFill Class
SWFFill->moveTo() -- Moves fill origin
SWFFill->rotateTo() -- Sets fill's rotation
SWFFill->scaleTo() -- Sets fill's scale
SWFFill->skewXTo() -- Sets fill x-skew
SWFFill->skewYTo() -- Sets fill y-skew
SWFFont -- SWFFont Class
SWFFont->__construct() -- Loads a font definition
SWFFont->getAscent() -- Returns the ascent of the font, or 0 if not available
SWFFont->getDescent() -- Returns the descent of the font, or 0 if not available
SWFFont->getLeading() -- Returns the leading of the font, or 0 if not available
SWFFont->getShape() -- Returns the glyph shape of a char as a text string
SWFFont->getUTF8Width() -- Calculates the width of the given string in this font at full height
SWFFont->getWidth() -- Returns the string's width
SWFFontChar -- SWFFontChar Class
SWFFontChar->addChars() -- Adds characters to a font for exporting font
SWFFontChar->addUTF8Chars() -- Adds characters to a font for exporting font
SWFGradient -- SWFGradient Class
SWFGradient->__construct() -- Creates a gradient object
SWFGradient->addEntry() -- Adds an entry to the gradient list
SWFMorph -- SWFMorph Class
SWFMorph->__construct() -- Creates a new SWFMorph object
SWFMorph->getShape1() -- Gets a handle to the starting shape
SWFMorph->getShape2() -- Gets a handle to the ending shape
SWFMovie -- SWFMovie Class
SWFMovie->__construct() -- Creates a new movie object, representing an SWF version 4 movie
SWFMovie->add() -- Adds any type of data to a movie
SWFMovie->addExport() --
SWFMovie->addFont() --
SWFMovie->importChar() --
SWFMovie->importFont() --
SWFMovie->labelFrame() -- Labels a frame
SWFMovie->nextFrame() -- Moves to the next frame of the animation
SWFMovie->output() -- Dumps your lovingly prepared movie out
SWFMovie->remove() -- Removes the object instance from the display list
SWFMovie->save() -- Saves the SWF movie in a file
SWFMovie->saveToFile() --
SWFMovie->setbackground() -- Sets the background color
SWFMovie->setDimension() -- Sets the movie's width and height
SWFMovie->setFrames() -- Sets the total number of frames in the animation
SWFMovie->setRate() -- Sets the animation's frame rate
SWFMovie->startSound() --
SWFMovie->stopSound() --
SWFMovie->streamMP3() -- Streams a MP3 file
SWFMovie->writeExports() --
SWFPrebuiltClip -- SWFPrebuiltClip Class
SWFPrebuiltClip->__construct() -- Returns a SWFPrebuiltClip object
SWFShape -- SWFShape Class
SWFShape->__construct() -- Creates a new shape object
SWFShape->addFill() -- Adds a solid fill to the shape
SWFShape->drawArc() -- Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
SWFShape->drawCircle() -- Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
SWFShape->drawCubic() -- Draws a cubic bezier curve using the current position and the three given points as control points
SWFShape->drawCubicTo() -- Draws a cubic bezier curve using the current position and the three given points as control points
SWFShape->drawCurve() -- Draws a curve (relative)
SWFShape->drawCurveTo() -- Draws a curve
SWFShape->drawGlyph() -- Draws the first character in the given string into the shape using the glyph definition from the given font
SWFShape->drawLine() -- Draws a line (relative)
SWFShape->drawLineTo() -- Draws a line
SWFShape->movePen() -- Moves the shape's pen (relative)
SWFShape->movePenTo() -- Moves the shape's pen
SWFShape->setLeftFill() -- Sets left rasterizing color
SWFShape->setLine() -- Sets the shape's line style
SWFShape->setRightFill() -- Sets right rasterizing color
SWFSound -- SWFSound Class
SWFSound -- Returns a new SWFSound object from given file
SWFSoundInstance -- SWFSoundInstance Class
SWFSoundInstance->loopCount() --
SWFSoundInstance->loopInPoint() --
SWFSoundInstance->loopOutPoint() --
SWFSoundInstance->noMultiple() --
SWFSprite -- SWFSprite Class
SWFSprite->__construct() -- Creates a movie clip (a sprite)
SWFSprite->add() -- Adds an object to a sprite
SWFSprite->labelFrame() -- Labels frame
SWFSprite->nextFrame() -- Moves to the next frame of the animation
SWFSprite->remove() -- Removes an object to a sprite
SWFSprite->setFrames() -- Sets the total number of frames in the animation
SWFSprite->startSound() --
SWFSprite->stopSound() --
SWFText -- SWFText Class
SWFText->__construct() -- Creates a new SWFText object
SWFText->addString() -- Draws a string
SWFText->addUTF8String() -- Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
SWFText->getAscent() -- Returns the ascent of the current font at its current size, or 0 if not available
SWFText->getDescent() -- Returns the descent of the current font at its current size, or 0 if not available
SWFText->getLeading() -- Returns the leading of the current font at its current size, or 0 if not available
SWFText->getUTF8Width() -- calculates the width of the given string in this text objects current font and size
SWFText->getWidth() -- Computes string's width
SWFText->moveTo() -- Moves the pen
SWFText->setColor() -- Sets the current text color
SWFText->setFont() -- Sets the current font
SWFText->setHeight() -- Sets the current font height
SWFText->setSpacing() -- Sets the current font spacing
SWFTextField -- SWFTextField Class
SWFTextField->__construct() -- Creates a text field object
SWFTextField->addChars() -- adds characters to a font that will be available within a textfield
SWFTextField->addString() -- Concatenates the given string to the text field
SWFTextField->align() -- Sets the text field alignment
SWFTextField->setBounds() -- Sets the text field width and height
SWFTextField->setColor() -- Sets the color of the text field
SWFTextField->setFont() -- Sets the text field font
SWFTextField->setHeight() -- Sets the font height of this text field font
SWFTextField->setIndentation() -- Sets the indentation of the first line
SWFTextField->setLeftMargin() -- Sets the left margin width of the text field
SWFTextField->setLineSpacing() -- Sets the line spacing of the text field
SWFTextField->setMargins() -- Sets the margins width of the text field
SWFTextField->setName() -- Sets the variable name
SWFTextField->setPadding() -- Sets the padding of this textfield
SWFTextField->setRightMargin() -- Sets the right margin width of the text field
SWFVideoStream -- SWFVideoStream Class
SWFVideoStream->__construct() -- Returns a SWFVideoStream object
SWFVideoStream->getNumFrames() --
SWFVideoStream->setDimension() --
ming_keypress -- Returns the action flag for keyPress(char)
ming_setcubicthreshold -- Set cubic threshold
ming_setscale -- Set scale
ming_useconstants -- Use constant pool
ming_useswfversion -- Sets the SWF version

Prev | Home | Next
mime_content_type | Up | SWFAction


ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5)

ming_setcubicthreshold -- Set cubic threshold

Description

void ming_setcubicthreshold ( int threshold )

Sets the threshold error for drawing cubic beziers.

Parameters

threshold

The Threshold. Lower is more accurate, hence larger file size.

Return Values

No value is returned.

Prev | Home | Next
ming_keypress | Up | ming_setscale


ming_setscale

(PHP 4 >= 4.0.5, PHP 5)

ming_setscale -- Set scale

Description

void ming_setscale ( int scale )

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
ming_setcubicthreshold | Up | ming_useconstants


ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5)

ming_useswfversion -- Sets the SWF version

Description

void ming_useswfversion ( int version )

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
ming_useconstants | Up | Miscellaneous Functions


SWFBitmap->getHeight()

(no version information, might be only in CVS)

SWFBitmap->getHeight() -- Returns the bitmap's height

Description

class SWFBitmap {

float getHeight ( void )

}

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.

Returns the bitmap's height.

Return Values

Returns the bitmap height in pixels.

See Also

SWFBitmap->getWidth()

Prev | Home | Next
SWFBitmap->__construct() | Up | SWFBitmap->getWidth()


SWFBitmap->getWidth()

(no version information, might be only in CVS)

SWFBitmap->getWidth() -- Returns the bitmap's width

Description

class SWFBitmap {

float getWidth ( void )

}

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.

Returns the bitmap's width.

Return Values

Returns the bitmap width in pixels.

See Also

SWFBitmap->getHeight()

Prev | Home | Next
SWFBitmap->getHeight() | Up | SWFButton


SWFButton->addAction()

(no version information, might be only in CVS)

SWFButton->addAction() -- Adds an action

Description

class SWFButton {

void addAction ( SWFAction action, 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.

Adds the given action to the button for the given conditions.

Parameters

action

An SWFAction, returned by SWFAction->__construct().

flags

The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

Return Values

No value is returned.

See Also

SWFButton->addShape()
SWFAction

Prev | Home | Next
SWFButton->__construct() | Up | SWFButton->addASound()


SWFButton->addShape()

(no version information, might be only in CVS)

SWFButton->addShape() -- Adds a shape to a button

Description

class SWFButton {

void addShape ( SWFShape shape, 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.

Adds the given shape to the button.

Parameters

shape

An SWFShape instance

flags

The following flags are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN and SWFBUTTON_HIT.

SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

Return Values

No value is returned.

Prev | Home | Next
SWFButton->addASound() | Up | SWFButton->setAction()


SWFButton->setAction()

(no version information, might be only in CVS)

SWFButton->setAction() -- Sets the action

Description

class SWFButton {

void setAction ( SWFAction action )

}

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.

Sets the action to be performed when the button is clicked.

This is a shortcut for SWFButton->addAction() called with the SWFBUTTON_MOUSEUP flag.

Parameters

action

An SWFAction, returned by SWFAction->__construct().

Return Values

No value is returned.

See Also

SWFButton->addAction()
SWFAction

Prev | Home | Next
SWFButton->addShape() | Up | SWFButton->setDown()


SWFButton->setDown()

(no version information, might be only in CVS)

SWFButton->setDown() -- Alias for addShape(shape, SWFBUTTON_DOWN)

Description

class SWFButton {

void setDown ( SWFShape shape )

}

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.

swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Return Values

No value is returned.

See Also

SWFButton->addShape()
SWFAction

Prev | Home | Next
SWFButton->setAction() | Up | SWFButton->setHit()


SWFButton->setHit()

(no version information, might be only in CVS)

SWFButton->setHit() -- Alias for addShape(shape, SWFBUTTON_HIT)

Description

class SWFButton {

void setHit ( SWFShape shape )

}

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.

swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).

Return Values

No value is returned.

See Also

SWFButton->addShape()
SWFAction

Prev | Home | Next
SWFButton->setDown() | Up | SWFButton->setMenu()


SWFButton->setOver()

(no version information, might be only in CVS)

SWFButton->setOver() -- Alias for addShape(shape, SWFBUTTON_OVER)

Description

class SWFButton {

void setOver ( SWFShape shape )

}

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.

swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).

Return Values

No value is returned.

See Also

SWFButton->addShape()
SWFAction

Prev | Home | Next
SWFButton->setMenu() | Up | SWFButton->setUp()


SWFButton->setUp()

(no version information, might be only in CVS)

SWFButton->setUp() -- Alias for addShape(shape, SWFBUTTON_UP)

Description

class SWFButton {

void setUp ( SWFShape shape )

}

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.

swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).

Return Values

No value is returned.

See Also

SWFButton->addShape()
SWFAction

Prev | Home | Next
SWFButton->setOver() | Up | SWFDisplayItem


SWFDisplayItem->addColor()

(no version information, might be only in CVS)

SWFDisplayItem->addColor() -- Adds the given color to this item's color transform

Description

class SWFDisplayItem {

void addColor ( int red, int green, int blue [, int a] )

}

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.

swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->addAction() | Up | SWFDisplayItem->endMask()


SWFDisplayItem->move()

(no version information, might be only in CVS)

SWFDisplayItem->move() -- Moves object in relative coordinates

Description

class SWFDisplayItem {

void move ( int dx, int dy )

}

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.

swfdisplayitem->move() moves the current object by (dx,dy) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->moveTo()

Prev | Home | Next
SWFDisplayItem->getYSkew() | Up | SWFDisplayItem->moveTo()


SWFDisplayItem->moveTo()

(no version information, might be only in CVS)

SWFDisplayItem->moveTo() -- Moves object in global coordinates

Description

class SWFDisplayItem {

void moveTo ( int x, int y )

}

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.

swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->move()

Prev | Home | Next
SWFDisplayItem->move() | Up | SWFDisplayItem->multColor()


SWFDisplayItem->multColor()

(no version information, might be only in CVS)

SWFDisplayItem->multColor() -- Multiplies the item's color transform

Description

class SWFDisplayItem {

void multColor ( int red, int green, int blue [, int a] )

}

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.

swfdisplayitem->multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

Examples

This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).

Example 1. swfdisplayitem->multcolor() example

&#60;?php

$b = new SWFBitmap(file_get_contents("backyard.jpg"));
// note use your own picture :-)
$s = new SWFShape();
$s-&#62;setRightFill($s-&#62;addFill($b));
$s-&#62;drawLine($b-&#62;getWidth(), 0);
$s-&#62;drawLine(0, $b-&#62;getHeight());
$s-&#62;drawLine(-$b-&#62;getWidth(), 0);
$s-&#62;drawLine(0, -$b-&#62;getHeight());

$m = new SWFMovie();
$m-&#62;setDimension($b-&#62;getWidth(), $b-&#62;getHeight());

$i = $m-&#62;add($s);

for ($n=0; $n&#60;=20; ++$n) {
  $i-&#62;multColor(1.0-$n/10, 1.0, 1.0);
  $i-&#62;addColor(0xff*$n/20, 0, 0);
  $m-&#62;nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFDisplayItem->moveTo() | Up | SWFDisplayItem->remove()


SWFDisplayItem->remove()

(no version information, might be only in CVS)

SWFDisplayItem->remove() -- Removes the object from the movie

Description

class SWFDisplayItem {

void remove ( void )

}

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.

swfdisplayitem->remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFMovie->add()

Prev | Home | Next
SWFDisplayItem->multColor() | Up | SWFDisplayItem->rotate()


SWFDisplayItem->rotate()

(no version information, might be only in CVS)

SWFDisplayItem->rotate() -- Rotates in relative coordinates

Description

class SWFDisplayItem {

void rotate ( float angle )

}

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.

swfdisplayitem->rotate() rotates the current object by angle degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->rotateTo()

Prev | Home | Next
SWFDisplayItem->remove() | Up | SWFDisplayItem->rotateTo()


SWFDisplayItem->rotateTo()

(no version information, might be only in CVS)

SWFDisplayItem->rotateTo() -- Rotates the object in global coordinates

Description

class SWFDisplayItem {

void rotateTo ( float angle )

}

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.

swfdisplayitem->rotateto() set the current object rotation to angle degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Examples

This example bring three rotating string from the background to the foreground. Pretty nice.

Example 1. swfdisplayitem->rotateto() example

&#60;?php
$thetext =  "ming!";

$f = new SWFFont("Bauhaus 93.fdb");

$m = new SWFMovie();
$m-&#62;setRate(24.0);
$m-&#62;setDimension(2400, 1600);
$m-&#62;setBackground(0xff, 0xff, 0xff);

// functions with huge numbers of arbitrary
// arguments are always a good idea!  Really!

function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
  global $f, $m;

  $t = new SWFText();
  $t-&#62;setFont($f);
  $t-&#62;setColor($r, $g, $b, $a);
  $t-&#62;setHeight(960);
  $t-&#62;moveTo(-($f-&#62;getWidth($string))/2, $f-&#62;getAscent()/2);
  $t-&#62;addString($string);

  // we can add properties just like a normal PHP var,
  // as long as the names aren't already used.
  // e.g., we can't set $i-&#62;scale, because that's a function

  $i = $m-&#62;add($t);
  $i-&#62;x = $x;
  $i-&#62;y = $y;
  $i-&#62;rot = $rot;
  $i-&#62;s = $scale;
  $i-&#62;rotateTo($rot);
  $i-&#62;scale($scale, $scale);

  // but the changes are local to the function, so we have to
  // return the changed object.  kinda weird..

  return $i;
}

function step($i)
{
  $oldrot = $i-&#62;rot;
  $i-&#62;rot = 19*$i-&#62;rot/20;
  $i-&#62;x = (19*$i-&#62;x + 1200)/20;
  $i-&#62;y = (19*$i-&#62;y + 800)/20;
  $i-&#62;s = (19*$i-&#62;s + 1.0)/20;

  $i-&#62;rotateTo($i-&#62;rot);
  $i-&#62;scaleTo($i-&#62;s, $i-&#62;s);
  $i-&#62;moveTo($i-&#62;x, $i-&#62;y);

  return $i;
}

// see?  it sure paid off in legibility:

$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

for ($i=1; $i&#60;=100; ++$i) {
  $i1 = step($i1);
  $i2 = step($i2);
  $i3 = step($i3);

  $m-&#62;nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

See Also

SWFDisplayItem->rotate()

Prev | Home | Next
SWFDisplayItem->rotate() | Up | SWFDisplayItem->scale()


SWFDisplayItem->scale()

(no version information, might be only in CVS)

SWFDisplayItem->scale() -- Scales the object in relative coordinates

Description

class SWFDisplayItem {

void scale ( int dx, int dy )

}

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.

swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->scaleTo()

Prev | Home | Next
SWFDisplayItem->rotateTo() | Up | SWFDisplayItem->scaleTo()


SWFDisplayItem->scaleTo()

(no version information, might be only in CVS)

SWFDisplayItem->scaleTo() -- Scales the object in global coordinates

Description

class SWFDisplayItem {

void scaleTo ( int x [, int y] )

}

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.

swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->scale()

Prev | Home | Next
SWFDisplayItem->scale() | Up | SWFDisplayItem->setDepth()


SWFDisplayItem->setDepth()

(no version information, might be only in CVS)

SWFDisplayItem->setDepth() -- Sets z-order

Description

class SWFDisplayItem {

void setDepth ( float depth )

}

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.

swfdisplayitem->setdepth() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by adding a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->scaleTo() | Up | SWFDisplayItem->setMaskLevel()


SWFDisplayItem->setName()

(no version information, might be only in CVS)

SWFDisplayItem->setName() -- Sets the object's name

Description

class SWFDisplayItem {

void setName ( string name )

}

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.

swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->setMatrix() | Up | SWFDisplayItem->setRatio()


SWFDisplayItem->setRatio()

(no version information, might be only in CVS)

SWFDisplayItem->setRatio() -- Sets the object's ratio

Description

class SWFDisplayItem {

void setRatio ( float ratio )

}

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.

swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Examples

This simple example will morph nicely three concentric circles.

Example 1. swfdisplayitem->setname() example

&#60;?php

$p = new SWFMorph();

$g = new SWFGradient();
$g-&#62;addEntry(0.0, 0, 0, 0);
$g-&#62;addEntry(0.16, 0xff, 0xff, 0xff);
$g-&#62;addEntry(0.32, 0, 0, 0);
$g-&#62;addEntry(0.48, 0xff, 0xff, 0xff);
$g-&#62;addEntry(0.64, 0, 0, 0);
$g-&#62;addEntry(0.80, 0xff, 0xff, 0xff);
$g-&#62;addEntry(1.00, 0, 0, 0);

$s = $p-&#62;getShape1();
$f = $s-&#62;addFill($g, SWFFILL_RADIAL_GRADIENT);
$f-&#62;scaleTo(0.05);
$s-&#62;setLeftFill($f);
$s-&#62;movePenTo(-160, -120);
$s-&#62;drawLine(320, 0);
$s-&#62;drawLine(0, 240);
$s-&#62;drawLine(-320, 0);
$s-&#62;drawLine(0, -240);

$g = new SWFGradient();
$g-&#62;addEntry(0.0, 0, 0, 0);
$g-&#62;addEntry(0.16, 0xff, 0, 0);
$g-&#62;addEntry(0.32, 0, 0, 0);
$g-&#62;addEntry(0.48, 0, 0xff, 0);
$g-&#62;addEntry(0.64, 0, 0, 0);
$g-&#62;addEntry(0.80, 0, 0, 0xff);
$g-&#62;addEntry(1.00, 0, 0, 0);

$s = $p-&#62;getShape2();
$f = $s-&#62;addFill($g, SWFFILL_RADIAL_GRADIENT);
$f-&#62;scaleTo(0.05);
$f-&#62;skewXTo(1.0);
$s-&#62;setLeftFill($f);
$s-&#62;movePenTo(-160, -120);
$s-&#62;drawLine(320, 0);
$s-&#62;drawLine(0, 240);
$s-&#62;drawLine(-320, 0);
$s-&#62;drawLine(0, -240);

$m = new SWFMovie();
$m-&#62;setDimension(320, 240);
$i = $m-&#62;add($p);
$i-&#62;moveTo(160, 120);

for ($n=0; $n&#60;=1.001; $n+=0.01) {
    $i-&#62;setRatio($n);
    $m-&#62;nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFDisplayItem->setName() | Up | SWFDisplayItem->skewX()


SWFDisplayItem->skewX()

(no version information, might be only in CVS)

SWFDisplayItem->skewX() -- Sets the X-skew

Description

class SWFDisplayItem {

void skewX ( float ddegrees )

}

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.

swfdisplayitem->skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->skewXTo()
SWFDisplayItem->skewY()
SWFDisplayItem->skewYTo()

Prev | Home | Next
SWFDisplayItem->setRatio() | Up | SWFDisplayItem->skewXTo()


SWFDisplayItem->skewXTo()

(no version information, might be only in CVS)

SWFDisplayItem->skewXTo() -- Sets the X-skew

Description

class SWFDisplayItem {

void skewXTo ( float degrees )

}

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.

swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->skewX()
SWFDisplayItem->skewY()
SWFDisplayItem->skewYTo()

Prev | Home | Next
SWFDisplayItem->skewX() | Up | SWFDisplayItem->skewY()


SWFDisplayItem->skewY()

(no version information, might be only in CVS)

SWFDisplayItem->skewY() -- Sets the Y-skew

Description

class SWFDisplayItem {

void skewY ( float ddegrees )

}

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.

swfdisplayitem->skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->skewYTo()
SWFDisplayItem->skewX()
SWFDisplayItem->skewXTo()

Prev | Home | Next
SWFDisplayItem->skewXTo() | Up | SWFDisplayItem->skewYTo()


SWFDisplayItem->skewYTo()

(no version information, might be only in CVS)

SWFDisplayItem->skewYTo() -- Sets the Y-skew

Description

class SWFDisplayItem {

void skewYTo ( float degrees )

}

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.

swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

SWFDisplayItem->skewY()
SWFDisplayItem->skewX()
SWFDisplayItem->skewXTo()

Prev | Home | Next
SWFDisplayItem->skewY() | Up | SWFFill


SWFFill->moveTo()

(no version information, might be only in CVS)

SWFFill->moveTo() -- Moves fill origin

Description

class SWFFill {

void moveTo ( int x, int y )

}

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.

Moves the fill origin to the given global coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.

Prev | Home | Next
SWFFill | Up | SWFFill->rotateTo()


SWFFill->rotateTo()

(no version information, might be only in CVS)

SWFFill->rotateTo() -- Sets fill's rotation

Description

class SWFFill {

void rotateTo ( float angle )

}

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.

Sets the fill rotation to the given angle.

Parameters

angle

The rotation angle, in degreess.

Return Values

No value is returned.

Prev | Home | Next
SWFFill->moveTo() | Up | SWFFill->scaleTo()


SWFFill->scaleTo()

(no version information, might be only in CVS)

SWFFill->scaleTo() -- Sets fill's scale

Description

class SWFFill {

void scaleTo ( int x [, int y] )

}

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.

Sets the fill scale to the given coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.

Prev | Home | Next
SWFFill->rotateTo() | Up | SWFFill->skewXTo()


SWFFill->skewXTo()

(no version information, might be only in CVS)

SWFFill->skewXTo() -- Sets fill x-skew

Description

class SWFFill {

void skewXTo ( float x )

}

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.

Sets the fill x-skew to x.

Parameters

x

When x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.

Return Values

No value is returned.

See Also

SWFFill->skewYTo()

Prev | Home | Next
SWFFill->scaleTo() | Up | SWFFill->skewYTo()


SWFFill->skewYTo()

(no version information, might be only in CVS)

SWFFill->skewYTo() -- Sets fill y-skew

Description

class SWFFill {

void skewYTo ( float y )

}

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.

Sets the fill y-skew to y.

Parameters

y

When y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.

Return Values

No value is returned.

See Also

SWFFill->skewXTo()

Prev | Home | Next
SWFFill->skewXTo() | Up | SWFFont


SWFFont->getWidth()

(no version information, might be only in CVS)

SWFFont->getWidth() -- Returns the string's width

Description

class SWFFont {

float getWidth ( string string )

}

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.

swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.

See Also

SWFFont->getUTF8Width()

Prev | Home | Next
SWFFont->getUTF8Width() | Up | SWFFontChar


SWFGradient->addEntry()

(no version information, might be only in CVS)

SWFGradient->addEntry() -- Adds an entry to the gradient list

Description

class SWFGradient {

void addEntry ( float ratio, int red, int green, int blue [, int a] )

}

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.

swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red, green, blue is a color (RGB mode). Last parameter a is optional.

Return Values

No value is returned.

Prev | Home | Next
SWFGradient->__construct() | Up | SWFMorph


SWFMorph->getShape1()

(no version information, might be only in CVS)

SWFMorph->getShape1() -- Gets a handle to the starting shape

Description

class SWFMorph {

SWFShape getShape1 ( void )

}

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.

Gets the morph's starting shape.

Return Values

Returns a SWFShape object.

See Also

SWFMorph->getShape2()

Prev | Home | Next
SWFMorph->__construct() | Up | SWFMorph->getShape2()


SWFMorph->getShape2()

(no version information, might be only in CVS)

SWFMorph->getShape2() -- Gets a handle to the ending shape

Description

class SWFMorph {

SWFShape getShape2 ( void )

}

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.

Gets the morph's ending shape.

Return Values

Returns a SWFShape object.

See Also

SWFMorph->getShape1()

Prev | Home | Next
SWFMorph->getShape1() | Up | SWFMovie


SWFMovie->add()

(no version information, might be only in CVS)

SWFMovie->add() -- Adds any type of data to a movie

Description

class SWFMovie {

mixed add ( object instance )

}

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.

Adds an SWF object instance to the current movie.

Parameters

instance

Any type of object instance, like SWFShape, SWFText, SWFFont.

Return Values

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem, a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

See Also

SWFMovie->remove()

Prev | Home | Next
SWFMovie->__construct() | Up | SWFMovie->addExport()


SWFMovie->nextFrame()

(no version information, might be only in CVS)

SWFMovie->nextFrame() -- Moves to the next frame of the animation

Description

class SWFMovie {

void nextFrame ( void )

}

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.

Moves to the next frame of the animation.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->labelFrame() | Up | SWFMovie->output()


SWFMovie->output()

(no version information, might be only in CVS)

SWFMovie->output() -- Dumps your lovingly prepared movie out

Description

class SWFMovie {

int output ( [int compression] )

}

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.

Dumps the SWFMovie.

Don't forget to send the Content-Type HTTP header file before using this function, in order to display the movie in a browser.

Parameters

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

Examples

Example 1. Displaying your $movie in a browser

&#60;?php
header('Content-type: application/x-shockwave-flash');
$movie-&#62;output();
?&#62;

See Also

SWFMovie->save()
SWFMovie->saveToFile()

Prev | Home | Next
SWFMovie->nextFrame() | Up | SWFMovie->remove()


SWFMovie->remove()

(no version information, might be only in CVS)

SWFMovie->remove() -- Removes the object instance from the display list

Description

class SWFMovie {

void remove ( object instance )

}

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.

Removes the given object instance from the display list.

Return Values

No value is returned.

See Also

SWFMovie->add()

Prev | Home | Next
SWFMovie->output() | Up | SWFMovie->save()


SWFMovie->save()

(no version information, might be only in CVS)

SWFMovie->save() -- Saves the SWF movie in a file

Description

class SWFMovie {

int save ( string filename [, int compression] )

}

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.

Saves the SWF movie to the specified filename.

Parameters

filename

The path to the saved SWF document.

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

SWFMovie->output()
SWFMovie->saveToFile()

Prev | Home | Next
SWFMovie->remove() | Up | SWFMovie->saveToFile()


SWFMovie->setbackground()

(no version information, might be only in CVS)

SWFMovie->setbackground() -- Sets the background color

Description

class SWFMovie {

void setbackground ( int red, int green, int blue )

}

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.

Sets the background color.

Why is there no rgba version? Think about it, you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->saveToFile() | Up | SWFMovie->setDimension()


SWFMovie->setDimension()

(no version information, might be only in CVS)

SWFMovie->setDimension() -- Sets the movie's width and height

Description

class SWFMovie {

void setDimension ( int width, int height )

}

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.

Sets the movie's dimension to the specified width and height.

Parameters

width

The movie width.

height

The movie height.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->setbackground() | Up | SWFMovie->setFrames()


SWFMovie->setFrames()

(no version information, might be only in CVS)

SWFMovie->setFrames() -- Sets the total number of frames in the animation

Description

class SWFMovie {

void setFrames ( int number )

}

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.

Sets the total number of frames in the animation to the given number.

Parameters

number

The number of frames.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->setDimension() | Up | SWFMovie->setRate()


SWFMovie->setRate()

(no version information, might be only in CVS)

SWFMovie->setRate() -- Sets the animation's frame rate

Description

class SWFMovie {

void setRate ( int rate )

}

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.

Sets the frame rate to the specified rate.

Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

Parameters

rate

The frame rate, in frame per seconds.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->setFrames() | Up | SWFMovie->startSound()


SWFMovie->streamMP3()

(no version information, might be only in CVS)

SWFMovie->streamMP3() -- Streams a MP3 file

Description

class SWFMovie {

void streamMP3 ( mixed mp3file )

}

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.

Streams the given MP3 file mp3file.

This method is not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it).

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Parameters

mp3file

Can be a file pointer returned by fopen() or the MP3 data, as a binary string.

Return Values

No value is returned.

Examples

Example 1. Streaming example

&#60;?php
$m = new SWFMovie();
$m-&#62;setRate(12.0);
$m-&#62;streamMp3(file_get_contents("distortobass.mp3"));
// use your own MP3

// The file is 11.85 seconds at 12.0 fps = 142 frames
$m-&#62;setFrames(142);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFMovie->stopSound() | Up | SWFMovie->writeExports()


SWFShape->addFill()

(no version information, might be only in CVS)

SWFShape->addFill() -- Adds a solid fill to the shape

Description

class SWFShape {

SWFFill addFill ( int red, int green, int blue [, int a] )

SWFFill addFill ( SWFBitmap bitmap [, int flags] )

SWFFill addFill ( SWFGradient gradient [, 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.

SWFShape->addFill() adds a solid fill to the shape's list of fill styles. SWFShape->addFill() accepts three different types of arguments.

red, green, blue is a color (RGB mode). Last parameter a is optional.

The bitmap argument is an SWFBitmap() object. The flags argument can be one of the following values: SWFFILL_CLIPPED_BITMAP, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.

The gradient argument is an SWFGradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

SWFShape->addFill() returns an SWFFill()
object for use with the SWFShape->setLeftFill()
and SWFShape->setRightFill() functions
described below.

Examples

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Example 1. SWFShape->addFill() example

&#60;?php

$p = new SWFMorph();

$b = new SWFBitmap(file_get_contents("alphafill.jpg"));
// use your own bitmap
$width = $b-&#62;getWidth();
$height = $b-&#62;getHeight();

$s = $p-&#62;getShape1();
$f = $s-&#62;addFill($b, SWFFILL_TILED_BITMAP);
$f-&#62;moveTo(-$width/2, -$height/4);
$f-&#62;scaleTo(1.0, 0.5);
$s-&#62;setLeftFill($f);
$s-&#62;movePenTo(-$width/2, -$height/4);
$s-&#62;drawLine($width, 0);
$s-&#62;drawLine(0, $height/2);
$s-&#62;drawLine(-$width, 0);
$s-&#62;drawLine(0, -$height/2);

$s = $p-&#62;getShape2();
$f = $s-&#62;addFill($b, SWFFILL_TILED_BITMAP);

// these two have no effect!
$f-&#62;moveTo(-$width/4, -$height/2);
$f-&#62;scaleTo(0.5, 1.0);

$s-&#62;setLeftFill($f);
$s-&#62;movePenTo(-$width/4, -$height/2);
$s-&#62;drawLine($width/2, 0);
$s-&#62;drawLine(0, $height);
$s-&#62;drawLine(-$width/2, 0);
$s-&#62;drawLine(0, -$height);

$m = new SWFMovie();
$m-&#62;setDimension($width, $height);
$i = $m-&#62;add($p);
$i-&#62;moveTo($width/2, $height/2);

for ($n=0; $n&#60;1.001; $n+=0.03) {
    $i-&#62;setRatio($n);
    $m-&#62;nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

See Also

SWFShape->setLeftFill()
SWFShape->setRightFill()

Prev | Home | Next
SWFShape->__construct() | Up | SWFShape->drawArc()


SWFShape->drawCurve()

(no version information, might be only in CVS)

SWFShape->drawCurve() -- Draws a curve (relative)

Description

class SWFShape {

int drawCurve ( int controldx, int controldy, int anchordx, int anchordy [, int targetdx, int targetdy] )

}

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.

swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (x+targetdx, x+targetdy) with control points (x+controldx, y+controldy) and (x+anchordx, y+anchordy).

See Also

SWFShape->drawCurve()

Prev | Home | Next
SWFShape->drawCubicTo() | Up | SWFShape->drawCurveTo()


SWFShape->drawCurveTo()

(no version information, might be only in CVS)

SWFShape->drawCurveTo() -- Draws a curve

Description

class SWFShape {

int drawCurveTo ( int controlx, int controly, int anchorx, int anchory [, int targetx, int targety] )

}

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.

swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (targetx, targety) with control points (controlx, controly) and (anchorx, anchory).

See Also

SWFShape->drawCurveTo()

Prev | Home | Next
SWFShape->drawCurve() | Up | SWFShape->drawGlyph()


SWFShape->drawLine()

(no version information, might be only in CVS)

SWFShape->drawLine() -- Draws a line (relative)

Description

class SWFShape {

void drawLine ( int dx, int dy )

}

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.

swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).

Return Values

No value is returned.

See Also

SWFShape->drawLineTo()

Prev | Home | Next
SWFShape->drawGlyph() | Up | SWFShape->drawLineTo()


SWFShape->drawLineTo()

(no version information, might be only in CVS)

SWFShape->drawLineTo() -- Draws a line

Description

class SWFShape {

void drawLineTo ( int x, int y )

}

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.

swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.

Return Values

No value is returned.

See Also

SWFShape->drawLine()

Prev | Home | Next
SWFShape->drawLine() | Up | SWFShape->movePen()


SWFShape->movePen()

(no version information, might be only in CVS)

SWFShape->movePen() -- Moves the shape's pen (relative)

Description

class SWFShape {

void movePen ( int dx, int dy )

}

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.

swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.

Return Values

No value is returned.

See Also

SWFShape->movePenTo()

Prev | Home | Next
SWFShape->drawLineTo() | Up | SWFShape->movePenTo()


SWFShape->movePenTo()

(no version information, might be only in CVS)

SWFShape->movePenTo() -- Moves the shape's pen

Description

class SWFShape {

void movePenTo ( int x, int y )

}

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.

swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

Return Values

No value is returned.

See Also

SWFShape->movePen()

Prev | Home | Next
SWFShape->movePen() | Up | SWFShape->setLeftFill()


SWFShape->setLeftFill()

(no version information, might be only in CVS)

SWFShape->setLeftFill() -- Sets left rasterizing color

Description

class SWFShape {

void setLeftFill ( SWFGradient fill )

void setLeftFill ( int red, int green, int blue [, int a] )

}

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.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

SWFShape->setRightFill()

Prev | Home | Next
SWFShape->movePenTo() | Up | SWFShape->setLine()


SWFShape->setLine()

(no version information, might be only in CVS)

SWFShape->setLine() -- Sets the shape's line style

Description

class SWFShape {

void setLine ( SWFShape shape )

void setLine ( int width, int red, int green, int blue [, int a] )

}

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.

swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.

You must declare all line styles before you use them (see example).

Return Values

No value is returned.

Examples

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Example 1. swfshape->setline() example

&#60;?php
$s = new SWFShape();
$f1 = $s-&#62;addFill(0xff, 0, 0);
$f2 = $s-&#62;addFill(0xff, 0x7f, 0);
$f3 = $s-&#62;addFill(0xff, 0xff, 0);
$f4 = $s-&#62;addFill(0, 0xff, 0);
$f5 = $s-&#62;addFill(0, 0, 0xff);

// bug: have to declare all line styles before you use them
$s-&#62;setLine(40, 0x7f, 0, 0);
$s-&#62;setLine(40, 0x7f, 0x3f, 0);
$s-&#62;setLine(40, 0x7f, 0x7f, 0);
$s-&#62;setLine(40, 0, 0x7f, 0);
$s-&#62;setLine(40, 0, 0, 0x7f);

$f = new SWFFont('Techno.fdb');

$s-&#62;setRightFill($f1);
$s-&#62;setLine(40, 0x7f, 0, 0);
$s-&#62;drawGlyph($f, '!');
$s-&#62;movePen($f-&#62;getWidth('!'), 0);

$s-&#62;setRightFill($f2);
$s-&#62;setLine(40, 0x7f, 0x3f, 0);
$s-&#62;drawGlyph($f, '#');
$s-&#62;movePen($f-&#62;getWidth('#'), 0);

$s-&#62;setRightFill($f3);
$s-&#62;setLine(40, 0x7f, 0x7f, 0);
$s-&#62;drawGlyph($f, '%');
$s-&#62;movePen($f-&#62;getWidth('%'), 0);

$s-&#62;setRightFill($f4);
$s-&#62;setLine(40, 0, 0x7f, 0);
$s-&#62;drawGlyph($f, '*');
$s-&#62;movePen($f-&#62;getWidth('*'), 0);

$s-&#62;setRightFill($f5);
$s-&#62;setLine(40, 0, 0, 0x7f);
$s-&#62;drawGlyph($f, '@');

$m = new SWFMovie();
$m-&#62;setDimension(3000,2000);
$m-&#62;setRate(12.0);
$i = $m-&#62;add($s);
$i-&#62;moveTo(1500-$f-&#62;getWidth("!#%*@")/2, 1000+$f-&#62;getAscent()/2);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Return Values

No value is returned.

Prev | Home | Next
SWFShape->setLeftFill() | Up | SWFShape->setRightFill()


SWFShape->setRightFill()

(no version information, might be only in CVS)

SWFShape->setRightFill() -- Sets right rasterizing color

Description

class SWFShape {

void setRightFill ( SWFGradient fill )

void setRightFill ( int red, int green, int blue [, int a] )

}

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.

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

SWFShape->setLeftFill()

Prev | Home | Next
SWFShape->setLine() | Up | SWFSound


SWFSprite->add()

(no version information, might be only in CVS)

SWFSprite->add() -- Adds an object to a sprite

Description

class SWFSprite {

void add ( object object )

}

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.

swfsprite->add() adds a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object.

For displayable types (swfshape(),
swfbutton(), swftext(),
swfaction() or swfsprite()),
this returns a handle  to the object in a display list.

Return Values

No value is returned.

Prev | Home | Next
SWFSprite->__construct() | Up | SWFSprite->labelFrame()


SWFSprite->nextFrame()

(no version information, might be only in CVS)

SWFSprite->nextFrame() -- Moves to the next frame of the animation

Description

class SWFSprite {

void nextFrame ( void )

}

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.

swfsprite->setframes() moves to the next frame of the animation.

Return Values

No value is returned.

Prev | Home | Next
SWFSprite->labelFrame() | Up | SWFSprite->remove()


SWFSprite->remove()

(no version information, might be only in CVS)

SWFSprite->remove() -- Removes an object to a sprite

Description

class SWFSprite {

void remove ( object object )

}

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.

swfsprite->remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

Return Values

No value is returned.

Prev | Home | Next
SWFSprite->nextFrame() | Up | SWFSprite->setFrames()


SWFSprite->setFrames()

(no version information, might be only in CVS)

SWFSprite->setFrames() -- Sets the total number of frames in the animation

Description

class SWFSprite {

void setFrames ( int number )

}

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.

swfsprite->setframes() sets the total number of frames in the animation to numberofframes.

Return Values

No value is returned.

Prev | Home | Next
SWFSprite->remove() | Up | SWFSprite->startSound()


SWFText->addString()

(no version information, might be only in CVS)

SWFText->addString() -- Draws a string

Description

class SWFText {

void addString ( string string )

}

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.

swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

Return Values

No value is returned.

See Also

SWFText->addUTF8String()

Prev | Home | Next
SWFText->__construct() | Up | SWFText->addUTF8String()


SWFText->getWidth()

(no version information, might be only in CVS)

SWFText->getWidth() -- Computes string's width

Description

class SWFText {

float getWidth ( string string )

}

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.

Returns the rendered width of the string at the text object's current font, scale, and spacing settings.

See Also

SWFText->getUTF8Width()

Prev | Home | Next
SWFText->getUTF8Width() | Up | SWFText->moveTo()


SWFText->moveTo()

(no version information, might be only in CVS)

SWFText->moveTo() -- Moves the pen

Description

class SWFText {

void moveTo ( int x, int y )

}

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.

swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

Return Values

No value is returned.

Prev | Home | Next
SWFText->getWidth() | Up | SWFText->setColor()


SWFText->setColor()

(no version information, might be only in CVS)

SWFText->setColor() -- Sets the current text color

Description

class SWFText {

void setColor ( int red, int green, int blue [, int a] )

}

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.

Changes the current text color.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

Prev | Home | Next
SWFText->moveTo() | Up | SWFText->setFont()


SWFText->setFont()

(no version information, might be only in CVS)

SWFText->setFont() -- Sets the current font

Description

class SWFText {

void setFont ( string font )

}

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.

swftext->setfont() sets the current font to font.

Return Values

No value is returned.

Prev | Home | Next
SWFText->setColor() | Up | SWFText->setHeight()


SWFText->setHeight()

(no version information, might be only in CVS)

SWFText->setHeight() -- Sets the current font height

Description

class SWFText {

void setHeight ( int height )

}

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.

swftext->setheight() sets the current font height to height. Default is 240.

Return Values

No value is returned.

Prev | Home | Next
SWFText->setFont() | Up | SWFText->setSpacing()


SWFText->setSpacing()

(no version information, might be only in CVS)

SWFText->setSpacing() -- Sets the current font spacing

Description

class SWFText {

void setSpacing ( float spacing )

}

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.

swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

Return Values

No value is returned.

Prev | Home | Next
SWFText->setHeight() | Up | SWFTextField


SWFTextField->addString()

(no version information, might be only in CVS)

SWFTextField->addString() -- Concatenates the given string to the text field

Description

class SWFTextField {

void addString ( string string )

}

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.

swftextfield->setname() concatenates the string string to the text field.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->addChars() | Up | SWFTextField->align()


SWFTextField->align()

(no version information, might be only in CVS)

SWFTextField->align() -- Sets the text field alignment

Description

class SWFTextField {

void align ( int alignement )

}

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.

swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->addString() | Up | SWFTextField->setBounds()


SWFTextField->setBounds()

(no version information, might be only in CVS)

SWFTextField->setBounds() -- Sets the text field width and height

Description

class SWFTextField {

void setBounds ( int width, int height )

}

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.

swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->align() | Up | SWFTextField->setColor()


SWFTextField->setColor()

(no version information, might be only in CVS)

SWFTextField->setColor() -- Sets the color of the text field

Description

class SWFTextField {

void setColor ( int red, int green, int blue [, int a] )

}

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.

swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setBounds() | Up | SWFTextField->setFont()


SWFTextField->setFont()

(no version information, might be only in CVS)

SWFTextField->setFont() -- Sets the text field font

Description

class SWFTextField {

void setFont ( string font )

}

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.

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setColor() | Up | SWFTextField->setHeight()


SWFTextField->setHeight()

(no version information, might be only in CVS)

SWFTextField->setHeight() -- Sets the font height of this text field font

Description

class SWFTextField {

void setHeight ( int height )

}

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.

swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setFont() | Up | SWFTextField->setIndentation()


SWFTextField->setIndentation()

(no version information, might be only in CVS)

SWFTextField->setIndentation() -- Sets the indentation of the first line

Description

class SWFTextField {

void setIndentation ( int width )

}

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.

swftextfield->setindentation() sets the indentation of the first line in the text field, to width.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setHeight() | Up | SWFTextField->setLeftMargin()


SWFTextField->setLeftMargin()

(no version information, might be only in CVS)

SWFTextField->setLeftMargin() -- Sets the left margin width of the text field

Description

class SWFTextField {

void setLeftMargin ( int width )

}

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.

swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setIndentation() | Up | SWFTextField->setLineSpacing()


SWFTextField->setLineSpacing()

(no version information, might be only in CVS)

SWFTextField->setLineSpacing() -- Sets the line spacing of the text field

Description

class SWFTextField {

void setLineSpacing ( int height )

}

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.

swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setLeftMargin() | Up | SWFTextField->setMargins()


SWFTextField->setMargins()

(no version information, might be only in CVS)

SWFTextField->setMargins() -- Sets the margins width of the text field

Description

class SWFTextField {

void setMargins ( int left, int right )

}

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.

swftextfield->setmargins() set both margins at once, for the man on the go.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setLineSpacing() | Up | SWFTextField->setName()


SWFTextField->setName()

(no version information, might be only in CVS)

SWFTextField->setName() -- Sets the variable name

Description

class SWFTextField {

void setName ( string name )

}

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.

swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setMargins() | Up | SWFTextField->setPadding()


SWFTextField->setRightMargin()

(no version information, might be only in CVS)

SWFTextField->setRightMargin() -- Sets the right margin width of the text field

Description

class SWFTextField {

void setRightMargin ( int width )

}

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.

swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setPadding() | Up | SWFVideoStream


Miscellaneous Functions

PHP Manual
Prev Next

LXXXVIII. Miscellaneous Functions

Introduction

These functions were placed here because none of the other categories seemed to fit.

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. Misc. Configuration Options

Name | Default | Changeable | Changelog
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.bg | "#FFFFFF" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

ignore_user_abort boolean

FALSE by default. If changed to TRUE scripts will not be terminated after a client has aborted their connection.

See also ignore_user_abort().

highlight.bg string, highlight.comment string, highlight.default string, highlight.html string, highlight.keyword string, highlight.string string

Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.

browscap string

Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().

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.

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

__COMPILER_HALT_OFFSET__ (integer)

Added in PHP 5.1.

Table of Contents
connection_aborted -- Returns TRUE if client disconnected
connection_status -- Returns connection status bitfield
connection_timeout -- Return TRUE if script timed out
constant -- Returns the value of a constant
define -- Defines a named constant
defined -- Checks whether a given named constant exists
die -- Equivalent to exit()
eval -- Evaluate a string as PHP code
exit -- Output a message and terminate the current script
get_browser -- Tells what the user's browser is capable of
__halt_compiler -- Halts the compiler execution
highlight_file -- Syntax highlighting of a file
highlight_string -- Syntax highlighting of a string
ignore_user_abort -- Set whether a client disconnect should abort script execution
pack -- Pack data into binary string
php_check_syntax -- Check the PHP syntax of (and execute) the specified file
php_strip_whitespace -- Return source with stripped comments and whitespace
show_source -- Alias of highlight_file()
sleep -- Delay execution
sys_getloadavg -- get average system load
time_nanosleep -- Delay for a number of seconds and nanoseconds
time_sleep_until -- Make the script sleep until the specified time
uniqid -- Generate a unique ID
unpack -- Unpack data from binary string
usleep -- Delay execution in microseconds

Prev | Home | Next
ming_useswfversion | Up | connection_aborted


connection_aborted

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

connection_aborted -- Returns TRUE if client disconnected

Description

int connection_aborted ( void )

Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.

See also connection_status(), and ignore_user_abort().

Prev | Home | Next
Miscellaneous Functions | Up | connection_status


connection_status

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

connection_status -- Returns connection status bitfield

Description

int connection_status ( void )

Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.

See also connection_aborted(), and ignore_user_abort().

Prev | Home | Next
connection_aborted | Up | connection_timeout


connection_timeout

(PHP 3 >= 3.0.7, PHP 4 <= 4.0.4)

connection_timeout -- Return TRUE if script timed out

Description

bool connection_timeout ( void )

Returns TRUE if script timed out.

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

See the Connection Handling description in the Features chapter for a complete explanation.

See also connection_status().

Prev | Home | Next
connection_status | Up | constant


constant

(PHP 4 >= 4.0.4, PHP 5)

constant -- Returns the value of a constant

Description

mixed constant ( string name )

constant() will return the value of the constant indicated by name.

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants.

Example 1. constant() example

&#60;?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

?&#62;

See also define(), defined() and the section on Constants.

Prev | Home | Next
connection_timeout | Up | define


define

(PHP 3, PHP 4, PHP 5)

define -- Defines a named constant

Description

bool define ( string name, mixed value [, bool case_insensitive] )

Defines a named constant at runtime. See the section on constants for more details.

The name of the constant is given by name; the value is given by value.

The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.

Example 1. Defining Constants

&#60;?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?&#62;

Returns TRUE on success or FALSE on failure.

See also defined(), constant() and the section on Constants.

Prev | Home | Next
constant | Up | defined


defined

(PHP 3, PHP 4, PHP 5)

defined -- Checks whether a given named constant exists

Description

bool defined ( string name )

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Example 1. Checking Constants

&#60;?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'CONSTANT' is the name of a constant named CONSTANT */
if (defined('CONSTANT')) {
    echo CONSTANT;
}
?&#62;

Note: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

See also define(),
constant(),
get_defined_constants(),
function_exists(), and the section on
Constants.

Prev | Home | Next
define | Up | die


die

(PHP 3, PHP 4, PHP 5)

die -- Equivalent to exit()

Description

This language construct is equivalent to exit().

Prev | Home | Next
defined | Up | eval


eval

(PHP 3, PHP 4, PHP 5)

eval -- Evaluate a string as PHP code

Description

mixed eval ( string code_str )

eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution. code_str does not have to contain PHP Opening tags.

There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str. To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.

Also remember that variables given values under eval() will retain these values in the main script afterwards.

A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In case of a parse error in the evaluated code, eval() returns FALSE. In case of a fatal error in the evaluated code, the whole script exits. In PHP 3, eval() does not return a value.

Example 1. eval() example - simple text merge

&#60;?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?&#62;

The above example will output:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions to capture the output of this function, and save it in a string (for example).

See also call_user_func().

Prev | Home | Next
die | Up | exit


exit

(PHP 3, PHP 4, PHP 5)

exit -- Output a message and terminate the current script

Description

void exit ( [string status] )

void exit ( int status )

Note: This is not a real function, but a language construct.

Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

The exit() function terminates execution of the script. It prints status just before exiting.

If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Example 1. exit() example

&#60;?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?&#62;

Example 2. exit() status example

&#60;?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?&#62;

Note: This language construct is equivalent to die().

See also: register_shutdown_function().

Prev | Home | Next
eval | Up | get_browser


get_browser

(PHP 3, PHP 4, PHP 5)

get_browser -- Tells what the user's browser is capable of

Description

mixed get_browser ( [string user_agent [, bool return_array]] )

get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file.

By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser(). You can bypass user_agent parameter with NULL value.

The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.

As of PHP 4.3.2, if the optional parameter return_array is TRUE, this function will return an array instead of an object.

Example 1. Listing all information about the users browser

&#60;?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?&#62;

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [css] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.

Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

Prev | Home | Next
exit | Up | __halt_compiler


highlight_file

(PHP 4, PHP 5)

highlight_file -- Syntax highlighting of a file

Description

mixed highlight_file ( string filename [, bool return] )

The highlight_file() function prints out a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.

Note: This function internally uses the output buffering with this parameter so it can not be used inside ob_start() callback function.

Note: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

Note: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.

Caution

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:

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

See also highlight_string().

Prev | Home | Next
__halt_compiler | Up | highlight_string


highlight_string

(PHP 4, PHP 5)

highlight_string -- Syntax highlighting of a string

Description

mixed highlight_string ( string str [, bool return] )

The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.

Note: This function internally uses the output buffering with this parameter so it can not be used inside ob_start() callback function.

Example 1. highlight_string() example

&#60;?php
highlight_string('&#60;?php phpinfo(); ?&#62;');
?&#62;

The above example will output (in PHP 4):

<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?&gt;</font>
</font>
</code>

The above example will output (in PHP 5):

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Note: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

See also highlight_file().

Prev | Home | Next
highlight_file | Up | ignore_user_abort


ignore_user_abort

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ignore_user_abort -- Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ( [bool setting] )

This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.

See also connection_aborted(), and connection_status().

Prev | Home | Next
highlight_string | Up | pack


pack

(PHP 3, PHP 4, PHP 5)

pack -- Pack data into binary string

Description

string pack ( string format [, mixed args [, mixed ...]] )

Pack given arguments into binary string according to format. Returns binary string containing data.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are

Table 1. pack() format characters

Code | Description
a | NUL-padded string
A | SPACE-padded string
h | Hex string, low nibble first
H | Hex string, high nibble first
c | signed char
C | unsigned char
s | signed short (always 16 bit, machine byte order)
S | unsigned short (always 16 bit, machine byte order)
n | unsigned short (always 16 bit, big endian byte order)
v | unsigned short (always 16 bit, little endian byte order)
i | signed integer (machine dependent size and byte order)
I | unsigned integer (machine dependent size and byte order)
l | signed long (always 32 bit, machine byte order)
L | unsigned long (always 32 bit, machine byte order)
N | unsigned long (always 32 bit, big endian byte order)
V | unsigned long (always 32 bit, little endian byte order)
f | float (machine dependent size and representation)
d | double (machine dependent size and representation)
x | NUL byte
X | Back up one byte
@ | NUL-fill to absolute position

Example 1. pack() example

&#60;?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?&#62;

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

See also unpack().

Prev | Home | Next
ignore_user_abort | Up | php_check_syntax


php_check_syntax

(PHP 5 <= 5.0.4)

php_check_syntax -- Check the PHP syntax of (and execute) the specified file

Description

bool php_check_syntax ( string file_name [, string &error_message] )

For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

The php_check_syntax() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline except php_check_syntax() will execute (but not output) the checked file_name. For example, if a function is defined in file_name, this defined function will be available to the file that executed php_check_syntax(), but output from file_name will be suppressed.

Parameters

file_name

The name of the file being checked.

error_message

If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.

Return Values

Returns TRUE if the lint check passed, and FALSE if the link check failed or if file_name cannot be opened.

ChangeLog

Version | Description
5.0.5 | This function was removed from PHP.
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault.
5.0.1 | error_message is passed by reference.

Examples

php -l somefile.php

The above example will output something similar to:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

See Also

include()
is_readable()

Prev | Home | Next
pack | Up | php_strip_whitespace


php_strip_whitespace

(PHP 5)

php_strip_whitespace -- Return source with stripped comments and whitespace

Description

string php_strip_whitespace ( string filename )

Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.

Note: This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report #29606.

Return Values

The stripped source code will be returned on success, or an empty string on failure.

Examples

Example 1. php_strip_whitespace() example

&#60;?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?&#62;

The above example will output:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.

Prev | Home | Next
php_check_syntax | Up | show_source


show_source

(PHP 4, PHP 5)

show_source -- Alias of highlight_file()

Description

This function is an alias of: highlight_file().

Prev | Home | Next
php_strip_whitespace | Up | sleep


sleep

(PHP 3, PHP 4, PHP 5)

sleep -- Delay execution

Description

int sleep ( int seconds )

The sleep() function delays program execution for the given number of seconds.

Example 1. sleep() example

&#60;?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?&#62;

This example will output (after 10 seconds)

05:31:23
05:31:33

See also usleep() and set_time_limit()

Prev | Home | Next
show_source | Up | sys_getloadavg


time_nanosleep

(PHP 5)

time_nanosleep -- Delay for a number of seconds and nanoseconds

Description

mixed time_nanosleep ( int seconds, int nanoseconds )

Delays program execution for the given number of seconds and nanoseconds.

seconds must be a positive integer, and nanoseconds must be a positive integer less than 1 billion.

Return Values

Returns TRUE on success or FALSE on failure.

If the delay was interrupted by a signal, an associative array will be returned with the components:

  • seconds - number of seconds remaining in the delay

  • nanoseconds - number of nanoseconds remaining in the delay

See Also

sleep(),
usleep(),
set_time_limit()

Examples

Example 1. time_nanosleep() example

&#60;?php
// Careful! This won't work as expected if an array is returned
if (time_nanosleep(0, 500000000)) {
    echo "Slept for half a second.\n";
}

// This is better:
if (time_nanosleep(0, 500000000) === true) {
    echo "Slept for half a second.\n";
}

// And this is the best:
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
    echo "Slept for 2 seconds, 100 milliseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?&#62;

Note: This function is not implemented on Windows platforms.

Prev | Home | Next
sys_getloadavg | Up | time_sleep_until


uniqid

(PHP 3, PHP 4, PHP 5)

uniqid -- Generate a unique ID

Description

string uniqid ( [string prefix [, bool more_entropy]] )

uniqid() returns a prefixed unique identifier based on the current time in microseconds. prefix became optional in PHP 5 but can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Up until PHP 4.3.1, prefix could only be a maximum of 114 characters long.

If the optional more_entropy parameter is TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.

With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

Note: The prefix parameter is required before PHP 5.

If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along these lines:

&#60;?php
// no prefix
// works only in PHP 5 and later versions
$token = md5(uniqid());

// better, difficult to guess
$better_token = md5(uniqid(rand(), true));
?&#62;

This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.

Prev | Home | Next
time_sleep_until | Up | unpack


unpack

(PHP 3, PHP 4, PHP 5)

unpack -- Unpack data from binary string

Description

array unpack ( string format, string data )

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

Example 1. unpack() example

&#60;?php
$array = unpack("c2chars/nint", $binarydata);
?&#62;

The resulting array will contain the entries "chars1", "chars2" and "int".

Caution

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

See also pack() for an explanation of the format codes.

Prev | Home | Next
uniqid | Up | usleep


usleep

(PHP 3, PHP 4, PHP 5)

usleep -- Delay execution in microseconds

Description

void usleep ( int micro_seconds )

The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.

Example 1. usleep() example

&#60;?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 seconds
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?&#62;

This script will output :

11:13:28
11:13:30

Note: This function did not work on Windows systems until PHP 5.0.0

See also sleep() and set_time_limit().

Prev | Home | Next
unpack | Up | mnoGoSearch Functions


mnoGoSearch Functions

PHP Manual
Prev Next

LXXXIX. mnoGoSearch Functions

Introduction

These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.

More information about mnoGoSearch can be found at http://www.mnogosearch.org/.

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

Download mnoGosearch from http://www.mnogosearch.org/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.

Installation

In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.

Note: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

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.

UDM_FIELD_URLID (integer)

UDM_FIELD_URL (integer)

UDM_FIELD_CONTENT (integer)

UDM_FIELD_TITLE (integer)

UDM_FIELD_KEYWORDS (integer)

UDM_FIELD_DESC (integer)

UDM_FIELD_DESCRIPTION (integer)

UDM_FIELD_TEXT (integer)

UDM_FIELD_SIZE (integer)

UDM_FIELD_RATING (integer)

UDM_FIELD_SCORE (integer)

UDM_FIELD_MODIFIED (integer)

UDM_FIELD_ORDER (integer)

UDM_FIELD_CRC (integer)

UDM_FIELD_CATEGORY (integer)

UDM_FIELD_LANG (integer)

UDM_FIELD_CHARSET (integer)

UDM_PARAM_PAGE_SIZE (integer)

UDM_PARAM_PAGE_NUM (integer)

UDM_PARAM_SEARCH_MODE (integer)

UDM_PARAM_CACHE_MODE (integer)

UDM_PARAM_TRACK_MODE (integer)

UDM_PARAM_PHRASE_MODE (integer)

UDM_PARAM_CHARSET (integer)

UDM_PARAM_LOCAL_CHARSET (integer)

UDM_PARAM_BROWSER_CHARSET (integer)

UDM_PARAM_STOPTABLE (integer)

UDM_PARAM_STOP_TABLE (integer)

UDM_PARAM_STOPFILE (integer)

UDM_PARAM_STOP_FILE (integer)

UDM_PARAM_WEIGHT_FACTOR (integer)

UDM_PARAM_WORD_MATCH (integer)

UDM_PARAM_MAX_WORD_LEN (integer)

UDM_PARAM_MAX_WORDLEN (integer)

UDM_PARAM_MIN_WORD_LEN (integer)

UDM_PARAM_MIN_WORDLEN (integer)

UDM_PARAM_ISPELL_PREFIXES (integer)

UDM_PARAM_ISPELL_PREFIX (integer)

UDM_PARAM_PREFIXES (integer)

UDM_PARAM_PREFIX (integer)

UDM_PARAM_CROSS_WORDS (integer)

UDM_PARAM_CROSSWORDS (integer)

UDM_PARAM_VARDIR (integer)

UDM_PARAM_DATADIR (integer)

UDM_PARAM_HLBEG (integer)

UDM_PARAM_HLEND (integer)

UDM_PARAM_SYNONYM (integer)

UDM_PARAM_SEARCHD (integer)

UDM_PARAM_QSTRING (integer)

UDM_PARAM_REMOTE_ADDR (integer)

UDM_LIMIT_CAT (integer)

UDM_LIMIT_URL (integer)

UDM_LIMIT_TAG (integer)

UDM_LIMIT_LANG (integer)

UDM_LIMIT_DATE (integer)

UDM_PARAM_FOUND (integer)

UDM_PARAM_NUM_ROWS (integer)

UDM_PARAM_WORDINFO (integer)

UDM_PARAM_WORD_INFO (integer)

UDM_PARAM_SEARCHTIME (integer)

UDM_PARAM_SEARCH_TIME (integer)

UDM_PARAM_FIRST_DOC (integer)

UDM_PARAM_LAST_DOC (integer)

UDM_MODE_ALL (integer)

UDM_MODE_ANY (integer)

UDM_MODE_BOOL (integer)

UDM_MODE_PHRASE (integer)

UDM_CACHE_ENABLED (integer)

UDM_CACHE_DISABLED (integer)

UDM_TRACK_ENABLED (integer)

UDM_TRACK_DISABLED (integer)

UDM_PHRASE_ENABLED (integer)

UDM_PHRASE_DISABLED (integer)

UDM_CROSS_WORDS_ENABLED (integer)

UDM_CROSSWORDS_ENABLED (integer)

UDM_CROSS_WORDS_DISABLED (integer)

UDM_CROSSWORDS_DISABLED (integer)

UDM_PREFIXES_ENABLED (integer)

UDM_PREFIX_ENABLED (integer)

UDM_ISPELL_PREFIXES_ENABLED (integer)

UDM_ISPELL_PREFIX_ENABLED (integer)

UDM_PREFIXES_DISABLED (integer)

UDM_PREFIX_DISABLED (integer)

UDM_ISPELL_PREFIXES_DISABLED (integer)

UDM_ISPELL_PREFIX_DISABLED (integer)

UDM_ISPELL_TYPE_AFFIX (integer)

UDM_ISPELL_TYPE_SPELL (integer)

UDM_ISPELL_TYPE_DB (integer)

UDM_ISPELL_TYPE_SERVER (integer)

UDM_MATCH_WORD (integer)

UDM_MATCH_BEGIN (integer)

UDM_MATCH_SUBSTR (integer)

UDM_MATCH_END (integer)

Table of Contents
udm_add_search_limit -- Add various search limits
udm_alloc_agent_array -- Allocate mnoGoSearch session
udm_alloc_agent -- Allocate mnoGoSearch session
udm_api_version -- Get mnoGoSearch API version
udm_cat_list -- Get all the categories on the same level with the current one
udm_cat_path -- Get the path to the current category
udm_check_charset -- Check if the given charset is known to mnogosearch
udm_check_stored -- Check connection to stored
udm_clear_search_limits -- Clear all mnoGoSearch search restrictions
udm_close_stored -- Close connection to stored
udm_crc32 -- Return CRC32 checksum of given string
udm_errno -- Get mnoGoSearch error number
udm_error -- Get mnoGoSearch error message
udm_find -- Perform search
udm_free_agent -- Free mnoGoSearch session
udm_free_ispell_data -- Free memory allocated for ispell data
udm_free_res -- Free mnoGoSearch result
udm_get_doc_count -- Get total number of documents in database
udm_get_res_field -- Fetch mnoGoSearch result field
udm_get_res_param -- Get mnoGoSearch result parameters
udm_hash32 -- Return Hash32 checksum of gived string
udm_load_ispell_data -- Load ispell data
udm_open_stored -- Open connection to stored
udm_set_agent_param -- Set mnoGoSearch agent session parameters

Prev | Home | Next
usleep | Up | udm_add_search_limit


udm_add_search_limit

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_add_search_limit -- Add various search limits

Description

bool udm_add_search_limit ( resource agent, int var, string val )

udm_add_search_limit() adds search restrictions. Returns TRUE on success or FALSE on failure.

agent - a link to Agent, received after call to udm_alloc_agent().

var - defines parameter, indicating limit.

val - defines the value of the current parameter.

Possible var values:

  • UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/catalog.

  • UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.

  • UDM_LIMIT_LANG - defines document language limitations.

  • UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the URL.

  • UDM_LIMIT_DATE - defines limitation by date the document was modified.

    Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:

    Example 1.

    &#60;?php
          Udm_Add_Search_Limit($udm, UDM_LIMIT_DATE, "&#38;lt;908012006");
    ?&#62;

    If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.

Prev | Home | Next
mnoGoSearch Functions | Up | udm_alloc_agent_array


udm_alloc_agent_array

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

udm_alloc_agent_array -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent_array ( array databases )

udm_alloc_agent_array() will create an agent with multiple database connections. The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

See also: udm_alloc_agent().

Prev | Home | Next
udm_add_search_limit | Up | udm_alloc_agent


udm_alloc_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_alloc_agent -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent ( string dbaddr [, string dbmode] )

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.

dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. When single is specified, all words are stored in the same table. If multi is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster, but requires more tables in the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires less disk space and it is faster comparing with "single" and "multi" modes. crc-multi uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like in "multi" mode.

Note: dbaddr and dbmode must match those used during indexing.

Note: In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().

Prev | Home | Next
udm_alloc_agent_array | Up | udm_api_version


udm_api_version

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_api_version -- Get mnoGoSearch API version

Description

int udm_api_version ( void )

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

This function allows the user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.

Example 1. udm_api_version() example

&#60;?php
if (udm_api_version() &#62;= 30111) {
    echo  "Total number of URLs in database: " . udm_get_doc_count($udm) . "&#60;br /&#62;\n";
}
?&#62;

Prev | Home | Next
udm_alloc_agent | Up | udm_cat_list


udm_cat_list

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

udm_cat_list -- Get all the categories on the same level with the current one

Description

array udm_cat_list ( resource agent, string category )

Returns an array listing all categories of the same level as the current category in the categories tree. agent is the agent identifier returned by a previous call to >udm_alloc_agent().

The function can be useful for developing categories tree browser.

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

$array[0] will contain '020300'
  $array[1] will contain 'Audi'
  $array[2] will contain '020301'
  $array[3] will contain 'BMW'
  $array[4] will contain '020302'
  $array[5] will contain 'Opel'
  ...
 etc.

Following is an example of displaying links of the current level in format:

Audi
  BMW
  Opel
  ...

Example 1. udm_cat_list()example

&#60;?php
 $cat_list_arr = udm_cat_list($udm_agent, $cat);
 $cat_list = '';
 for ($i=0; $i&#60;count($cat_list_arr); $i+=2) {
    $path = $cat_list_arr[$i];
    $name = $cat_list_arr[$i+1];
    $cat_list .= "&#60;a href=\"$_SERVER[PHP_SELF]?cat=$path\"&#62;$name&#60;/a&#62;&#60;br /&#62;";
 }
?&#62;

See also udm_cat_path().

Prev | Home | Next
udm_api_version | Up | udm_cat_path


udm_cat_path

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

udm_cat_path -- Get the path to the current category

Description

array udm_cat_path ( resource agent, string category )

Returns an array describing the path in the categories tree from the tree root to the current one, specified by category. agent is the agent identifier returned by a previous call to >udm_alloc_agent().

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:

$array[0] will contain ''
 $array[1] will contain 'Root'
 $array[2] will contain '02'
 $array[3] will contain 'Sport'
 $array[4] will contain '0203'
 $array[5] will contain 'Auto'
 $array[4] will contain '02031D'
 $array[5] will contain 'Ferrari'

Example 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

&#60;?php
  $cat_path_arr = udm_cat_path($udm_agent, $cat);
  $cat_path = '';
  for ($i=0; $i&#60;count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " &#62; &#60;a href=\"$_SERVER[PHP_SELF]?cat=$path\"&#62;$name&#60;/a&#62; ";
  }
?&#62;

See also udm_cat_list().

Prev | Home | Next
udm_cat_list | Up | udm_check_charset


udm_check_charset

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

udm_check_charset -- Check if the given charset is known to mnogosearch

Description

bool udm_check_charset ( resource agent, string charset )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
udm_cat_path | Up | udm_check_stored


udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored -- Check connection to stored

Description

int udm_check_stored ( resource agent, int link, string doc_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
udm_check_charset | Up | udm_clear_search_limits


udm_clear_search_limits

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_clear_search_limits -- Clear all mnoGoSearch search restrictions

Description

bool udm_clear_search_limits ( resource agent )

udm_clear_search_limits() resets defined search limitations and returns TRUE.

See also udm_add_search_limit().

Prev | Home | Next
udm_check_stored | Up | udm_close_stored


udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored -- Close connection to stored

Description

int udm_close_stored ( resource agent, int link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
udm_clear_search_limits | Up | udm_crc32


udm_crc32

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

udm_crc32 -- Return CRC32 checksum of given string

Description

int udm_crc32 ( resource agent, string str )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
udm_close_stored | Up | udm_errno


udm_errno

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_errno -- Get mnoGoSearch error number

Description

int udm_errno ( resource agent )

udm_errno() returns mnoGoSearch error number, zero if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving numeric agent error code.

Prev | Home | Next
udm_crc32 | Up | udm_error


udm_error

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_error -- Get mnoGoSearch error message

Description

string udm_error ( resource agent )

udm_error() returns mnoGoSearch error message, empty string if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving agent error message.

Prev | Home | Next
udm_errno | Up | udm_find


udm_find

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_find -- Perform search

Description

resource udm_find ( resource agent, string query )

Returns a result link identifier on success, or FALSE on failure.

The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.

mnoGoSearch understands the following boolean operators:

& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".

| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".

~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!

() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.

Prev | Home | Next
udm_error | Up | udm_free_agent


udm_free_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_agent -- Free mnoGoSearch session

Description

int udm_free_agent ( resource agent )

Returns TRUE on success or FALSE on failure.

agent - link to agent identifier, received ` after call to udm_alloc_agent().

Freeing up memory allocated for agent session.

Prev | Home | Next
udm_find | Up | udm_free_ispell_data


udm_free_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_ispell_data -- Free memory allocated for ispell data

Description

bool udm_free_ispell_data ( int agent )

udm_free_ispell_data() always returns TRUE.

agent - agent link identifier, received after call to udm_alloc_agent().

Note: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

Prev | Home | Next
udm_free_agent | Up | udm_free_res


udm_free_res

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_res -- Free mnoGoSearch result

Description

bool udm_free_res ( resource res )

Returns TRUE on success or FALSE on failure.

res - a link to result identifier, received after call to udm_find().

Freeing up memory allocated for results.

Prev | Home | Next
udm_free_ispell_data | Up | udm_get_doc_count


udm_get_doc_count

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_doc_count -- Get total number of documents in database

Description

int udm_get_doc_count ( resource agent )

udm_get_doc_count() returns the number of documents in the database.

agent - link to agent identifier, received after call to udm_alloc_agent().

Note: This function is supported only in mnoGoSearch 3.1.11 or later.

Prev | Home | Next
udm_free_res | Up | udm_get_res_field


udm_get_res_field

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_res_field -- Fetch mnoGoSearch result field

Description

string udm_get_res_field ( resource res, int row, int field )

udm_get_res_field() returns result field value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field

  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).

  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).

  • UDM_FIELD_TITLE - document title field.

  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).

  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).

  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).

  • UDM_FIELD_SIZE - document size.

  • UDM_FIELD_URLID - unique URL ID of the link.

  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).

  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.

  • UDM_FIELD_ORDER - the number of the current document in set of found documents.

  • UDM_FIELD_CRC - document CRC.

Prev | Home | Next
udm_get_doc_count | Up | udm_get_res_param


udm_get_res_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_res_param -- Get mnoGoSearch result parameters

Description

string udm_get_res_param ( resource res, int param )

udm_get_res_param() returns result parameter value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.

  • UDM_PARAM_FOUND - total number of results matching the query.

  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"

  • UDM_PARAM_SEARCHTIME - search time in seconds.

  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.

  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

Prev | Home | Next
udm_get_res_field | Up | udm_hash32


udm_hash32

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

udm_hash32 -- Return Hash32 checksum of gived string

Description

int udm_hash32 ( resource agent, string str )

udm_hash32() will take a string str and return a quite unique 32-bit hash number from it. Requires an allocated agent.

See also: udm_alloc_agent().

Prev | Home | Next
udm_get_res_param | Up | udm_load_ispell_data


udm_load_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_load_ispell_data -- Load ispell data

Description

bool udm_load_ispell_data ( resource agent, int var, string val1, string val2, int flag )

udm_load_ispell_data() loads ispell data. Returns TRUE on success or FALSE on failure.

agent - agent link identifier, received after call to udm_alloc_agent().

var - parameter, indicating the source for ispell data. May have the following values:

After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.

The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.

  • UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.

    Note: flag indicates that after loading ispell data from defined source it should be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().

    Example 1. udm_load_ispell_data()example

    &#60;?php
    if (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_DB, '', '', 1)) {
      printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
      exit;
    }
    ?&#62;

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Example 2. udm_load_ispell_data() example

    &#60;?php
    if ((! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
        (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
        (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
        (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
        exit;
    }
    ?&#62;

    Note: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    &#60;?php
         if ((! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
            (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
            (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
            (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
          exit;
          }
    ?&#62;

    Note: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.

    Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).

    udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.

    Note: This function is available in mnoGoSearch 3.1.12 or later.

    Example:

    &#60;?php
    if (!udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SERVER, '', '', 1)) {
        echo "Error loading ispell data from server&#60;br /&#62;\n";
        exit;
    }
    ?&#62;

Prev | Home | Next
udm_hash32 | Up | udm_open_stored


udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored -- Open connection to stored

Description

int udm_open_stored ( resource agent, string storedaddr )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
udm_load_ispell_data | Up | udm_set_agent_param


udm_set_agent_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_set_agent_param -- Set mnoGoSearch agent session parameters

Description

bool udm_set_agent_param ( resource agent, int var, string val )

Returns TRUE on success or FALSE on failure. Defines mnoGoSearch session parameters.

The following parameters and their values are available:

  • UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).

  • UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.

  • UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.

  • UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.

  • UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current Unix timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.

  • UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.

    Examples of phrase search:

    "Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase

  • UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...

  • UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the PHP script is executed.)

  • UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.

  • UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:

    URLWeight 1
    BodyWeight 2
    TitleWeight 4
    KeywordWeight 8
    DescWeight 16

    As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 aggregate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.

    This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:

    E is a factor for weight 1 (URL Weight bit)
    D is a factor for weight 2 (BodyWeight bit)
    C is a factor for weight 4 (TitleWeight bit)
    B is a factor for weight 8 (KeywordWeight bit)
    A is a factor for weight 16 (DescWeight bit)

    Examples:

    UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.

    UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.

    UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.

    UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:

    Description with factor 15 (F hex)
    Keywords with factor 9
    Title with factor 4
    Body with factor 2
    URL with factor 1

    If UDM_PARAM_WEIGHT_FACTOR variable is omitted, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.

  • UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:

    UDM_MATCH_BEGIN - word beginning match;

    UDM_MATCH_END - word ending match;

    UDM_MATCH_WORD - whole word match;

    UDM_MATCH_SUBSTR - word substring match.

  • UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.

  • UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().

  • UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.

    The crosswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.

    Note: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.

Prev | Home | Next
udm_open_stored | Up | Microsoft SQL Server Functions


Mohawk Software Session Handler Functions

PHP Manual
Prev Next

XCII. Mohawk Software Session Handler Functions

Introduction

msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at http://www.mohawksoft.org/?q=node/8.

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.1.3.

Requirements

Installation

To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.

Runtime Configuration

Resource Types

Predefined Constants

Table of Contents
msession_connect -- Connect to msession server
msession_count -- Get session count
msession_create -- Create a session
msession_destroy -- Destroy a session
msession_disconnect -- Close connection to msession server
msession_find -- Find all sessions with name and value
msession_get_array -- Get array of msession variables
msession_get_data -- Get data session unstructured data
msession_get -- Get value from session
msession_inc -- Increment value in session
msession_list -- List all sessions
msession_listvar -- List sessions with variable
msession_lock -- Lock a session
msession_plugin -- Call an escape function within the msession personality plugin
msession_randstr -- Get random string
msession_set_array -- Set msession variables from an array
msession_set_data -- Set data session unstructured data
msession_set -- Set value in session
msession_timeout -- Set/get session timeout
msession_uniq -- Get unique id
msession_unlock -- Unlock a session

Prev | Home | Next
PDO_DBLIB DSN | Up | msession_connect


msession_connect

(PHP 4 >= 4.2.0, PHP 5)

msession_connect -- Connect to msession server

Description

bool msession_connect ( string host, string port )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
Mohawk Software Session Handler Functions | Up | msession_count


msession_count

(PHP 4 >= 4.2.0, PHP 5)

msession_count -- Get session count

Description

int msession_count ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_connect | Up | msession_create


msession_create

(PHP 4 >= 4.2.0, PHP 5)

msession_create -- Create a session

Description

bool msession_create ( string session )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_count | Up | msession_destroy


msession_destroy

(PHP 4 >= 4.2.0, PHP 5)

msession_destroy -- Destroy a session

Description

bool msession_destroy ( string name )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_create | Up | msession_disconnect


msession_disconnect

(PHP 4 >= 4.2.0, PHP 5)

msession_disconnect -- Close connection to msession server

Description

void msession_disconnect ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_destroy | Up | msession_find


msession_find

(PHP 4 >= 4.2.0, PHP 5)

msession_find -- Find all sessions with name and value

Description

array msession_find ( string name, string value )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_disconnect | Up | msession_get_array


msession_get_array

(PHP 4 >= 4.2.0, PHP 5)

msession_get_array -- Get array of msession variables

Description

array msession_get_array ( string session )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_find | Up | msession_get_data


msession_get_data

(PHP 4 >= 4.2.0, PHP 5)

msession_get_data -- Get data session unstructured data

Description

string msession_get_data ( string session )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_get_array | Up | msession_get


msession_get

(PHP 4 >= 4.2.0, PHP 5)

msession_get -- Get value from session

Description

string msession_get ( string session, string name, string value )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_get_data | Up | msession_inc


msession_inc

(PHP 4 >= 4.2.0, PHP 5)

msession_inc -- Increment value in session

Description

string msession_inc ( string session, string name )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_get | Up | msession_list


msession_list

(PHP 4 >= 4.2.0, PHP 5)

msession_list -- List all sessions

Description

array msession_list ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_inc | Up | msession_listvar


msession_listvar

(PHP 4 >= 4.2.0, PHP 5)

msession_listvar -- List sessions with variable

Description

array msession_listvar ( string name )

Used for searching sessions with common attributes.

Return Values

Returns an associative array of value/session for all sessions with a variable named name.

Prev | Home | Next
msession_list | Up | msession_lock


msession_lock

(PHP 4 >= 4.2.0, PHP 5)

msession_lock -- Lock a session

Description

int msession_lock ( string name )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_listvar | Up | msession_plugin


msession_plugin

(PHP 4 >= 4.2.0, PHP 5)

msession_plugin -- Call an escape function within the msession personality plugin

Description

string msession_plugin ( string session, string val [, string param] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_lock | Up | msession_randstr


msession_randstr

(PHP 4 >= 4.2.0, PHP 5)

msession_randstr -- Get random string

Description

string msession_randstr ( int param )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_plugin | Up | msession_set_array


msession_set_array

(PHP 4 >= 4.2.0, PHP 5)

msession_set_array -- Set msession variables from an array

Description

void msession_set_array ( string session, array tuples )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_randstr | Up | msession_set_data


msession_set_data

(PHP 4 >= 4.2.0, PHP 5)

msession_set_data -- Set data session unstructured data

Description

bool msession_set_data ( string session, string value )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_set_array | Up | msession_set


msession_set

(PHP 4 >= 4.2.0, PHP 5)

msession_set -- Set value in session

Description

bool msession_set ( string session, string name, string value )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_set_data | Up | msession_timeout


msession_timeout

(PHP 4 >= 4.2.0, PHP 5)

msession_timeout -- Set/get session timeout

Description

int msession_timeout ( string session [, int param] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_set | Up | msession_uniq


msession_uniq

(PHP 4 >= 4.2.0, PHP 5)

msession_uniq -- Get unique id

Description

string msession_uniq ( int param )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_timeout | Up | msession_unlock


msession_unlock

(PHP 4 >= 4.2.0, PHP 5)

msession_unlock -- Unlock a session

Description

int msession_unlock ( string session, int key )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
msession_uniq | Up | mSQL Functions


mSQL Functions

PHP Manual
Prev Next

XCIII. mSQL Functions

Introduction

These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.

Installation

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/msql3.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy msql.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. mSQL configuration options

Name | Default | Changeable | Changelog
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.

Resource Types

There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource 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.

MSQL_ASSOC (integer)

MSQL_NUM (integer)

MSQL_BOTH (integer)

Examples

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Example 1. mSQL usage example

&#60;?php
/* Connecting, selecting database */
$link = msql_connect('localhost', 'username', 'password')
    or die('Could not connect : ' . msql_error($link));

msql_select_db('database', $link)
    or die('Could not select database');

/* Issue SQL query */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Query failed : ' . msql_error($link));

/* Printing results in HTML */
echo "&#60;table&#62;\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t&#60;tr&#62;\n";
    foreach ($row as $col_value) {
        echo "\t\t&#60;td&#62;$col_value&#60;/td&#62;\n";
    }
    echo "\t&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?&#62;

Table of Contents
msql_affected_rows -- Returns number of affected rows
msql_close -- Close mSQL connection
msql_connect -- Open mSQL connection
msql_create_db -- Create mSQL database
msql_createdb -- Alias of msql_create_db()
msql_data_seek -- Move internal row pointer
msql_db_query -- Send mSQL query
msql_dbname -- Alias of msql_result()
msql_drop_db -- Drop (delete) mSQL database
msql_error -- Returns error message of last msql call
msql_fetch_array -- Fetch row as array
msql_fetch_field -- Get field information
msql_fetch_object -- Fetch row as object
msql_fetch_row -- Get row as enumerated array
msql_field_flags -- Get field flags
msql_field_len -- Get field length
msql_field_name -- Get the name of the specified field in a result
msql_field_seek -- Set field offset
msql_field_table -- Get table name for field
msql_field_type -- Get field type
msql_fieldflags -- Alias of msql_field_flags()
msql_fieldlen -- Alias of msql_field_len()
msql_fieldname -- Alias of msql_field_name()
msql_fieldtable -- Alias of msql_field_table()
msql_fieldtype -- Alias of msql_field_type()
msql_free_result -- Free result memory
msql_list_dbs -- List mSQL databases on server
msql_list_fields -- List result fields
msql_list_tables -- List tables in an mSQL database
msql_num_fields -- Get number of fields in result
msql_num_rows -- Get number of rows in result
msql_numfields -- Alias of msql_num_fields()
msql_numrows -- Alias of msql_num_rows()
msql_pconnect -- Open persistent mSQL connection
msql_query -- Send mSQL query
msql_regcase -- Alias of sql_regcase()
msql_result -- Get result data
msql_select_db -- Select mSQL database
msql_tablename -- Alias of msql_result()
msql -- Alias of msql_db_query()

Prev | Home | Next
msession_unlock | Up | msql_affected_rows


msql_affected_rows

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

msql_affected_rows -- Returns number of affected rows

Description

int msql_affected_rows ( resource result )

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of affected rows on success, or FALSE on error.

See Also

msql_query()

Prev | Home | Next
mSQL Functions | Up | msql_close


msql_close

(PHP 3, PHP 4, PHP 5)

msql_close -- Close mSQL connection

Description

bool msql_close ( [resource link_identifier] )

msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.

Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_connect()
msql_pconnect()

Prev | Home | Next
msql_affected_rows | Up | msql_connect


msql_connect

(PHP 3, PHP 4, PHP 5)

msql_connect -- Open mSQL connection

Description

resource msql_connect ( [string hostname] )

msql_connect() establishes a connection to a mSQL server.

In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.

Note: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

msql_pconnect()
msql_close()

Prev | Home | Next
msql_close | Up | msql_create_db


msql_create_db

(PHP 3, PHP 4, PHP 5)

msql_create_db -- Create mSQL database

Description

bool msql_create_db ( string database_name [, resource link_identifier] )

msql_create_db() attempts to create a new database on the mSQL server.

Parameters

database_name

The name of the mSQL database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_drop_db()

Prev | Home | Next
msql_connect | Up | msql_createdb


msql_createdb

(PHP 3, PHP 4, PHP 5)

msql_createdb -- Alias of msql_create_db()

Description

This function is an alias of: msql_create_db().

Prev | Home | Next
msql_create_db | Up | msql_data_seek


msql_data_seek

(PHP 3, PHP 4, PHP 5)

msql_data_seek -- Move internal row pointer

Description

bool msql_data_seek ( resource result, int row_number )

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row_number

The seeked row number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_fetch_array()
msql_fetch_object()
msql_fetch_row()
msql_result()

Prev | Home | Next
msql_createdb | Up | msql_db_query


msql_db_query

(PHP 3, PHP 4, PHP 5)

msql_db_query -- Send mSQL query

Description

resource msql_db_query ( string database, string query [, resource link_identifier] )

msql_db_query() selects a database and executes a query on it.

Parameters

database

The name of the mSQL database.

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier to the query result, or FALSE on error.

See Also

msql_query()

Prev | Home | Next
msql_data_seek | Up | msql_dbname


msql_dbname

(PHP 3, PHP 4, PHP 5)

msql_dbname -- Alias of msql_result()

Description

This function is an alias of: msql_result().

Prev | Home | Next
msql_db_query | Up | msql_drop_db


msql_drop_db

(PHP 3, PHP 4, PHP 5)

msql_drop_db -- Drop (delete) mSQL database

Description

bool msql_drop_db ( string database_name [, resource link_identifier] )

msql_drop_db() attempts to drop (remove) a database from the mSQL server.

Parameters

database_name

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_create_db()

Prev | Home | Next
msql_dbname | Up | msql_error


msql_error

(PHP 3, PHP 4, PHP 5)

msql_error -- Returns error message of last msql call

Description

string msql_error ( void )

msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().

Return Values

The last error message or an empty string if no error was issued.

Prev | Home | Next
msql_drop_db | Up | msql_fetch_array


msql_fetch_array

(PHP 3, PHP 4, PHP 5)

msql_fetch_array -- Fetch row as array

Description

array msql_fetch_array ( resource result [, int result_type] )

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

result_type

A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example 1. msql_fetch_array() example

&#60;?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?&#62;

ChangeLog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

msql_fetch_row()
msql_fetch_object()
msql_data_seek()
msql_result()

Prev | Home | Next
msql_error | Up | msql_fetch_field


msql_fetch_field

(PHP 3, PHP 4, PHP 5)

msql_fetch_field -- Get field information

Description

object msql_fetch_field ( resource result [, int field_offset] )

msql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

Return Values

Returns an object containing field information. The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • unique - 1 if the column is a unique key

  • type - the type of the column

See Also

msql_field_seek()

Prev | Home | Next
msql_fetch_array | Up | msql_fetch_object


msql_fetch_object

(PHP 3, PHP 4, PHP 5)

msql_fetch_object -- Fetch row as object

Description

object msql_fetch_object ( resource result )

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_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. msql_fetch_object() example

&#60;?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_object($result, MSQL_ASSOC)) {
    echo $row-&#62;id . ': ' . $row-&#62;name . "\n";
}

msql_free_result($result);
?&#62;

ChangeLog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

msql_fetch_array()
msql_fetch_row()
msql_data_seek()
msql_result()

Prev | Home | Next
msql_fetch_field | Up | msql_fetch_row


msql_fetch_row

(PHP 3, PHP 4, PHP 5)

msql_fetch_row -- Get row as enumerated array

Description

array msql_fetch_row ( resource result )

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example 1. msql_fetch_row() example

&#60;?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_row($result)) {
    echo $row[0] . ': ' . $row[1] . "\n";
}

msql_free_result($result);
?&#62;

ChangeLog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

msql_fetch_array()
msql_fetch_object()
msql_data_seek()
msql_result()

Prev | Home | Next
msql_fetch_object | Up | msql_field_flags


msql_field_flags

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_flags -- Get field flags

Description

string msql_field_flags ( resource result, int field_offset )

msql_field_flags() returns the field flags of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.

Prev | Home | Next
msql_fetch_row | Up | msql_field_len


msql_field_len

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_len -- Get field length

Description

int msql_field_len ( resource result, int field_offset )

msql_field_len() returns the length of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns the length of the specified field or FALSE on error.

Prev | Home | Next
msql_field_flags | Up | msql_field_name


msql_field_name

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_name -- Get the name of the specified field in a result

Description

string msql_field_name ( resource result, int field_offset )

msql_field_name() gets the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the field or FALSE on failure.

See Also

msql_field_len()

Prev | Home | Next
msql_field_len | Up | msql_field_seek


msql_field_seek

(PHP 3, PHP 4, PHP 5)

msql_field_seek -- Set field offset

Description

bool msql_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_fetch_field()

Prev | Home | Next
msql_field_name | Up | msql_field_table


msql_field_table

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_table -- Get table name for field

Description

int msql_field_table ( resource result, int field_offset )

Returns the name of the table that the specified field is in.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the table on success, or FALSE on failure.

Prev | Home | Next
msql_field_seek | Up | msql_field_type


msql_field_type

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_type -- Get field type

Description

string msql_field_type ( resource result, int field_offset )

msql_field_type() gets the type of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.

Prev | Home | Next
msql_field_table | Up | msql_fieldflags


msql_fieldflags

(PHP 3, PHP 4, PHP 5)

msql_fieldflags -- Alias of msql_field_flags()

Description

This function is an alias of msql_field_flags().

Prev | Home | Next
msql_field_type | Up | msql_fieldlen


msql_fieldlen

(PHP 3, PHP 4, PHP 5)

msql_fieldlen -- Alias of msql_field_len()

Description

This function is an alias of msql_field_len().

Prev | Home | Next
msql_fieldflags | Up | msql_fieldname


msql_fieldname

(PHP 3, PHP 4, PHP 5)

msql_fieldname -- Alias of msql_field_name()

Description

This function is an alias of msql_field_name().

Prev | Home | Next
msql_fieldlen | Up | msql_fieldtable


msql_fieldtable

(PHP 3, PHP 4, PHP 5)

msql_fieldtable -- Alias of msql_field_table()

Description

This function is an alias of msql_field_table().

Prev | Home | Next
msql_fieldname | Up | msql_fieldtype


msql_fieldtype

(PHP 3, PHP 4, PHP 5)

msql_fieldtype -- Alias of msql_field_type()

Description

This function is an alias of msql_field_type().

Prev | Home | Next
msql_fieldtable | Up | msql_free_result


msql_free_result

(PHP 3, PHP 4, PHP 5)

msql_free_result -- Free result memory

Description

bool msql_free_result ( resource result )

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
msql_fieldtype | Up | msql_list_dbs


msql_list_dbs

(PHP 3, PHP 4, PHP 5)

msql_list_dbs -- List mSQL databases on server

Description

resource msql_list_dbs ( [resource link_identifier] )

msql_list_tables() lists the databases available on the specified link_identifier.

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

msql_list_tables()
msql_list_fields()

Prev | Home | Next
msql_free_result | Up | msql_list_fields


msql_list_fields

(PHP 3, PHP 4, PHP 5)

msql_list_fields -- List result fields

Description

resource msql_list_fields ( string database, string tablename [, resource link_identifier] )

msql_list_fields() returns information about the given table.

Parameters

database

The name of the database.

tablename

The name of the table.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

msql_list_tables()
msql_list_dbs()

Prev | Home | Next
msql_list_dbs | Up | msql_list_tables


msql_list_tables

(PHP 3, PHP 4, PHP 5)

msql_list_tables -- List tables in an mSQL database

Description

resource msql_list_tables ( string database [, resource link_identifier] )

msql_list_tables() lists the tables on the specified database.

Parameters

database

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

msql_list_fields()
msql_list_dbs()

Prev | Home | Next
msql_list_fields | Up | msql_num_fields


msql_num_fields

(PHP 3, PHP 4, PHP 5)

msql_num_fields -- Get number of fields in result

Description

int msql_num_fields ( resource result )

msql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of fields in the result set.

See Also

msql_query()
msql_fetch_field()
msql_num_rows()

Prev | Home | Next
msql_list_tables | Up | msql_num_rows


msql_num_rows

(PHP 3, PHP 4, PHP 5)

msql_num_rows -- Get number of rows in result

Description

int msql_num_rows ( resource query_identifier )

msql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of rows in the result set.

See Also

msql_num_fields()

Prev | Home | Next
msql_num_fields | Up | msql_numfields


msql_numfields

(PHP 3, PHP 4, PHP 5)

msql_numfields -- Alias of msql_num_fields()

Description

This function is an alias of msql_num_fields().

Prev | Home | Next
msql_num_rows | Up | msql_numrows


msql_numrows

(PHP 3, PHP 4, PHP 5)

msql_numrows -- Alias of msql_num_rows()

Description

This function is an alias of msql_num_rows().

Prev | Home | Next
msql_numfields | Up | msql_pconnect


msql_pconnect

(PHP 3, PHP 4, PHP 5)

msql_pconnect -- Open persistent mSQL connection

Description

resource msql_pconnect ( [string hostname] )

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by this function).

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.

Note: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

msql_connect()
msql_close()

Prev | Home | Next
msql_numrows | Up | msql_query


msql_query

(PHP 3, PHP 4, PHP 5)

msql_query -- Send mSQL query

Description

resource msql_query ( string query [, resource link_identifier] )

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier on success, or FALSE on error.

Examples

Example 1. msql_query() example

&#60;?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?&#62;

See Also

msql_db_query()
msql_select_db()
msql_connect()

Prev | Home | Next
msql_pconnect | Up | msql_regcase


msql_regcase

(PHP 3, PHP 4, PHP 5)

msql_regcase -- Alias of sql_regcase()

Description

This function is an alias of sql_regcase().

Prev | Home | Next
msql_query | Up | msql_result


msql_result

(PHP 3, PHP 4, PHP 5)

msql_result -- Get result data

Description

string msql_result ( resource result, int row [, mixed field] )

msql_result() returns the contents of one cell from a mSQL 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 are often much quicker than msql_result().

Recommended high-performance alternatives:
msql_fetch_row(),
msql_fetch_array(), and
msql_fetch_object().

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row

The row offset.

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname.). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

Note: Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.

Return Values

Returns the contents of the cell at the row and offset in the specified mSQL result set.

Prev | Home | Next
msql_regcase | Up | msql_select_db


msql_select_db

(PHP 3, PHP 4, PHP 5)

msql_select_db -- Select mSQL database

Description

bool msql_select_db ( string database_name [, resource link_identifier] )

msql_select_db() sets the current active database on the server that's associated with the specified link_identifier.

Subsequent calls to msql_query() will be made on the active database.

Parameters

database_name

The database name.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

msql_connect()
msql_pconnect()
msql_query()

Prev | Home | Next
msql_result | Up | msql_tablename


msql_tablename

(PHP 3, PHP 4, PHP 5)

msql_tablename -- Alias of msql_result()

Description

This function is an alias of msql_result().

Prev | Home | Next
msql_select_db | Up | msql


msql

(PHP 3, PHP 4, PHP 5)

msql -- Alias of msql_db_query()

Description

This function is an alias of msql_db_query().

Prev | Home | Next
msql_tablename | Up | Multibyte String Functions


Microsoft SQL Server Functions

PHP Manual
Prev Next

XC. Microsoft SQL Server Functions

Introduction

These functions allow you to access MS SQL Server database.

Requirements

Requirements for Win32 platforms.

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access. Configuration of the client will require installation of all the tools.

Requirements for Unix/Linux platforms.

To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: http://www.freetds.org/

Note: In Windows, the DBLIB from Microsoft is used. Functions that return a column name are based on the dbcolname() function in DBLIB. DBLIB was developed for SQL Server 6.x where the max identifier length is 30. For this reason, the maximum column length is 30 characters. On platforms where FreeTDS is used (Linux), this is not a problem.

Installation

The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

To get these functions to work, you have to compile PHP with --with-mssql[=DIR], where DIR is the FreeTDS install prefix. And FreeTDS should be compiled using --enable-msdblib.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. MS SQL Server configuration options

Name | Default | Changeable | Changelog
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Available since PHP 4.1.0.
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

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.

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

Table of Contents
mssql_bind -- Adds a parameter to a stored procedure or a remote stored procedure
mssql_close -- Close MS SQL Server connection
mssql_connect -- Open MS SQL server connection
mssql_data_seek -- Moves internal row pointer
mssql_execute -- Executes a stored procedure on a MS SQL server database
mssql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
mssql_fetch_assoc -- Returns an associative array of the current row in the result
mssql_fetch_batch -- Returns the next batch of records
mssql_fetch_field -- Get field information
mssql_fetch_object -- Fetch row as object
mssql_fetch_row -- Get row as enumerated array
mssql_field_length -- Get the length of a field
mssql_field_name -- Get the name of a field
mssql_field_seek -- Seeks to the specified field offset
mssql_field_type -- Gets the type of a field
mssql_free_result -- Free result memory
mssql_free_statement -- Free statement memory
mssql_get_last_message -- Returns the last message from the server
mssql_guid_string -- Converts a 16 byte binary GUID to a string
mssql_init -- Initializes a stored procedure or a remote stored procedure
mssql_min_error_severity -- Sets the lower error severity
mssql_min_message_severity -- Sets the lower message severity
mssql_next_result -- Move the internal result pointer to the next result
mssql_num_fields -- Gets the number of fields in result
mssql_num_rows -- Gets the number of rows in result
mssql_pconnect -- Open persistent MS SQL connection
mssql_query -- Send MS SQL query
mssql_result -- Get result data
mssql_rows_affected -- Returns the number of records affected by the query
mssql_select_db -- Select MS SQL database

Prev | Home | Next
udm_set_agent_param | Up | mssql_bind


mssql_bind

(PHP 4 >= 4.1.0, PHP 5)

mssql_bind -- Adds a parameter to a stored procedure or a remote stored procedure

Description

bool mssql_bind ( resource stmt, string param_name, mixed &var, int type [, int is_output [, int is_null [, int maxlen]]] )

Binds a parameter to a stored procedure or a remote stored procedure.

Parameters

stmt

Statement resource, obtained with mssql_init().

param_name

The parameter name, as a string.

Note: You have to include the @ character, like in the T-SQL syntax. See the explanation included in mssql_execute().

var

The PHP variable you'll bind the MSSQL parameter to. You can pass it by value, or by reference, to retrieve OUTPUT and RETVAL values after the procedure execution.

type

One of: SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4, SQLBIT, SQLFLT4, SQLFLT8, SQLFLTN.

is_output

Wether the value is an OUTPUT parameter or not. If it's an OUTPUT parameter and you don't mention it, it will be treated as a normal input parameter and no error will be thrown.

is_null

Wether the parameter is NULL or not. Passing the NULL value as var will not do the job.

maxlen

Used with char/varchar values. You have to indicate the length of the data so if the parameter is a varchar(50), the type must be SQLVARCHAR and this value 50.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mssql_bind() Example

&#60;?php

$cn = mssql_connect($DBSERVER, $DBUSER, $DBPASS);
mssql_select_db($DB, $cn);

$sp = mssql_init("WDumpAdd"); // stored proc name

mssql_bind($sp, "@productname", stripslashes($newproduct), SQLVARCHAR, false, false, 150);
mssql_bind($sp, "@quantity", stripslashes($newquantity), SQLVARCHAR, false, false, 50);

mssql_execute($sp);
mssql_close($cn);

?&#62;

See Also

mssql_execute()
mssql_free_statement()
mssql_init()

Prev | Home | Next
Microsoft SQL Server Functions | Up | mssql_close


mssql_close

(PHP 3, PHP 4, PHP 5)

mssql_close -- Close MS SQL Server connection

Description

bool mssql_close ( [resource link_identifier] )

Closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect().

This function will not close persistent links generated by mssql_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mssql_connect()
mssql_pconnect()

Prev | Home | Next
mssql_bind | Up | mssql_connect


mssql_connect

(PHP 3, PHP 4, PHP 5)

mssql_connect -- Open MS SQL server connection

Description

resource mssql_connect ( [string servername [, string username [, string password [, bool new_link]]]] )

mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mssql_close().

Parameters

servername

The MS SQL server. It can also include a port number. e.g. hostname:port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Return Values

Returns a MS SQL link identifier on success, or FALSE on error.

See Also

mssql_close()
mssql_pconnect()

Prev | Home | Next
mssql_close | Up | mssql_data_seek


mssql_data_seek

(PHP 3, PHP 4, PHP 5)

mssql_data_seek -- Moves internal row pointer

Description

bool mssql_data_seek ( resource result_identifier, int row_number )

mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number, first row being number 0. The next call to mssql_fetch_row() would return that row.

Parameters

result_identifier

The result resource that is being evaluated.

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
mssql_connect | Up | mssql_execute


mssql_execute

(PHP 4 >= 4.1.0, PHP 5)

mssql_execute -- Executes a stored procedure on a MS SQL server database

Description

mixed mssql_execute ( resource stmt [, bool skip_results] )

Executes a stored procedure on a MS SQL server database

Parameters

stmt

Statement handle obtained with mssql_init().

skip_results

Notes

Note: If the stored procedure returns parameters or a return value these will be available after the call to mssql_execute() unless the stored procedure returns more than one result set. In that case use mssql_next_result() to shift through the results. When the last result has been processed the output parameters and return values will be available.

See Also

mssql_bind()
mssql_free_statement()
mssql_init()

Prev | Home | Next
mssql_data_seek | Up | mssql_fetch_array


mssql_fetch_array

(PHP 3, PHP 4, PHP 5)

mssql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

Description

array mssql_fetch_array ( resource result [, int result_type] )

mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MSSQL_ASSOC, MSSQL_NUM, and the default value of MSSQL_BOTH.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See Also

mssql_fetch_row()

Prev | Home | Next
mssql_execute | Up | mssql_fetch_assoc


mssql_fetch_assoc

(PHP 4 >= 4.2.0, PHP 5)

mssql_fetch_assoc -- Returns an associative array of the current row in the result

Description

array mssql_fetch_assoc ( resource result_id )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mssql_fetch_assoc() is equivalent to calling mssql_fetch_array() with MSSQL_ASSOC for the optional second parameter.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Prev | Home | Next
mssql_fetch_array | Up | mssql_fetch_batch


mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5)

mssql_fetch_batch -- Returns the next batch of records

Description

int mssql_fetch_batch ( resource result )

Returns the next batch of records

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the batch number as an integer.

Examples

Example 1. mssql_fetch_batch() Example

&#60;?php

$resDb = mssql_connect('localhost', 'user', 'name');
$result = mssql_query('SELECT * FROM MYTABLE', $resDb, 10000);

$intNumRows = mssql_num_rows($result);

while ($intNumRows &#62; 0) {
    while ($arrRow = mssql_fetch_assoc($result)) {
        // Do stuff ...
    }
    $intNumRows = mssql_fetch_batch($result);
?&#62;

Prev | Home | Next
mssql_fetch_assoc | Up | mssql_fetch_field


mssql_fetch_field

(PHP 3, PHP 4, PHP 5)

mssql_fetch_field -- Get field information

Description

object mssql_fetch_field ( resource result [, int field_offset] )

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

Return Values

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.

  • column_source - the table from which the column was taken

  • max_length - maximum length of the column

  • numeric - 1 if the column is numeric

  • type - the column type.

See Also

mssql_field_seek()

Prev | Home | Next
mssql_fetch_batch | Up | mssql_fetch_object


mssql_fetch_object

(PHP 3, PHP 4, PHP 5)

mssql_fetch_object -- Fetch row as object

Description

object mssql_fetch_object ( resource result )

mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See Also

mssql_fetch_array()
mssql_fetch_row()

Prev | Home | Next
mssql_fetch_field | Up | mssql_fetch_row


mssql_fetch_row

(PHP 3, PHP 4, PHP 5)

mssql_fetch_row -- Get row as enumerated array

Description

array mssql_fetch_row ( resource result )

mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to mssql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: This function sets NULL fields to PHP NULL value.

See Also

mssql_fetch_array()
mssql_fetch_object()
mssql_data_seek()
mssql_fetch_lengths()
mssql_result()

Prev | Home | Next
mssql_fetch_object | Up | mssql_field_length


mssql_field_length

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_length -- Get the length of a field

Description

int mssql_field_length ( resource result [, int offset] )

Returns the length of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The length of the specified field index on success, or FALSE on failure.

Notes

Note to Win32 Users: Due to a limitation in the underlying API used by PHP (MS DbLib C API), the length of VARCHAR fields is limited to 255. If you need to store more data, use a TEXT field instead.

See Also

mssql_field_name()
mssql_field_type()

Prev | Home | Next
mssql_fetch_row | Up | mssql_field_name


mssql_field_name

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_name -- Get the name of a field

Description

string mssql_field_name ( resource result [, int offset] )

Returns the name of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The name of the specified field index on success, or FALSE on failure.

See Also

mssql_field_length()
mssql_field_type()

Prev | Home | Next
mssql_field_length | Up | mssql_field_seek


mssql_field_seek

(PHP 3, PHP 4, PHP 5)

mssql_field_seek -- Seeks to the specified field offset

Description

bool mssql_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The field offset, starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mssql_fetch_field()

Prev | Home | Next
mssql_field_name | Up | mssql_field_type


mssql_field_type

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_type -- Gets the type of a field

Description

string mssql_field_type ( resource result [, int offset] )

Returns the type of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The type of the specified field index on success, or FALSE on failure.

See Also

mssql_field_length()
mssql_field_name()

Prev | Home | Next
mssql_field_seek | Up | mssql_free_result


mssql_free_result

(PHP 3, PHP 4, PHP 5)

mssql_free_result -- Free result memory

Description

bool mssql_free_result ( resource result )

mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

The result resource that is being freed. This result comes from a call to mssql_query().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
mssql_field_type | Up | mssql_free_statement


mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5)

mssql_free_statement -- Free statement memory

Description

bool mssql_free_statement ( resource stmt )

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

Parameters

stmt

Statement resource, obtained with mssql_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mssql_bind()
mssql_execute()
mssql_init()

Prev | Home | Next
mssql_free_result | Up | mssql_get_last_message


mssql_get_last_message

(PHP 3, PHP 4, PHP 5)

mssql_get_last_message -- Returns the last message from the server

Description

string mssql_get_last_message ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mssql_free_statement | Up | mssql_guid_string


mssql_guid_string

(PHP 4 >= 4.1.0, PHP 5)

mssql_guid_string -- Converts a 16 byte binary GUID to a string

Description

string mssql_guid_string ( string binary [, int short_format] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mssql_get_last_message | Up | mssql_init


mssql_init

(PHP 4 >= 4.1.0, PHP 5)

mssql_init -- Initializes a stored procedure or a remote stored procedure

Description

resource mssql_init ( string sp_name [, resource link_identifier] )

Initializes a stored procedure or a remote stored procedure.

Parameters

sp_name

Stored procedure name, like ownew.sp_name or otherdb.owner.sp_name).

link_identifier

A MS SQL link identifier, returned by mssql_connect().

Return Values

Returns a resource identifier "statement", used in subsequent calls to mssql_bind() and mssql_execute(), or FALSE on errors.

See Also

mssql_bind()
mssql_execute()
mssql_free_statement()

Prev | Home | Next
mssql_guid_string | Up | mssql_min_error_severity


mssql_min_error_severity

(PHP 3, PHP 4, PHP 5)

mssql_min_error_severity -- Sets the lower error severity

Description

void mssql_min_error_severity ( int severity )

Warning

This function is currently not documented; only the argument list is available.

Parameters

severity

Return Values

No value is returned.

Prev | Home | Next
mssql_init | Up | mssql_min_message_severity


mssql_min_message_severity

(PHP 3, PHP 4, PHP 5)

mssql_min_message_severity -- Sets the lower message severity

Description

void mssql_min_message_severity ( int severity )

Warning

This function is currently not documented; only the argument list is available.

Parameters

severity

Return Values

No value is returned.

Prev | Home | Next
mssql_min_error_severity | Up | mssql_next_result


mssql_next_result

(PHP 4 >= 4.0.5, PHP 5)

mssql_next_result -- Move the internal result pointer to the next result

Description

bool mssql_next_result ( resource result_id )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example 1. mssql_next_result() example

&#60;?php
$link = mssql_connect("localhost", "userid", "secret");
mssql_select_db("MyDB", $link);
$sql = "Select * from table1 select * from table2";
$rs = mssql_query($sql, $link);
do {
    while ($row = mssql_fetch_row($rs)) {
    }
} while (mssql_next_result($rs));
mssql_free_result($rs);
mssql_close($link);
?&#62;

Prev | Home | Next
mssql_min_message_severity | Up | mssql_num_fields


mssql_num_fields

(PHP 3, PHP 4, PHP 5)

mssql_num_fields -- Gets the number of fields in result

Description

int mssql_num_fields ( resource result )

mssql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of fields, as an integer.

See Also

mssql_query()
mssql_fetch_field()
mssql_num_rows()

Prev | Home | Next
mssql_next_result | Up | mssql_num_rows


mssql_num_rows

(PHP 3, PHP 4, PHP 5)

mssql_num_rows -- Gets the number of rows in result

Description

int mssql_num_rows ( resource result )

mssql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of rows, as an integer.

See Also

mssql_query()
mssql_fetch_row()

Prev | Home | Next
mssql_num_fields | Up | mssql_pconnect


mssql_pconnect

(PHP 3, PHP 4, PHP 5)

mssql_pconnect -- Open persistent MS SQL connection

Description

resource mssql_pconnect ( [string servername [, string username [, string password [, bool new_link]]]] )

mssql_pconnect() acts very much like mssql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The MS SQL server. It can also include a port number. e.g. hostname:port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Return Values

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Prev | Home | Next
mssql_num_rows | Up | mssql_query


mssql_query

(PHP 3, PHP 4, PHP 5)

mssql_query -- Send MS SQL query

Description

mixed mssql_query ( string query [, resource link_identifier [, int batch_size]] )

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

A SQL query.

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.

batch_size

The number of records to batch in the buffer.

Return Values

Returns a MS SQL result resource on success, TRUE if no rows were returned, or FALSE on error.

See Also

mssql_select_db()
mssql_connect()

Prev | Home | Next
mssql_pconnect | Up | mssql_result


mssql_result

(PHP 3, PHP 4, PHP 5)

mssql_result -- Get result data

Description

string mssql_result ( resource result, int row, mixed field )

mssql_result() returns the contents of one cell from a MS SQL result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

row

The row number.

field

Can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.

Note: Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

Returns the contents of the specified cell.

Notes

Note: When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result().

See Also

Recommended high-performance alternatives:

mssql_fetch_row()
mssql_fetch_array()
mssql_fetch_object()

Prev | Home | Next
mssql_query | Up | mssql_rows_affected


mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5)

mssql_rows_affected -- Returns the number of records affected by the query

Description

int mssql_rows_affected ( resource link_identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

Prev | Home | Next
mssql_result | Up | mssql_select_db


mssql_select_db

(PHP 3, PHP 4, PHP 5)

mssql_select_db -- Select MS SQL database

Description

bool mssql_select_db ( string database_name [, resource link_identifier] )

mssql_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to mssql_query() will be made on the active database.

Parameters

database_name

The database name.

To escape the name of a database that contains spaces, hyphens ("-"), or any other exceptional characters, the database name must be enclosed in brackets, as is shown in the example, below. This technique must also be applied when selecting a database name that is also a reserved word (such as primary).

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mssql_select_db() example

&#60;?php
$conn = mssql_connect('MYSQLSERVER', 'sa', 'password');
mssql_select_db('[my data-base]', $conn);
?&#62;

See Also

mssql_connect()
mssql_pconnect()
mssql_query()

Prev | Home | Next
mssql_rows_affected | Up | Microsoft SQL Server and Sybase Functions (PDO_DBLIB)


muscat Functions

PHP Manual
Prev Next

XCV. muscat Functions

Introduction

This extension provides an interface to the Muscat 3.6 search system. Muscat doesn't exist anymore, but the Xapian project may provide you with a good alternative.

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.

Installation

These functions are only available if PHP was configured with --with-muscat[=DIR].

Table of Contents
muscat_close -- Shuts down the muscat session
muscat_get -- Gets a line back from the core muscat API
muscat_give -- Sends string to the core muscat API
muscat_setup_net -- Creates a new muscat session
muscat_setup -- Creates a new local muscat session

Prev | Home | Next
mb_substr | Up | muscat_close


muscat_close

(4.0.5 - 4.2.3 only, PECL)

muscat_close -- Shuts down the muscat session

Description

void muscat_close ( resource muscat_handle )

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.

Shuts down the muscat session and releases any memory back to PHP.

Parameters

muscat_handle

A muscat session handler, returned by muscat_setup() or muscat_setup_net().

Return Values

No value is returned.

See Also

muscat_setup()
muscat_setup_net()

Prev | Home | Next
muscat Functions | Up | muscat_get


muscat_get

(4.0.5 - 4.2.3 only, PECL)

muscat_get -- Gets a line back from the core muscat API

Description

string muscat_get ( resource muscat_handle )

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.

Gets a line back from the core muscat API.

Parameters

muscat_handle

A muscat session handler, returned by muscat_setup() or muscat_setup_net().

Return Values

Returns the muscat response, as a string.

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

muscat_give()

Prev | Home | Next
muscat_close | Up | muscat_give


muscat_give

(4.0.5 - 4.2.3 only, PECL)

muscat_give -- Sends string to the core muscat API

Description

void muscat_give ( resource muscat_handle, string string )

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.

Sends a string to the core muscat API.

Parameters

muscat_handle

A muscat session handler, returned by muscat_setup() or muscat_setup_net().

string

The string to be sent

Return Values

No value is returned.

See Also

muscat_get()

Prev | Home | Next
muscat_get | Up | muscat_setup_net


muscat_setup_net

(4.0.5 - 4.2.3 only, PECL)

muscat_setup_net -- Creates a new muscat session

Description

resource muscat_setup_net ( string muscat_host, int port )

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.

Creates a new muscat session.

Parameters

muscat_host

The host name to connect to

port

The port number to connect to

Return Values

Returns a session handler or FALSE on error.

See Also

muscat_setup()
muscat_close()

Prev | Home | Next
muscat_give | Up | muscat_setup


muscat_setup

(4.0.5 - 4.2.3 only, PECL)

muscat_setup -- Creates a new local muscat session

Description

resource muscat_setup ( int size [, string muscat_dir] )

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.

Creates a new local muscat session.

Parameters

size

The amount of memory in bytes to allocate for muscat

muscat_dir

The muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory.

Return Values

Returns a session handler or FALSE on error.

See Also

muscat_setup_net()
muscat_close()

Prev | Home | Next
muscat_setup_net | Up | MySQL Functions


MySQL Functions

PHP Manual
Prev Next

XCVI. MySQL Functions

Introduction

These functions allow you to access MySQL database servers. More information about MySQL can be found at http://www.mysql.com/.

Documentation for MySQL can be found at http://dev.mysql.com/doc/.

Requirements

In order to have these functions available, you must compile PHP with MySQL support.

Installation

For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installation directory.

Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these versions provide. For that, use the MySQLi extension.

If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.

Installation on Linux Systems

PHP 4

The option --with-mysql is enabled by default. This default behavior may be disabled with the --without-mysql configure option. If MySQL is enabled without specifying the path to the MySQL install DIR, PHP will use the bundled MySQL client libraries.

Users who run other applications that use MySQL (for example, auth-mysql) should not use the bundled library, but rather specify the path to MySQL's install directory, like so: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries installed by MySQL, thus avoiding any conflicts.

PHP 5+

MySQL is not enabled by default, nor is the MySQL library bundled with PHP. Read this FAQ for details on why. Use the --with-mysql[=DIR] configure option to include MySQL support. You can download headers and libraries from MySQL.

Installation on Windows Systems

PHP 4

The PHP MySQL extension is compiled into PHP.

PHP 5+

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. 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 libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended.

As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:\php\ext

Note: If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.

MySQL Installation Notes

Warning

Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.

Note: If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset support.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. MySQL Configuration Options

Name | Default | Changeable | Changelog
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Available since PHP 4.0.1.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

mysql.allow_persistent boolean

Whether to allow persistent connections to MySQL.

mysql.max_persistent integer

The maximum number of persistent MySQL connections per process.

mysql.max_links integer

The maximum number of MySQL connections per process, including persistent connections.

mysql.trace_mode boolean

Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0)

mysql.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

mysql.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysql.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in SQL safe mode.

mysql.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in SQL safe mode.

mysql.default_password string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in SQL safe mode.

mysql.connect_timeout integer

Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.

Resource Types

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource 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.

Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions. The following constants are defined:

Table 2. MySQL client constants

Constant | Description
MYSQL_CLIENT_COMPRESS | Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE | Allow space after function names
MYSQL_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection.
MYSQL_CLIENT_SSL | Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5.

The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

Table 3. MySQL fetch constants

Constant | Description
MYSQL_ASSOC | Columns are returned into the array having the fieldname as the array index.
MYSQL_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MYSQL_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Notes

Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE.

Examples

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

Example 1. MySQL extension overview example

&#60;?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "&#60;table&#62;\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t&#60;tr&#62;\n";
    foreach ($line as $col_value) {
        echo "\t\t&#60;td&#62;$col_value&#60;/td&#62;\n";
    }
    echo "\t&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?&#62;

Table of Contents
mysql_affected_rows -- Get number of affected rows in previous MySQL operation
mysql_change_user -- Change logged in user of the active connection
mysql_client_encoding -- Returns the name of the character set
mysql_close -- Close MySQL connection
mysql_connect -- Open a connection to a MySQL Server
mysql_create_db -- Create a MySQL database
mysql_data_seek -- Move internal result pointer
mysql_db_name -- Get result data
mysql_db_query -- Send a MySQL query
mysql_drop_db -- Drop (delete) a MySQL database
mysql_errno -- Returns the numerical value of the error message from previous MySQL operation
mysql_error -- Returns the text of the error message from previous MySQL operation
mysql_escape_string -- Escapes a string for use in a mysql_query
mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc -- Fetch a result row as an associative array
mysql_fetch_field -- Get column information from a result and return as an object
mysql_fetch_lengths -- Get the length of each output in a result
mysql_fetch_object -- Fetch a result row as an object
mysql_fetch_row -- Get a result row as an enumerated array
mysql_field_flags -- Get the flags associated with the specified field in a result
mysql_field_len -- Returns the length of the specified field
mysql_field_name -- Get the name of the specified field in a result
mysql_field_seek -- Set result pointer to a specified field offset
mysql_field_table -- Get name of the table the specified field is in
mysql_field_type -- Get the type of the specified field in a result
mysql_free_result -- Free result memory
mysql_get_client_info -- Get MySQL client info
mysql_get_host_info -- Get MySQL host info
mysql_get_proto_info -- Get MySQL protocol info
mysql_get_server_info -- Get MySQL server info
mysql_info -- Get information about the most recent query
mysql_insert_id -- Get the ID generated from the previous INSERT operation
mysql_list_dbs -- List databases available on a MySQL server
mysql_list_fields -- List MySQL table fields
mysql_list_processes -- List MySQL processes
mysql_list_tables -- List tables in a MySQL database
mysql_num_fields -- Get number of fields in result
mysql_num_rows -- Get number of rows in result
mysql_pconnect -- Open a persistent connection to a MySQL server
mysql_ping -- Ping a server connection or reconnect if there is no connection
mysql_query -- Send a MySQL query
mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement
mysql_result -- Get result data
mysql_select_db -- Select a MySQL database
mysql_stat -- Get current system status
mysql_tablename -- Get table name of field
mysql_thread_id -- Return the current thread ID
mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the result rows

Prev | Home | Next
muscat_setup | Up | mysql_affected_rows


mysql_affected_rows

(PHP 3, PHP 4, PHP 5)

mysql_affected_rows -- Get number of affected rows in previous MySQL operation

Description

int mysql_affected_rows ( [resource link_identifier] )

Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the number of affected rows on success, and -1 if the last query failed.

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 with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.

Examples

Example 1. mysql_affected_rows() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id &#60; 10');
printf("Records deleted: %d\n", mysql_affected_rows());

/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?&#62;

The above example will output something similar to:

Records deleted: 10
Records deleted: 0

Example 2. mysql_affected_rows() example using transactions

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id &#60; 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?&#62;

The above example will output something similar to:

Updated Records: 10

Notes

Transactions: If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT.

SELECT Statements: To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows().

See Also

mysql_num_rows()
mysql_info()

Prev | Home | Next
MySQL Functions | Up | mysql_change_user


mysql_change_user

(PHP 3 >= 3.0.13)

mysql_change_user -- Change logged in user of the active connection

Description

int mysql_change_user ( string user, string password [, string database [, resource link_identifier]] )

mysql_change_user() changes the logged in user of the current active connection, or the connection given by the optional link_identifier parameter. If a database is specified, this will be the current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.

This function is deprecated and no longer exists in PHP.

Parameters

user

The new MySQL username.

password

The new MySQL password.

database

The MySQL database. If not specified, the current selected database is used.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
3.0.14 | This function was removed from PHP.

Notes

Requirements: This function requires MySQL 3.23.3 or higher.

See Also

mysql_connect()
mysql_select_db()
mysql_query()

Prev | Home | Next
mysql_affected_rows | Up | mysql_client_encoding


mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding -- Returns the name of the character set

Description

string mysql_client_encoding ( [resource link_identifier] )

Retrieves the character_set variable from MySQL.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the default character set name for the current connection.

Examples

Example 1. mysql_client_encoding() example

&#60;?php
$link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "The current character set is: $charset\n";
?&#62;

The above example will output something similar to:

The current character set is: latin1

See Also

mysql_real_escape_string()

Prev | Home | Next
mysql_change_user | Up | mysql_close


mysql_close

(PHP 3, PHP 4, PHP 5)

mysql_close -- Close MySQL connection

Description

bool mysql_close ( [resource link_identifier] )

mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mysql_close() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?&#62;

The above example will output:

Connected successfully

Notes

Note: mysql_close() will not close persistent links created by mysql_pconnect().

See Also

mysql_connect()
mysql_free_result()

Prev | Home | Next
mysql_client_encoding | Up | mysql_connect


mysql_connect

(PHP 3, PHP 4, PHP 5)

mysql_connect -- Open a connection to a MySQL Server

Description

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )

Opens or reuses a connection to a MySQL server.

Parameters

server

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.

username

The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.

password

The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.

new_link

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.

client_flags

The client_flags parameter can be a combination of the following constants: MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about Table 2 for further information. In SQL safe mode, this parameter is ignored.

Return Values

Returns a MySQL link identifier on success, or FALSE on failure.

ChangeLog

Version | Description
4.3.0 | Added the client_flags parameter.
4.2.0 | Added the new_link parameter.
3.0.10 | Added support for ":/path/to/socket" with server.
3.0.0 | Added support for ":port" with server.

Examples

Example 1. mysql_connect() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?&#62;

Example 2. mysql_connect() example using hostname:port syntax

&#60;?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?&#62;

Example 3. mysql_connect() example using ":/path/to/socket" syntax

&#60;?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

//variant 1: ommit localhost
$link = mysql_connect('/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?&#62;

Notes

Note: Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as mysql.default_host string in your PHP configuration and leave the server field blank.

Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().

Note: You can suppress the error message on failure by prepending a @ to the function name.

See Also

mysql_pconnect()
mysql_close()

Prev | Home | Next
mysql_close | Up | mysql_create_db


mysql_create_db

(PHP 3, PHP 4, PHP 5)

mysql_create_db -- Create a MySQL database

Description

bool mysql_create_db ( string database_name [, resource link_identifier] )

mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Parameters

database_name

The name of the database being created.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mysql_create_db() alternative example

The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue a sql CREATE DATABASE statement instead.

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db created successfully\n";
} else {
    echo 'Error creating database: ' . mysql_error() . "\n";
}
?&#62;

The above example will output something similar to:

Database my_db created successfully

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_createdb()

Note: This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

See Also

mysql_query()
mysql_select_db()

Prev | Home | Next
mysql_connect | Up | mysql_data_seek


mysql_data_seek

(PHP 3, PHP 4, PHP 5)

mysql_data_seek -- Move internal result pointer

Description

bool mysql_data_seek ( resource result, int row_number )

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mysql_data_seek() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
    die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i &#62;= 0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Cannot seek to row $i: " . mysql_error() . "\n";
        continue;
    }

    if (!($row = mysql_fetch_assoc($result))) {
        continue;
    }

    echo $row['last_name'] . ' ' . $row['first_name'] . "&#60;br /&#62;\n";
}

mysql_free_result($result);
?&#62;

Notes

Note: The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query().

See Also

mysql_query()
mysql_num_rows()
mysql_fetch_row()
mysql_fetch_assoc()
mysql_fetch_array()
mysql_fetch_object()

Prev | Home | Next
mysql_create_db | Up | mysql_db_name


mysql_db_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mysql_db_name -- Get result data

Description

string mysql_db_name ( resource result, int row [, mixed field] )

Retrieve the database name from a call to mysql_list_dbs().

Parameters

result

The result pointer from a call to mysql_list_dbs().

row

The index into the result set.

field

The field name.

Return Values

Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error.

Examples

Example 1. mysql_db_name() example

&#60;?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i &#60; $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_dbname()

See Also

mysql_list_dbs()
mysql_tablename()

Prev | Home | Next
mysql_data_seek | Up | mysql_db_query


mysql_db_query

(PHP 3, PHP 4, PHP 5)

mysql_db_query -- Send a MySQL query

Description

resource mysql_db_query ( string database, string query [, resource link_identifier] )

mysql_db_query() selects a database, and executes a query on it.

Parameters

database

The name of the database that will be selected.

query

The MySQL query.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.

ChangeLog

Version | Description
4.0.6 | This function is deprecated, do not use this function. Use mysql_select_db() and mysql_query() instead.

Examples

Example 1. mysql_db_query() alternative example

&#60;?php

if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

if (!mysql_select_db('mysql_dbname', $link)) {
    echo 'Could not select database';
    exit;
}

$sql    = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['foo'];
}

mysql_free_result($result);

?&#62;

Notes

Note: Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db() instead of this function.

See Also

mysql_query()
mysql_select_db()

Prev | Home | Next
mysql_db_name | Up | mysql_drop_db


mysql_drop_db

(PHP 3, PHP 4, PHP 5)

mysql_drop_db -- Drop (delete) a MySQL database

Description

bool mysql_drop_db ( string database_name [, resource link_identifier] )

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue a sql DROP DATABASE statement instead.

Parameters

database_name

The name of the database that will be deleted.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mysql_drop_db() alternative example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db was successfully dropped\n";
} else {
    echo 'Error dropping database: ' . mysql_error() . "\n";
}
?&#62;

Notes

Warning

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

Note: For downward compatibility, the following deprecated alias may be used: mysql_dropdb()

See Also

mysql_query()

Prev | Home | Next
mysql_db_query | Up | mysql_errno


mysql_errno

(PHP 3, PHP 4, PHP 5)

mysql_errno -- Returns the numerical value of the error message from previous MySQL operation

Description

int mysql_errno ( [resource link_identifier] )

Returns the error number from the last MySQL function.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

Examples

Example 1. mysql_errno() example

&#60;?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!mysql_select_db("nonexistentdb", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?&#62;

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

mysql_error()
MySQL error codes

Prev | Home | Next
mysql_drop_db | Up | mysql_error


mysql_error

(PHP 3, PHP 4, PHP 5)

mysql_error -- Returns the text of the error message from previous MySQL operation

Description

string mysql_error ( [resource link_identifier] )

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.

Examples

Example 1. mysql_error() example

&#60;?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?&#62;

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

mysql_errno()
MySQL error codes

Prev | Home | Next
mysql_errno | Up | mysql_escape_string


mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string -- Escapes a string for use in a mysql_query

Description

string mysql_escape_string ( string unescaped_string )

This function will escape the unescaped_string, so that it is safe to place it in a mysql_query(). This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

Parameters

unescaped_string

The string that is to be escaped.

Return Values

Returns the escaped string.

ChangeLog

Version | Description
4.3.0 | This function became deprecated, do not use this function. Instead, use mysql_real_escape_string().

Examples

Example 1. mysql_escape_string() example

&#60;?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?&#62;

The above example will output:

Escaped string: Zak\'s Laptop

Notes

Note: mysql_escape_string() does not escape % and _.

See Also

mysql_real_escape_string()
addslashes()
The magic_quotes_gpc directive.

Prev | Home | Next
mysql_error | Up | mysql_fetch_array


mysql_fetch_array

(PHP 3, PHP 4, PHP 5)

mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

Description

array mysql_fetch_array ( resource result [, int result_type] )

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

Examples

Example 1. Query with aliased duplicate field names

SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Example 2. mysql_fetch_array() with MYSQL_NUM

&#60;?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);
}

mysql_free_result($result);
?&#62;

Example 3. mysql_fetch_array() with MYSQL_ASSOC

&#60;?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("ID: %s  Name: %s", $row["id"], $row["name"]);
}

mysql_free_result($result);
?&#62;

Example 4. mysql_fetch_array() with MYSQL_BOTH

&#60;?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf ("ID: %s  Name: %s", $row[0], $row["name"]);
}

mysql_free_result($result);
?&#62;

Notes

Performance: An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See Also

mysql_fetch_row()
mysql_fetch_assoc()
mysql_data_seek()
mysql_query()

Prev | Home | Next
mysql_escape_string | Up | mysql_fetch_assoc


mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc -- Fetch a result row as an associative array

Description

array mysql_fetch_assoc ( resource result )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_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 either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

Examples

Example 1. An expanded mysql_fetch_assoc() example

&#60;?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

?&#62;

Notes

Performance: An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See Also

mysql_fetch_row()
mysql_fetch_array()
mysql_data_seek()
mysql_query()
mysql_error()

Prev | Home | Next
mysql_fetch_array | Up | mysql_fetch_field


mysql_fetch_field

(PHP 3, PHP 4, PHP 5)

mysql_fetch_field -- Get column information from a result and return as an object

Description

object mysql_fetch_field ( resource result [, int field_offset] )

Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

Return Values

Returns an object containing field information. The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • def - default value of the column

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • primary_key - 1 if the column is a primary key

  • unique_key - 1 if the column is a unique key

  • multiple_key - 1 if the column is a non-unique key

  • numeric - 1 if the column is numeric

  • blob - 1 if the column is a BLOB

  • type - the type of the column

  • unsigned - 1 if the column is unsigned

  • zerofill - 1 if the column is zero-filled

Examples

Example 1. mysql_fetch_field() example

&#60;?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i &#60; mysql_num_fields($result)) {
    echo "Information for column $i:&#60;br /&#62;\n";
    $meta = mysql_fetch_field($result, $i);
    if (!$meta) {
        echo "No information available&#60;br /&#62;\n";
    }
    echo "&#60;pre&#62;
blob:         $meta-&#62;blob
max_length:   $meta-&#62;max_length
multiple_key: $meta-&#62;multiple_key
name:         $meta-&#62;name
not_null:     $meta-&#62;not_null
numeric:      $meta-&#62;numeric
primary_key:  $meta-&#62;primary_key
table:        $meta-&#62;table
type:         $meta-&#62;type
default:      $meta-&#62;def
unique_key:   $meta-&#62;unique_key
unsigned:     $meta-&#62;unsigned
zerofill:     $meta-&#62;zerofill
&#60;/pre&#62;";
    $i++;
}
mysql_free_result($result);
?&#62;

Notes

Note: Field names returned by this function are case-sensitive.

See Also

mysql_field_seek()

Prev | Home | Next
mysql_fetch_assoc | Up | mysql_fetch_lengths


mysql_fetch_lengths

(PHP 3, PHP 4, PHP 5)

mysql_fetch_lengths -- Get the length of each output in a result

Description

array mysql_fetch_lengths ( resource result )

Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths() stores the lengths of
each result column in the last row returned by
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at
offset 0.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

An array of lengths on success, or FALSE on failure.

Examples

Example 1. A mysql_fetch_lengths() example

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row     = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);

print_r($row);
print_r($lengths);
?&#62;

The above example will output something similar to:

Array
(
    [id] => 42
    [email] => user@example.com
)
Array
(
    [0] => 2
    [1] => 16
)

See Also

mysql_field_len()
mysql_fetch_row()
strlen()

Prev | Home | Next
mysql_fetch_field | Up | mysql_fetch_object


mysql_fetch_object

(PHP 3, PHP 4, PHP 5)

mysql_fetch_object -- Fetch a result row as an object

Description

object mysql_fetch_object ( resource result [, string class_name [, array params]] )

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

ChangeLog

Version | Description
5.0.0 | Added the ability to return as a different object.

Examples

Example 1. mysql_fetch_object() example

&#60;?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
    echo $row-&#62;user_id;
    echo $row-&#62;fullname;
}
mysql_free_result($result);
?&#62;

Example 2. mysql_fetch_object() example

&#60;?php

$row = mysql_fetch_object($result);

/* this is valid */
echo $row-&#62;field;
/* this is invalid */
// echo $row-&#62;0;

?&#62;

Notes

Performance: Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

Note: mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

See Also

mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_row()
mysql_data_seek()
mysql_query()

Prev | Home | Next
mysql_fetch_lengths | Up | mysql_fetch_row


mysql_fetch_row

(PHP 3, PHP 4, PHP 5)

mysql_fetch_row -- Get a result row as an enumerated array

Description

array mysql_fetch_row ( resource result )

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns an numerical array that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Examples

Example 1. Fetching one row with mysql_fetch_row()

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?&#62;

Notes

Note: This function sets NULL fields to PHP NULL value.

See Also

mysql_fetch_array()
mysql_fetch_assoc()
mysql_data_object()
mysql_data_seek()
mysql_fetch_lengths()
mysql_result()

Prev | Home | Next
mysql_fetch_object | Up | mysql_field_flags


mysql_field_flags

(PHP 3, PHP 4, PHP 5)

mysql_field_flags -- Get the flags associated with the specified field in a result

Description

string mysql_field_flags ( resource result, int field_offset )

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Returns a string of flags associated with the result, or FALSE on failure.

The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp".

Examples

Example 1. A mysql_field_flags() example

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$flags = mysql_field_flags($result, 0);

echo $flags;
print_r(explode(' ', $flags));
?&#62;

The above example will output something similar to:

not_null primary_key auto_increment
Array
(
    [0] => not_null
    [1] => primary_key
    [2] => auto_increment
)

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_fieldflags()

Prev | Home | Next
mysql_fetch_row | Up | mysql_field_len


mysql_field_len

(PHP 3, PHP 4, PHP 5)

mysql_field_len -- Returns the length of the specified field

Description

int mysql_field_len ( resource result, int field_offset )

mysql_field_len() returns the length of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The length of the specified field index on success, or FALSE on failure.

Examples

Example 1. mysql_field_len() example

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

// Will get the length of the id field as specified in the database
// schema.
$length = mysql_field_len($result, 0);
echo $length;
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_fieldlen()

See Also

mysql_fetch_lengths()
strlen()

Prev | Home | Next
mysql_field_flags | Up | mysql_field_name


mysql_field_name

(PHP 3, PHP 4, PHP 5)

mysql_field_name -- Get the name of the specified field in a result

Description

string mysql_field_name ( resource result, int field_offset )

mysql_field_name() returns the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the specified field index on success, or FALSE on failure.

Examples

Example 1. mysql_field_name() example

&#60;?php
/* The users table consists of three fields:
*   user_id
*   username
*   password.
*/
$link = @mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?&#62;

The above example will output:

user_id
password

Notes

Note: Field names returned by this function are case-sensitive.

Note: For downward compatibility, the following deprecated alias may be used: mysql_fieldname()

Prev | Home | Next
mysql_field_len | Up | mysql_field_seek


mysql_field_seek

(PHP 3, PHP 4, PHP 5)

mysql_field_seek -- Set result pointer to a specified field offset

Description

bool mysql_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

See Also

mysql_fetch_field()

Prev | Home | Next
mysql_field_name | Up | mysql_field_table


mysql_field_table

(PHP 3, PHP 4, PHP 5)

mysql_field_table -- Get name of the table the specified field is in

Description

string mysql_field_table ( resource result, int field_offset )

Returns the name of the table that the specified field is in.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the table on success.

Examples

Example 1. A mysql_field_table() example

&#60;?php
$result = mysql_query("SELECT name,comment FROM people,comments");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

// Assuming name is in the people table
$table = mysql_field_table($result, 'name');
echo $table; // people
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_fieldtable()

See Also

mysql_list_tables()

Prev | Home | Next
mysql_field_seek | Up | mysql_field_type


mysql_field_type

(PHP 3, PHP 4, PHP 5)

mysql_field_type -- Get the type of the specified field in a result

Description

string mysql_field_type ( resource result, int field_offset )

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation.

Examples

Example 1. mysql_field_type() example

&#60;?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i &#60; $fields; $i++) {
    $type  = mysql_field_type($result, $i);
    $name  = mysql_field_name($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?&#62;

The above example will output something similar to:

Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_fieldtype()

Prev | Home | Next
mysql_field_table | Up | mysql_free_result


mysql_free_result

(PHP 3, PHP 4, PHP 5)

mysql_free_result -- Free result memory

Description

bool mysql_free_result ( resource result )

mysql_free_result() will free all memory associated with the result identifier result.

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns TRUE on success or FALSE on failure.

If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

Examples

Example 1. A mysql_free_result() example

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
/* Use the result, assuming we're done with it afterwords */
$row = mysql_fetch_assoc($result);

/* Now we free up the result and continue on with our script */
mysql_free_result($result);

echo $row['id'];
echo $row['email'];
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_freeresult()

See Also

mysql_query()
is_resource()

Prev | Home | Next
mysql_field_type | Up | mysql_get_client_info


mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info -- Get MySQL client info

Description

string mysql_get_client_info ( void )

mysql_get_client_info() returns a string that represents the client library version.

Return Values

The MySQL client version.

Examples

Example 1. mysql_get_client_info() example

&#60;?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?&#62;

The above example will output something similar to:

MySQL client info: 3.23.39

See Also

mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()

Prev | Home | Next
mysql_free_result | Up | mysql_get_host_info


mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info -- Get MySQL host info

Description

string mysql_get_host_info ( [resource link_identifier] )

Describes the type of connection in use for the connection, including the server host name.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure.

Examples

Example 1. mysql_get_host_info() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?&#62;

The above example will output something similar to:

MySQL host info: Localhost via UNIX socket

See Also

mysql_get_client_info()
mysql_get_proto_info()
mysql_get_server_info()

Prev | Home | Next
mysql_get_client_info | Up | mysql_get_proto_info


mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info -- Get MySQL protocol info

Description

int mysql_get_proto_info ( [resource link_identifier] )

Retrieves the MySQL protocol.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the MySQL protocol on success, or FALSE on failure.

Examples

Example 1. mysql_get_proto_info() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?&#62;

The above example will output something similar to:

MySQL protocol version: 10

See Also

mysql_get_client_info()
mysql_get_host_info()
mysql_get_server_info()

Prev | Home | Next
mysql_get_host_info | Up | mysql_get_server_info


mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info -- Get MySQL server info

Description

string mysql_get_server_info ( [resource link_identifier] )

Retrieves the MySQL server version.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the MySQL server version on success, or FALSE on failure.

Examples

Example 1. mysql_get_server_info() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?&#62;

The above example will output something similar to:

MySQL server version: 4.0.1-alpha

See Also

mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
phpversion()

Prev | Home | Next
mysql_get_proto_info | Up | mysql_info


mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info -- Get information about the most recent query

Description

string mysql_info ( [resource link_identifier] )

Returns detailed information about the last query.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE.

Examples

Example 1. Relevant MySQL Statements

Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query.

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0

Notes

Note: mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

See Also

mysql_affected_rows()
mysql_insert_id()
mysql_stat()

Prev | Home | Next
mysql_get_server_info | Up | mysql_insert_id


mysql_insert_id

(PHP 3, PHP 4, PHP 5)

mysql_insert_id -- Get the ID generated from the previous INSERT operation

Description

int mysql_insert_id ( [resource link_identifier] )

Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

The ID generated for an AUTO_INCREMENT column by the previous INSERT query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

Examples

Example 1. mysql_insert_id() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?&#62;

Notes

Caution

mysql_insert_id() converts the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT, the value returned by mysql_insert_id() will be incorrect. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.

Note: Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Note: The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

See Also

mysql_query()
mysql_info()

Prev | Home | Next
mysql_info | Up | mysql_list_dbs


mysql_list_dbs

(PHP 3, PHP 4, PHP 5)

mysql_list_dbs -- List databases available on a MySQL server

Description

resource mysql_list_dbs ( [resource link_identifier] )

Returns a result pointer containing the databases available from the current mysql daemon.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Examples

Example 1. mysql_list_dbs() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
     echo $row-&#62;Database . "\n";
}
?&#62;

The above example will output something similar to:

database1
database2
database3

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_listdbs()

See Also

mysql_db_name()
mysql_select_db()

Prev | Home | Next
mysql_insert_id | Up | mysql_list_fields


mysql_list_fields

(PHP 3, PHP 4, PHP 5)

mysql_list_fields -- List MySQL table fields

Description

resource mysql_list_fields ( string database_name, string table_name [, resource link_identifier] )

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.

Parameters

database_name

The name of the database that's being queried.

table_name

The name of the table that's being queried.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

A result pointer resource on success, or FALSE on failure.

The returned result can be used with mysql_field_flags(),
mysql_field_len(),
mysql_field_name() and
mysql_field_type().

Examples

Example 1. Alternate to deprecated mysql_list_fields()

&#60;?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
if (mysql_num_rows($result) &#62; 0) {
    while ($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
?&#62;

The above example will output something similar to:

Array
(
    [Field] => id
    [Type] => int(7)
    [Null] =>
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment
)
Array
(
    [Field] => email
    [Type] => varchar(100)
    [Null] =>
    [Key] =>
    [Default] =>
    [Extra] =>
)

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_listfields()

See Also

mysql_field_flags()
mysql_info()

Prev | Home | Next
mysql_list_dbs | Up | mysql_list_processes


mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes -- List MySQL processes

Description

resource mysql_list_processes ( [resource link_identifier] )

Retrieves the current MySQL server threads.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

A result pointer resource on success, or FALSE on failure.

Examples

Example 1. mysql_list_processes() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
        $row["Command"], $row["Time"]);
}
mysql_free_result($result);
?&#62;

The above example will output something similar to:

1 localhost test Processlist 0
4 localhost mysql sleep 5

See Also

mysql_thread_id()
mysql_stat()

Prev | Home | Next
mysql_list_fields | Up | mysql_list_tables


mysql_list_tables

(PHP 3, PHP 4, PHP 5)

mysql_list_tables -- List tables in a MySQL database

Description

resource mysql_list_tables ( string database [, resource link_identifier] )

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parameters

database

The name of the database

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

A result pointer resource on success, or FALSE on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

ChangeLog

Version | Description
4.3.7 | This function became deprecated.

Examples

Example 1. mysql_list_tables() alternative example

&#60;?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_listtables()

See Also

mysql_list_dbs()
mysql_tablename()

Prev | Home | Next
mysql_list_processes | Up | mysql_num_fields


mysql_num_fields

(PHP 3, PHP 4, PHP 5)

mysql_num_fields -- Get number of fields in result

Description

int mysql_num_fields ( resource result )

Retrieves the number of fields from a query.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns the number of fields in the result set resource on success, or FALSE on failure.

Examples

Example 1. A mysql_num_fields() example

&#60;?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_numfields()

See Also

mysql_select_db()
mysql_query()
mysql_fetch_field()
mysql_num_rows()

Prev | Home | Next
mysql_list_tables | Up | mysql_num_rows


mysql_num_rows

(PHP 3, PHP 4, PHP 5)

mysql_num_rows -- Get number of rows in result

Description

int mysql_num_rows ( resource result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

The number of rows in a result set on success, or FALSE on failure.

Examples

Example 1. mysql_num_rows() example

&#60;?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?&#62;

Notes

Note: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

Note: For downward compatibility, the following deprecated alias may be used: mysql_numrows()

See Also

mysql_affected_rows()
mysql_connect()
mysql_data_seek()
mysql_select_db()
mysql_query()

Prev | Home | Next
mysql_num_fields | Up | mysql_pconnect


mysql_pconnect

(PHP 3, PHP 4, PHP 5)

mysql_pconnect -- Open a persistent connection to a MySQL server

Description

resource mysql_pconnect ( [string server [, string username [, string password [, int client_flags]]]] )

Establishes a persistent connection to a MySQL server.

mysql_pconnect() acts very much like mysql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

This type of link is therefore called 'persistent'.

Parameters

server

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'

username

The username. Default value is the name of the user that owns the server process.

password

The password. Default value is an empty password.

client_flags

The client_flags parameter can be a combination of the following constants: MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

Return Values

Returns a MySQL persistent link identifier on success, or FALSE on failure.

ChangeLog

Version | Description
4.3.0 | Added the client_flags parameter.
3.0.10 | Added support for ":/path/to/socket" with server.
3.0.0 | Added support for ":port" with server.

Notes

Note: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

Warning

Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.

Note: You can suppress the error message on failure by prepending a @ to the function name.

See Also

mysql_connect()
Persistent Database Connections

Prev | Home | Next
mysql_num_rows | Up | mysql_ping


mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping -- Ping a server connection or reconnect if there is no connection

Description

bool mysql_ping ( [resource link_identifier] )

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE.

Examples

Example 1. A mysql_ping() example

&#60;?php
set_time_limit(0);

$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db   = mysql_select_db('mydb');

/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
    echo 'Query #1 failed, exiting.';
    exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
    echo 'Lost connection, exiting after query #1';
    exit;
}
mysql_free_result($result);

/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?&#62;

See Also

mysql_thread_id()
mysql_list_processes()

Prev | Home | Next
mysql_pconnect | Up | mysql_query


mysql_query

(PHP 3, PHP 4, PHP 5)

mysql_query -- Send a MySQL query

Description

resource mysql_query ( string query [, resource link_identifier] )

mysql_query() sends an unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

Parameters

query

A SQL query

The query string should not end with a semicolon.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Examples

Example 1. Invalid Query

The following query is syntactically invalid, so mysql_query() fails and returns FALSE.

&#60;?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

?&#62;

Example 2. Valid Query

The following query is valid, so mysql_query() returns a resource.

&#60;?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

// Formulate Query
// This is the best way to perform a SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?&#62;

See Also

mysql_connect()
mysql_error()
mysql_real_escape_string()
mysql_result()
mysql_fetch_assoc()
mysql_unbuffered_query()

Prev | Home | Next
mysql_ping | Up | mysql_real_escape_string


mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement

Description

string mysql_real_escape_string ( string unescaped_string [, resource link_identifier] )

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Parameters

unescaped_string

The string that is to be escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the escaped string, or FALSE on error.

Examples

Example 1. Simple mysql_real_escape_string() example

&#60;?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?&#62;

Example 2. An example SQL Injection Attack

&#60;?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?&#62;

The query sent to MySQL:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Example 3. A "Best Practice" query

Using mysql_real_escape_string() around each variable prevents SQL Injection. This example demonstrates the "best practice" method for querying a database, independent of the Magic Quotes setting.

&#60;?php

if (isset($_POST['product_name']) &#38;&#38; isset($_POST['product_description']) &#38;&#38; isset($_POST['user_id'])) {
    // Connect

    $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');

    if(!is_resource($link)) {

        echo "Failed to connect to the server\n";
        // ... log the error properly

    } else {

        // Reverse magic_quotes_gpc effects on those vars if ON.

        if(get_magic_quotes_gpc()) {
            $product_name        = stripslashes($_POST['product_name']);
            $product_description = stripslashes($_POST['product_description']);
        } else {
            $product_name        = $_POST['product_name'];
            $product_description = $_POST['product_description'];
        }

        // Make a safe query
        $query = sprintf("INSERT INTO products (`name`, `description`, `user_id`) VALUES ('%s', '%s', '%d')",
                    mysql_real_escape_string($product_name, $link),
                    mysql_real_escape_string($product_description, $link),
                    $_POST['user_id']);

        mysql_query($query, $link);

        if (mysql_affected_rows($link) &#62; 0) {
            echo "Product inserted\n";
        }
    }
} else {
    echo "Fill the form properly\n";
}
?&#62;

The query will now execute correctly, and SQL Injection attacks will not work.

Notes

Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Note: If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

See Also

mysql_client_encoding()
addslashes()
stripslashes()
The magic_quotes_gpc directive
The magic_quotes_runtime directive

Prev | Home | Next
mysql_query | Up | mysql_result


mysql_result

(PHP 3, PHP 4, PHP 5)

mysql_result -- Get result data

Description

string mysql_result ( resource result, int row [, mixed field] )

Retrieves the contents of one cell from a MySQL result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

row

The row number from the result that's being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved.

It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

Return Values

The contents of one cell from a MySQL result set on success, or FALSE on failure.

Examples

Example 1. mysql_result() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
    die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name

mysql_close($link);
?&#62;

Notes

Note: Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

See Also

mysql_fetch_row()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_object()

Prev | Home | Next
mysql_real_escape_string | Up | mysql_select_db


mysql_select_db

(PHP 3, PHP 4, PHP 5)

mysql_select_db -- Select a MySQL database

Description

bool mysql_select_db ( string database_name [, resource link_identifier] )

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

Parameters

database_name

The name of the database that is to be selected.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. mysql_select_db() example

&#60;?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}
?&#62;

Notes

Note: For downward compatibility, the following deprecated alias may be used: mysql_createdb()

See Also

mysql_connect()
mysql_pconnect()
mysql_query()

Prev | Home | Next
mysql_result | Up | mysql_stat


mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat -- Get current system status

Description

string mysql_stat ( [resource link_identifier] )

mysql_stat() returns the current server status.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the SHOW STATUS SQL command. If link_identifier is invalid, NULL is returned.

Examples

Example 1. mysql_stat() example

&#60;?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$status = explode('  ', mysql_stat($link));
print_r($status);
?&#62;

The above example will output something similar to:

Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

Example 2. Alternative mysql_stat() example

&#60;?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SHOW VARIABLES', $link);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['Variable_name'] . ' = ' . $row['Value'] . "\n";
}
?&#62;

The above example will output something similar to:

back_log = 50
basedir = /usr/local/
bdb_cache_size = 8388600
bdb_log_buffer_size = 32768
bdb_home = /var/db/mysql/
bdb_max_lock = 10000
bdb_logdir =
bdb_shared_data = OFF
bdb_tmpdir = /var/tmp/
...

See Also

mysql_get_server_info()
mysql_list_processes()

Prev | Home | Next
mysql_select_db | Up | mysql_tablename


mysql_tablename

(PHP 3, PHP 4, PHP 5)

mysql_tablename -- Get table name of field

Description

string mysql_tablename ( resource result, int i )

Retrieves the table name from a result.

This function deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parameters

result

A result pointer resource that's returned from mysql_list_tables().

i

The integer index (row/table number)

Return Values

The name of the table on success, or FALSE on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Examples

Example 1. mysql_tablename() example

&#60;?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i &#60; $num_rows; $i++) {
    echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?&#62;

Notes

Note: The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

See Also

mysql_list_tables()
mysql_field_table()
mysql_db_name()

Prev | Home | Next
mysql_stat | Up | mysql_thread_id


mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id -- Return the current thread ID

Description

int mysql_thread_id ( [resource link_identifier] )

Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

The thread ID on success, or FALSE on failure.

Examples

Example 1. mysql_thread_id() example

&#60;?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf("current thread id is %d\n", $thread_id);
}
?&#62;

The above example will output something similar to:

current thread id is 73

See Also

mysql_ping()
mysql_list_processes()

Prev | Home | Next
mysql_tablename | Up | mysql_unbuffered_query


mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the result rows

Description

resource mysql_unbuffered_query ( string query [, resource link_identifier] )

mysql_unbuffered_query() sends a SQL query query to MySQL, without fetching and buffering the result rows automatically, as mysql_query() does. On the one hand, this saves a considerable amount of memory with SQL queries that produce large result sets. On the other hand, you can start working on the result set immediately after the first row has been retrieved: you don't have to wait until the complete SQL query has been performed. When using multiple DB-connects, you have to specify the optional parameter link_identifier.

Parameters

query

A SQL query

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns TRUE on success or FALSE on error.

Notes

Note: The benefits of mysql_unbuffered_query() come at a cost: You cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query(). You also have to fetch all result rows from an unbuffered SQL query, before you can send a new SQL query to MySQL.

See Also

mysql_query()

Prev | Home | Next
mysql_thread_id | Up | MySQL Functions (PDO_MYSQL)


MySQL Improved Extension

PHP Manual
Prev Next

XCVIII. MySQL Improved Extension

Introduction

The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at http://www.mysql.com/

Documentation for MySQL can be found at http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of MySQL AB.

Requirements

In order to have these functions available, you must compile PHP with support for the mysqli extension.

Note: The mysqli extension is designed to work with the version 4.1.3 or above of MySQL. For previous versions, please see the MySQL extension documentation.

Installation

To install the mysqli extension for PHP, use the --with-mysqli=mysql_config_path/mysql_config configuration option where mysql_config_path represents the location of the mysql_config program that comes with MySQL versions greater than 4.1.

If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.

Installation on Windows Systems

MySQLi is not enabled by default, so the php_mysqli.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. 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 libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended.

As with enabling any PHP extension (such as php_mysqli.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:\php\ext

Note: If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysqli.dll'", this is because php_mysqli.dll and/or libmysql.dll cannot be found by the system.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. MySQLi Configuration Options

Name | Default | Changeable | Changelog
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.

For further details and definitions of the above PHP_INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

mysqli.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysqli.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.

mysqli.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.

mysqli.default_pw string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.

Predefined Classes

mysqli

Represents a connection between PHP and a MySQL database.

Constructor

  • mysqli - construct a new mysqli object

Methods

  • autocommit - turns on or off auto-commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MySQL database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MySQL server

  • get_server_version - returns version of the MySQL server

  • init - initializes mysqli object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a mysql thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi-query

  • next_result - reads next result from currently executed multi-query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares a SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MySQL database server

  • escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • set_charset - sets the default client character set

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init- initializes a statement for use with mysqli_stmt_prepare

  • store_result - transfers a resultset from last query

  • thread_safe - returns whether thread safety is given or not

  • use_result - transfers an unbuffered resultset from last query

Properties

  • affected_rows - gets the number of affected rows in a previous MySQL operation

  • client_info - returns the MySQL client version as a string

  • client_version - returns the MySQL client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MySQL protocol used

  • server_info - returns a string that represents the server version number

  • server_version - returns the version number of the server as an integer

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

mysqli_stmt

Represents a prepared statement.

Methods

  • bind_param - binds variables to a prepared statement

  • bind_result - binds variables to a prepared statement for result storage

  • close - closes a prepared statement

  • data_seek - seeks to an arbitrary row in a statement result set

  • execute - executes a prepared statement

  • fetch - fetches result from a prepared statement into bound variables

  • free_result - frees stored result memory for the given statement handle

  • prepare - prepares a SQL query

  • reset - resets a prepared statement

  • result_metadata - retrieves a resultset from a prepared statement for metadata information

  • send_long_data - sends data in chunks

  • store_result - buffers complete resultset from a prepared statement

Properties

  • affected_rows - returns affected rows from last statement execution

  • errno - returns errorcode for last statement function

  • error - returns errormessage for last statement function

  • field_count - returns the number of columns in a result set

  • id - returns the statement identifier

  • insert_id - returns the value generated for an AUTO_INCREMENT column by the prepared statement

  • num_rows - returns the number of rows in the result set

  • param_count - returns number of parameter for a given prepare statement

  • sqlstate - returns a string containing the SQLSTATE error code for the last statement function

mysqli_result

Represents the result set obtained from a query against the database.

Methods

  • close - closes resultset

  • data_seek - moves internal result pointer

  • fetch_array - fetches a result row as an associative array, a numeric array, or both.

  • fetch_assoc - fetches a result row as an associative array

  • fetch_field - gets column information from a resultset

  • fetch_fields - gets information for all columns from a resulset

  • fetch_field_direct - gets column information for specified column

  • fetch_object - fetches a result row as an object

  • fetch_row - gets a result row as an enumerated array

  • field_seek - set result pointer to a specified field offset

  • free_result - frees result memory

Properties

  • current_field - returns offset of current fieldpointer

  • field_count - returns number of fields in resultset

  • lengths - returns an array of columnlengths

  • num_rows - returns number of rows in resultset

  • type - returns MYSQLI_STORE_RESULT or MYSQLI_USE_RESULT

Predefined Constants

Table 2. MySQLi Constants

Name | Description
MYSQLI_READ_DEFAULT_GROUP (integer) | Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE
MYSQLI_READ_DEFAULT_FILE (integer) | Read options from the named option file instead of from my.cnf
MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Connect timeout in seconds
MYSQLI_OPT_LOCAL_INFILE (integer) | Enables command LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND (integer) | Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.
MYSQLI_CLIENT_SSL (integer) | Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library
MYSQLI_CLIENT_COMPRESS (integer) | Use compression protocol
MYSQLI_CLIENT_INTERACTIVE (integer) | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.
MYSQLI_CLIENT_IGNORE_SPACE (integer) | Allow spaces after function names. Makes all functions names reserved words.
MYSQLI_CLIENT_NO_SCHEMA (integer) | Don't allow the db_name.tbl_name.col_name syntax.
MYSQLI_CLIENT_MULTI_QUERIES (integer) |
MYSQLI_STORE_RESULT (integer) | For using buffered resultsets
MYSQLI_USE_RESULT (integer) | For using unbuffered resultsets
MYSQLI_ASSOC (integer) | Columns are returned into the array having the fieldname as the array index.
MYSQLI_NUM (integer) | Columns are returned into the array having an enumerated index.
MYSQLI_BOTH (integer) | Columns are returned into the array having both a numerical index and the fieldname as the associative index.
MYSQLI_NOT_NULL_FLAG (integer) | Indicates that a field is defined as NOT NULL
MYSQLI_PRI_KEY_FLAG (integer) | Field is part of a primary index
MYSQLI_UNIQUE_KEY_FLAG (integer) | Field is part of a unique index.
MYSQLI_MULTIPLE_KEY_FLAG (integer) | Field is part of an index.
MYSQLI_BLOB_FLAG (integer) | Field is defined as BLOB
MYSQLI_UNSIGNED_FLAG (integer) | Field is defined as UNSIGNED
MYSQLI_ZEROFILL_FLAG (integer) | Field is defined as ZEROFILL
MYSQLI_AUTO_INCREMENT_FLAG (integer) | Field is defined as AUTO_INCREMENT
MYSQLI_TIMESTAMP_FLAG (integer) | Field is defined as TIMESTAMP
MYSQLI_SET_FLAG (integer) | Field is defined as SET
MYSQLI_NUM_FLAG (integer) | Field is defined as NUMERIC
MYSQLI_PART_KEY_FLAG (integer) | Field is part of an multi-index
MYSQLI_GROUP_FLAG (integer) | Field is part of GROUP BY
MYSQLI_TYPE_DECIMAL (integer) | Field is defined as DECIMAL
MYSQLI_TYPE_NEWDECIMAL (integer) | Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)
MYSQLI_TYPE_BIT (integer) | Field is defined as BIT (MySQL 5.0.3 and up)
MYSQLI_TYPE_TINY (integer) | Field is defined as TINYINT
MYSQLI_TYPE_SHORT (integer) | Field is defined as INT
MYSQLI_TYPE_LONG (integer) | Field is defined as INT
MYSQLI_TYPE_FLOAT (integer) | Field is defined as FLOAT
MYSQLI_TYPE_DOUBLE (integer) | Field is defined as DOUBLE
MYSQLI_TYPE_NULL (integer) | Field is defined as DEFAULT NULL
MYSQLI_TYPE_TIMESTAMP (integer) | Field is defined as TIMESTAMP
MYSQLI_TYPE_LONGLONG (integer) | Field is defined as BIGINT
MYSQLI_TYPE_INT24 (integer) | Field is defined as MEDIUMINT
MYSQLI_TYPE_DATE (integer) | Field is defined as DATE
MYSQLI_TYPE_TIME (integer) | Field is defined as TIME
MYSQLI_TYPE_DATETIME (integer) | Field is defined as DATETIME
MYSQLI_TYPE_YEAR (integer) | Field is defined as YEAR
MYSQLI_TYPE_NEWDATE (integer) | Field is defined as DATE
MYSQLI_TYPE_ENUM (integer) | Field is defined as ENUM
MYSQLI_TYPE_SET (integer) | Field is defined as SET
MYSQLI_TYPE_TINY_BLOB (integer) | Field is defined as TINYBLOB
MYSQLI_TYPE_MEDIUM_BLOB (integer) | Field is defined as MEDIUMBLOB
MYSQLI_TYPE_LONG_BLOB (integer) | Field is defined as LONGBLOB
MYSQLI_TYPE_BLOB (integer) | Field is defined as BLOB
MYSQLI_TYPE_VAR_STRING (integer) | Field is defined as VARCHAR
MYSQLI_TYPE_STRING (integer) | Field is defined as CHAR
MYSQLI_TYPE_GEOMETRY (integer) | Field is defined as GEOMETRY
MYSQLI_NEED_DATA (integer) | More data available for bind variable
MYSQLI_NO_DATA (integer) | No more data available for bind variable
MYSQLI_DATA_TRUNCATED (integer) | Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

Examples

All Examples in the MySQLI documentation use the world database from MySQL AB. The world database can be found at http://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick

Table of Contents
mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation
mysqli_autocommit -- Turns on or off auto-commiting database modifications
mysqli_bind_param -- Alias for mysqli_stmt_bind_param()
mysqli_bind_result -- Alias for mysqli_stmt_bind_result()
mysqli_change_user -- Changes the user of the specified database connection
mysqli_character_set_name -- Returns the default character set for the database connection
mysqli_client_encoding -- Alias of mysqli_character_set_name()
mysqli_close -- Closes a previously opened database connection
mysqli_commit -- Commits the current transaction
mysqli_connect_errno -- Returns the error code from last connect call
mysqli_connect_error -- Returns a string description of the last connect error
mysqli_connect -- Open a new connection to the MySQL server
mysqli_data_seek -- Adjusts the result pointer to an arbitary row in the result
mysqli_debug -- Performs debugging operations
mysqli_disable_reads_from_master -- Disable reads from master
mysqli_disable_rpl_parse -- Disable RPL parse
mysqli_dump_debug_info -- Dump debugging information into the log
mysqli_embedded_server_end --
mysqli_embedded_server_start --
mysqli_enable_reads_from_master -- Enable reads from master
mysqli_enable_rpl_parse -- Enable RPL parse
mysqli_errno -- Returns the error code for the most recent function call
mysqli_error -- Returns a string description of the last error
mysqli_escape_string -- Alias of mysqli_real_escape_string()
mysqli_execute -- Alias for mysqli_stmt_execute()
mysqli_fetch_array -- Fetch a result row as an associative, a numeric array, or both
mysqli_fetch_assoc -- Fetch a result row as an associative array
mysqli_fetch_field_direct -- Fetch meta-data for a single field
mysqli_fetch_field -- Returns the next field in the result set
mysqli_fetch_fields -- Returns an array of objects representing the fields in a result set
mysqli_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object -- Returns the current row of a result set as an object
mysqli_fetch_row -- Get a result row as an enumerated array
mysqli_fetch -- Alias for mysqli_stmt_fetch()
mysqli_field_count -- Returns the number of columns for the most recent query
mysqli_field_seek -- Set result pointer to a specified field offset
mysqli_field_tell -- Get current field offset of a result pointer
mysqli_free_result -- Frees the memory associated with a result
mysqli_get_charset -- Returns a character set object
mysqli_get_client_info -- Returns the MySQL client version as a string
mysqli_get_client_version -- Get MySQL client info
mysqli_get_host_info -- Returns a string representing the type of connection used
mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()
mysqli_get_proto_info -- Returns the version of the MySQL protocol used
mysqli_get_server_info -- Returns the version of the MySQL server
mysqli_get_server_version -- Returns the version of the MySQL server as an integer
mysqli_get_warnings --
mysqli_info -- Retrieves information about the most recently executed query
mysqli_init -- Initializes MySQLi and returns a resource for use with mysqli_real_connect()
mysqli_insert_id -- Returns the auto generated id used in the last query
mysqli_kill -- Asks the server to kill a MySQL thread
mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup
mysqli_more_results -- Check if there are any more query results from a multi query
mysqli_multi_query -- Performs a query on the database
mysqli_next_result -- Prepare next result from multi_query
mysqli_num_fields -- Get the number of fields in a result
mysqli_num_rows -- Gets the number of rows in a result
mysqli_options -- Set options
mysqli_param_count -- Alias for mysqli_stmt_param_count()
mysqli_ping -- Pings a server connection, or tries to reconnect if the connection has gone down
mysqli_prepare -- Prepare a SQL statement for execution
mysqli_query -- Performs a query on the database
mysqli_real_connect -- Opens a connection to a mysql server
mysqli_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
mysqli_real_query -- Execute an SQL query
mysqli_report -- Enables or disables internal report functions
mysqli_rollback -- Rolls back current transaction
mysqli_rpl_parse_enabled -- Check if RPL parse is enabled
mysqli_rpl_probe -- RPL probe
mysqli_rpl_query_type -- Returns RPL query type
mysqli_select_db -- Selects the default database for database queries
mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()
mysqli_send_query -- Send the query and return
mysqli_server_end -- Shut down the embedded server
mysqli_server_init -- Initialize embedded server
mysqli_set_charset -- Sets the default client character set
mysqli_set_local_infile_default -- Unsets user defined handler for load local infile command
mysqli_set_local_infile_handler -- Set callback functions for LOAD DATA LOCAL INFILE command
mysqli_set_opt -- Alias of mysqli_options()
mysqli_slave_query -- Force execution of a query on a slave in a master/slave setup
mysqli_sqlstate -- Returns the SQLSTATE error from previous MySQL operation
mysqli_ssl_set -- Used for establishing secure connections using SSL
mysqli_stat -- Gets the current system status
mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
mysqli_stmt_attr_get --
mysqli_stmt_attr_set --
mysqli_stmt_bind_param -- Binds variables to a prepared statement as parameters
mysqli_stmt_bind_result -- Binds variables to a prepared statement for result storage
mysqli_stmt_close -- Closes a prepared statement
mysqli_stmt_data_seek -- Seeks to an arbitray row in statement result set
mysqli_stmt_errno -- Returns the error code for the most recent statement call
mysqli_stmt_error -- Returns a string description for last statement error
mysqli_stmt_execute -- Executes a prepared Query
mysqli_stmt_fetch -- Fetch results from a prepared statement into the bound variables
mysqli_stmt_field_count -- Returns the number of field in the given statement
mysqli_stmt_free_result -- Frees stored result memory for the given statement handle
mysqli_stmt_get_warnings --
mysqli_stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli_stmt_insert_id -- Get the ID generated from the previous INSERT operation
mysqli_stmt_num_rows -- Return the number of rows in statements result set
mysqli_stmt_param_count -- Returns the number of parameter for the given statement
mysqli_stmt_prepare -- Prepare a SQL statement for execution
mysqli_stmt_reset -- Resets a prepared statement
mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement
mysqli_stmt_send_long_data -- Send data in blocks
mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
mysqli_stmt_store_result -- Transfers a result set from a prepared statement
mysqli_store_result -- Transfers a result set from the last query
mysqli_thread_id -- Returns the thread ID for the current connection
mysqli_thread_safe -- Returns whether thread safety is given or not
mysqli_use_result -- Initiate a result set retrieval
mysqli_warning_count -- Returns the number of warnings from the last query for the given link

Prev | Home | Next
PDO_MYSQL DSN | Up | mysqli_affected_rows


mysqli_affected_rows

(PHP 5)

mysqli_affected_rows

(no version information, might be only in CVS)

mysqli->affected_rows -- Gets the number of affected rows in a previous MySQL operation

Description

Procedural style:

int mysqli_affected_rows ( mysqli link )

Object oriented style (property):

class mysqli {

int affected_rows

}

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

This function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the mysqli_num_rows() function instead.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Note: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli-&#62;query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli-&#62;affected_rows);

$mysqli-&#62;query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli-&#62;query("UPDATE Language SET Status=1 WHERE Percentage &#62; 50");
printf("Affected rows (UPDATE): %d\n", $mysqli-&#62;affected_rows);

/* delete rows */
$mysqli-&#62;query("DELETE FROM Language WHERE Percentage &#60; 50");
printf("Affected rows (DELETE): %d\n", $mysqli-&#62;affected_rows);

/* select all rows */
$result = $mysqli-&#62;query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli-&#62;affected_rows);

$result-&#62;close();

/* Delete table Language */
$mysqli-&#62;query("DROP TABLE Language");

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage &#62; 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage &#60; 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

See Also

mysqli_num_rows()
mysqli_info()

Prev | Home | Next
MySQL Improved Extension | Up | mysqli_autocommit


mysqli_autocommit

(PHP 5)

mysqli_autocommit

(no version information, might be only in CVS)

mysqli->autocommit() -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool mysqli_autocommit ( mysqli link, bool mode )

Object oriented style (method)

class mysqli {

bool autocommit ( bool mode )

}

Turns on or off auto-commit mode on queries for the database connection.

To determine the current state of autocommit use the SQL command SELECT @@autocommit.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

mode

Whether to turn on auto-commit or not.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function doesn't work with non transactional table types (like MyISAM or ISAM).

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli-&#62;autocommit(TRUE);

if ($result = $mysqli-&#62;query("SELECT @@autocommit")) {
    $row = $result-&#62;fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result-&#62;free();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Autocommit is 1

See Also

mysqli_commit()
mysqli_rollback()

Prev | Home | Next
mysqli_affected_rows | Up | mysqli_bind_param


mysqli_bind_param

(PHP 5)

mysqli_bind_param -- Alias for mysqli_stmt_bind_param()

Description

This function is an alias of mysqli_stmt_bind_param().

Notes

Note: mysqli_bind_param() is deprecated and will be removed.

See Also

mysqli_stmt_bind_param()

Prev | Home | Next
mysqli_autocommit | Up | mysqli_bind_result


mysqli_bind_result

(PHP 5)

mysqli_bind_result -- Alias for mysqli_stmt_bind_result()

Description

This function is an alias of mysqli_stmt_bind_result().

Notes

Note: mysqli_bind_result() is deprecated and will be removed.

See Also

mysqli_stmt_bind_result()

Prev | Home | Next
mysqli_bind_param | Up | mysqli_change_user


mysqli_change_user

(PHP 5)

mysqli_change_user

(no version information, might be only in CVS)

mysqli->change_user() -- Changes the user of the specified database connection

Description

Procedural style:

bool mysqli_change_user ( mysqli link, string user, string password, string database )

Object oriented style (method):

class mysqli {

bool change_user ( string user, string password, string database )

}

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

user

The MySQL user name.

password

The MySQL password.

database

The database to change to.

If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Examples

Example 1. Object oriented style

&#60;?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli-&#62;query("SET @a:=1");

/* reset all and select a new database */
$mysqli-&#62;change_user("my_user", "my_password", "world");

if ($result = $mysqli-&#62;query("SELECT DATABASE()")) {
    $row = $result-&#62;fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result-&#62;close();
}

if ($result = $mysqli-&#62;query("SELECT @a")) {
    $row = $result-&#62;fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Default database: world
Value of variable a is NULL

See Also

mysqli_connect()
mysqli_select_db()

Prev | Home | Next
mysqli_bind_result | Up | mysqli_character_set_name


mysqli_character_set_name

(PHP 5)

mysqli_character_set_name

(no version information, might be only in CVS)

mysqli->character_set_name() -- Returns the default character set for the database connection

Description

Procedural style:

string mysqli_character_set_name ( mysqli link )

Object oriented style (method):

class mysqli {

string character_set_name ( void )

}

Returns the current character set for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The default character set for the current connection

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = $mysqli-&#62;character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Current character set is latin1_swedish_ci

See Also

mysqli_client_encoding()
mysqli_real_escape_string()

Prev | Home | Next
mysqli_change_user | Up | mysqli_client_encoding


mysqli_client_encoding

(PHP 5)

mysqli_client_encoding -- Alias of mysqli_character_set_name()

Description

This function is an alias of mysqli_character_set_name().

See Also

mysqli_real_escape_string()

Prev | Home | Next
mysqli_character_set_name | Up | mysqli_close


mysqli_close

(PHP 5)

mysqli_close

(no version information, might be only in CVS)

mysqli->close() -- Closes a previously opened database connection

Description

Procedural style:

bool mysqli_close ( mysqli link )

Object oriented style (method):

class mysqli {

bool close ( void )

}

Closes a previously opened database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_connect()
mysqli_init()
mysqli_real_connect()

Prev | Home | Next
mysqli_client_encoding | Up | mysqli_commit


mysqli_commit

(PHP 5)

mysqli_commit

(no version information, might be only in CVS)

mysqli->commit() -- Commits the current transaction

Description

Procedural style:

bool mysqli_commit ( mysqli link )

Object oriented style (method)

class mysqli {

bool commit ( void )

}

Commits the current transaction for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* set autocommit to off */
$mysqli-&#62;autocommit(FALSE);

/* Insert some values */
$mysqli-&#62;query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli-&#62;query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
$mysqli-&#62;commit();

/* drop table */
$mysqli-&#62;query("DROP TABLE Language");

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?&#62;

See Also

mysqli_autocommit()
mysqli_rollback()

Prev | Home | Next
mysqli_close | Up | mysqli_connect_errno


mysqli_connect_errno

(PHP 5)

mysqli_connect_errno -- Returns the error code from last connect call

Description

int mysqli_connect_errno ( void )

Returns the last error code number from the last call to mysqli_connect().

Note: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Return Values

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Examples

Example 1. mysqli_connect_errno() example

&#60;?php

$link = @mysqli_connect("localhost", "nonexisting_user", "");

if (!$link) {
    printf("Can't connect to localhost. Errorcode: %d\n", mysqli_connect_errno());
}
?&#62;

See Also

mysqli_connect()
mysqli_connect_error()
mysqli_errno()
mysqli_error()
mysqli_sqlstate()

Prev | Home | Next
mysqli_commit | Up | mysqli_connect_error


mysqli_connect_error

(PHP 5)

mysqli_connect_error -- Returns a string description of the last connect error

Description

string mysqli_connect_error ( void )

Returns the last error message string from the last call to mysqli_connect().

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example 1. mysqli_connect_error() example

&#60;?php

$link = @mysqli_connect("localhost", "nonexisting_user", "");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
}
?&#62;

See Also

mysqli_connect()
mysqli_connect_errno()
mysqli_errno()
mysqli_error()
mysqli_sqlstate()

Prev | Home | Next
mysqli_connect_errno | Up | mysqli_connect


mysqli_connect

(PHP 5)

mysqli_connect

(no version information, might be only in CVS)

mysqli->__construct() -- Open a new connection to the MySQL server

Description

Procedural style

mysqli mysqli_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

Object oriented style (constructor):

class mysqli {

__construct ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

Opens a connection to the MySQL Server running on.

Parameters

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

Return Values

Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Host information: %s\n", $mysqli-&#62;host_info);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Host information: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Host information: Localhost via UNIX socket

Prev | Home | Next
mysqli_connect_error | Up | mysqli_data_seek


mysqli_data_seek

(PHP 5)

mysqli_data_seek

(no version information, might be only in CVS)

result->data_seek() -- Adjusts the result pointer to an arbitary row in the result

Description

Procedural style:

bool mysqli_data_seek ( mysqli_result result, int offset )

Object oriented style (method):

class mysqli_result {

bool data_seek ( int offset )

}

The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

offset

The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli-&#62;query( $query)) {

    /* seek to row no. 400 */
    $result-&#62;data_seek(399);

    /* fetch row */
    $row = $result-&#62;fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

City: Benin City  Countrycode: NGA

See Also

mysqli_store_result()
mysqli_fetch_row()
mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_object()
mysqli_query()
mysqli_num_rows()

Prev | Home | Next
mysqli_connect | Up | mysqli_debug


mysqli_debug

(PHP 5)

mysqli_debug

(no version information, might be only in CVS)

mysqli->debug() -- Performs debugging operations

Description

Procedural style:

bool mysqli_debug ( string message )

Object oriented style (method):

class mysqli {

bool debug ( string message )

}

Performs debugging operations using the Fred Fish debugging library.

Parameters

message

A string representing the debugging operation to perform

Return Values

Returns TRUE.

Notes

Note: To use the mysqli_debug() function you must complile the MySQL client library to support debugging.

Examples

Example 1. Generating a Trace File

&#60;?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:0,/tmp/client.trace");

?&#62;

See Also

mysqli_dump_debug_info()
mysqli_report()

Prev | Home | Next
mysqli_data_seek | Up | mysqli_disable_reads_from_master


mysqli_disable_reads_from_master

(PHP 5)

mysqli_disable_reads_from_master

(no version information, might be only in CVS)

mysqli->disable_reads_from_master() -- Disable reads from master

Description

Procedural style:

bool mysqli_disable_reads_from_master ( mysqli link )

Object oriented style (method):

class mysqli {

void disable_reads_from_master ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_debug | Up | mysqli_disable_rpl_parse


mysqli_disable_rpl_parse

(PHP 5)

mysqli_disable_rpl_parse -- Disable RPL parse

Description

bool mysqli_disable_rpl_parse ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_disable_reads_from_master | Up | mysqli_dump_debug_info


mysqli_dump_debug_info

(PHP 5)

mysqli_dump_debug_info

(no version information, might be only in CVS)

mysqli->dump_debug_info() -- Dump debugging information into the log

Description

Procedural style:

bool mysqli_dump_debug_info ( mysqli link )

Object oriented style (method):

class mysqli {

bool dump_debug_info ( void )

}

This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_debug()

Prev | Home | Next
mysqli_disable_rpl_parse | Up | mysqli_embedded_server_end


mysqli_enable_reads_from_master

(PHP 5)

mysqli_enable_reads_from_master -- Enable reads from master

Description

bool mysqli_enable_reads_from_master ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_embedded_server_start | Up | mysqli_enable_rpl_parse


mysqli_enable_rpl_parse

(PHP 5)

mysqli_enable_rpl_parse -- Enable RPL parse

Description

bool mysqli_enable_rpl_parse ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_enable_reads_from_master | Up | mysqli_errno


mysqli_errno

(PHP 5)

mysqli_errno

(no version information, might be only in CVS)

mysqli->errno -- Returns the error code for the most recent function call

Description

Procedural style:

int mysqli_errno ( mysqli link )

Object oriented style (property):

class mysqli {

int errno

}

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli-&#62;query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli-&#62;errno);
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errorcode: %d\n", mysqli_errno($link));
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Errorcode: 1193

See Also

mysqli_connect_errno()
mysqli_connect_error()
mysqli_error()
mysqli_sqlstate()

Prev | Home | Next
mysqli_enable_rpl_parse | Up | mysqli_error


mysqli_error

(PHP 5)

mysqli_error -- Returns a string description of the last error

Description

Procedural style:

string mysqli_error ( mysqli link )

Object oriented style (property)

class mysqli {

string error

}

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli-&#62;query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli-&#62;error);
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Errormessage: Unknown system variable 'a'

See Also

mysqli_connect_errno()
mysqli_connect_error()
mysqli_errno()
mysqli_sqlstate()

Prev | Home | Next
mysqli_errno | Up | mysqli_escape_string


mysqli_escape_string

(PHP 5)

mysqli_escape_string -- Alias of mysqli_real_escape_string()

Description

This function is an alias of mysqli_real_escape_string().

See Also

mysqli_real_escape_string()

Prev | Home | Next
mysqli_error | Up | mysqli_execute


mysqli_execute

(PHP 5)

mysqli_execute -- Alias for mysqli_stmt_execute()

Description

This function is an alias of mysqli_stmt_execute().

Notes

Note: mysqli_execute() is deprecated and will be removed.

See Also

mysqli_stmt_execute()

Prev | Home | Next
mysqli_escape_string | Up | mysqli_fetch_array


mysqli_fetch_array

(PHP 5)

mysqli_fetch_array

(no version information, might be only in CVS)

result->fetch_array() -- Fetch a result row as an associative, a numeric array, or both

Description

Procedural style:

mixed mysqli_fetch_array ( mysqli_result result [, int resulttype] )

Object oriented style (method):

class mysqli_result {

mixed fetch_array ( [int resulttype] )

}

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH. Defaults to MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

Return Values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli-&#62;query($query);

/* numeric array */
$row = $result-&#62;fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result-&#62;fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result-&#62;fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
$result-&#62;close();

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

See Also

mysqli_fetch_assoc()
mysqli_fetch_row()
mysqli_fetch_object()
mysqli_query()
mysqli_data_seek()

Prev | Home | Next
mysqli_execute | Up | mysqli_fetch_assoc


mysqli_fetch_assoc

(PHP 5)

mysqli_fetch_assoc

(no version information, might be only in CVS)

mysqli->fetch_assoc() -- Fetch a result row as an associative array

Description

Procedural style:

array mysqli_fetch_assoc ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

array fetch_assoc ( void )

}

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an associative array representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

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 mysqli_fetch_row() or add alias names.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli-&#62;query($query)) {

    /* fetch associative array */
    while ($row = $result-&#62;fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

mysqli_fetch_array()
mysqli_fetch_row()
mysqli_fetch_object()
mysqli_query()
mysqli_data_seek()

Prev | Home | Next
mysqli_fetch_array | Up | mysqli_fetch_field_direct


mysqli_fetch_field_direct

(PHP 5)

mysqli_fetch_field_direct

(no version information, might be only in CVS)

result->fetch_field_direct() -- Fetch meta-data for a single field

Description

Procedural style:

object mysqli_fetch_field_direct ( mysqli_result result, int fieldnr )

Object oriented style (method):

class mysqli_result {

object fetch_field_direct ( int fieldnr )

}

Returns an object which contains field definition informations from specified resultset.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Return Values

Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.

Table 1. Object attributes

Attribute | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the tabl definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli-&#62;query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result-&#62;fetch_field_direct(1);

    printf("Name:     %s\n", $finfo-&#62;name);
    printf("Table:    %s\n", $finfo-&#62;table);
    printf("max. Len: %d\n", $finfo-&#62;max_length);
    printf("Flags:    %d\n", $finfo-&#62;flags);
    printf("Type:     %d\n", $finfo-&#62;type);

    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);

    printf("Name:     %s\n", $finfo-&#62;name);
    printf("Table:    %s\n", $finfo-&#62;table);
    printf("max. Len: %d\n", $finfo-&#62;max_length);
    printf("Flags:    %d\n", $finfo-&#62;flags);
    printf("Type:     %d\n", $finfo-&#62;type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

mysqli_num_fields()
mysqli_fetch_field()
mysqli_fetch_fields()

Prev | Home | Next
mysqli_fetch_assoc | Up | mysqli_fetch_field


mysqli_fetch_field

(PHP 5)

mysqli_fetch_field

(no version information, might be only in CVS)

result->fetch_field() -- Returns the next field in the result set

Description

Procedural style:

object mysqli_fetch_field ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

object fetch_field ( void )

}

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an object which contains field definition information or FALSE if no field information is available.

Table 1. Object properties

Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli-&#62;query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result-&#62;fetch_field()) {

        printf("Name:     %s\n", $finfo-&#62;name);
        printf("Table:    %s\n", $finfo-&#62;table);
        printf("max. Len: %d\n", $finfo-&#62;max_length);
        printf("Flags:    %d\n", $finfo-&#62;flags);
        printf("Type:     %d\n\n", $finfo-&#62;type);
    }
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        printf("Name:     %s\n", $finfo-&#62;name);
        printf("Table:    %s\n", $finfo-&#62;table);
        printf("max. Len: %d\n", $finfo-&#62;max_length);
        printf("Flags:    %d\n", $finfo-&#62;flags);
        printf("Type:     %d\n\n", $finfo-&#62;type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

mysqli_num_fields()
mysqli_fetch_field_direct()
mysqli_fetch_fields()
mysqli_field_seek()

Prev | Home | Next
mysqli_fetch_field_direct | Up | mysqli_fetch_fields


mysqli_fetch_fields

(PHP 5)

mysqli_fetch_fields

(no version information, might be only in CVS)

result->fetch_fields() -- Returns an array of objects representing the fields in a result set

Description

Procedural Style:

array mysqli_fetch_fields ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

array fetch_fields ( void )

}

This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an array of objects which contains field definition information or FALSE if no field information is available.

Table 1. Object properties

Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli-&#62;query($query)) {

    /* Get field information for all columns */
    $finfo = $result-&#62;fetch_fields();

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val-&#62;name);
        printf("Table:    %s\n", $val-&#62;table);
        printf("max. Len: %d\n", $val-&#62;max_length);
        printf("Flags:    %d\n", $val-&#62;flags);
        printf("Type:     %d\n\n", $val-&#62;type);
    }
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all columns */
    $finfo = mysqli_fetch_fields($result);

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val-&#62;name);
        printf("Table:    %s\n", $val-&#62;table);
        printf("max. Len: %d\n", $val-&#62;max_length);
        printf("Flags:    %d\n", $val-&#62;flags);
        printf("Type:     %d\n\n", $val-&#62;type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

mysqli_num_fields()
mysqli_fetch_field_direct()
mysqli_fetch_field()

Prev | Home | Next
mysqli_fetch_field | Up | mysqli_fetch_lengths


mysqli_fetch_lengths

(PHP 5)

mysqli_fetch_lengths

(no version information, might be only in CVS)

result->lengths() -- Returns the lengths of the columns of the current row in the result set

Description

Procedural style:

array mysqli_fetch_lengths ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

array lengths

}

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli-&#62;query($query)) {

    $row = $result-&#62;fetch_row();

    /* display column lengths */
    foreach ($result-&#62;lengths as $i =&#62; $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i =&#62; $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Field  1 has Length  3
Field  2 has Length  5
Field  3 has Length 13
Field  4 has Length  9
Field  5 has Length  6
Field  6 has Length  1
Field  7 has Length  6
Field  8 has Length  4
Field  9 has Length  6
Field 10 has Length  6
Field 11 has Length  5
Field 12 has Length 44
Field 13 has Length  7
Field 14 has Length  3
Field 15 has Length  2

Prev | Home | Next
mysqli_fetch_fields | Up | mysqli_fetch_object


mysqli_fetch_object

(PHP 5)

mysqli_fetch_object

(no version information, might be only in CVS)

result->fetch_object() -- Returns the current row of a result set as an object

Description

Procedural style:

object mysqli_fetch_object ( mysqli_result result [, string class_name [, array params]] )

Object oriented style (method):

class mysqli_result {

object fetch_object ( [string class_name [, array params]] )

}

The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

class_name

params

Return Values

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to PHP NULL value.

ChangeLog

Version | Description
5.0.0 | Added the ability to return as a different object.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli-&#62;query($query)) {

    /* fetch object array */
    while ($obj = $result-&#62;fetch_object()) {
        printf ("%s (%s)\n", $obj-&#62;Name, $obj-&#62;CountryCode);
    }

    /* free result set */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj-&#62;Name, $obj-&#62;CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_row()
mysqli_query()
mysqli_data_seek()

Prev | Home | Next
mysqli_fetch_lengths | Up | mysqli_fetch_row


mysqli_fetch_row

(PHP 5)

mysqli_fetch_row

(no version information, might be only in CVS)

result->fetch_row() -- Get a result row as an enumerated array

Description

Procedural style:

mixed mysqli_fetch_row ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

mixed fetch_row ( void )

}

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

mysqli_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to PHP NULL value.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli-&#62;query($query)) {

    /* fetch object array */
    while ($row = $result-&#62;fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_object()
mysqli_query()
mysqli_data_seek()

Prev | Home | Next
mysqli_fetch_object | Up | mysqli_fetch


mysqli_fetch

(PHP 5)

mysqli_fetch -- Alias for mysqli_stmt_fetch()

Description

This function is an alias of mysqli_stmt_fetch().

Notes

Note: mysqli_fetch() is deprecated and will be removed.

See Also

mysqli_stmt_fetch()

Prev | Home | Next
mysqli_fetch_row | Up | mysqli_field_count


mysqli_field_count

(PHP 5)

mysqli_field_count

(no version information, might be only in CVS)

mysqli->field_count() -- Returns the number of columns for the most recent query

Description

Procedural style:

int mysqli_field_count ( mysqli link )

Object oriented style (method):

class mysqli_result {

int field_count ( void )

}

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer representing the number of fields in a result set.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli-&#62;query( "DROP TABLE IF EXISTS friends");
$mysqli-&#62;query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli-&#62;query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli-&#62;real_query($HTTP_POST_VARS['query']);

if ($mysqli-&#62;field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli-&#62;store_result();

    /* process resultset */
    $row = $result-&#62;fetch_row();

    /* free resultset */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, $HTTP_POST_VARS['query']);

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

Prev | Home | Next
mysqli_fetch | Up | mysqli_field_seek


mysqli_field_seek

(PHP 5)

mysqli_field_seek

(no version information, might be only in CVS)

result->field_seek() -- Set result pointer to a specified field offset

Description

Procedural style:

bool mysqli_field_seek ( mysqli_result result, int fieldnr )

Object oriented style (method):

class mysqli_result {

bool field_seek ( int fieldnr )

}

Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.

Note: To seek to the beginning of a row, pass an offset value of zero.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Return Values

Returns the previous value of field cursor.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli-&#62;query($query)) {

    /* Get field information for 2nd column */
    $result-&#62;field_seek(1);
    $finfo = $result-&#62;fetch_field();

    printf("Name:     %s\n", $finfo-&#62;name);
    printf("Table:    %s\n", $finfo-&#62;table);
    printf("max. Len: %d\n", $finfo-&#62;max_length);
    printf("Flags:    %d\n", $finfo-&#62;flags);
    printf("Type:     %d\n\n", $finfo-&#62;type);

    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);

    printf("Name:     %s\n", $finfo-&#62;name);
    printf("Table:    %s\n", $finfo-&#62;table);
    printf("max. Len: %d\n", $finfo-&#62;max_length);
    printf("Flags:    %d\n", $finfo-&#62;flags);
    printf("Type:     %d\n\n", $finfo-&#62;type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

mysqli_fetch_field()

Prev | Home | Next
mysqli_field_count | Up | mysqli_field_tell


mysqli_field_tell

(PHP 5)

mysqli_field_tell

(no version information, might be only in CVS)

result->current_field -- Get current field offset of a result pointer

Description

Procedural style:

int mysqli_field_tell ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

int current_field

}

Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns current offset of field cursor.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli-&#62;query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result-&#62;fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result-&#62;current_field;

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo-&#62;name);
        printf("Table:    %s\n", $finfo-&#62;table);
        printf("max. Len: %d\n", $finfo-&#62;max_length);
        printf("Flags:    %d\n", $finfo-&#62;flags);
        printf("Type:     %d\n\n", $finfo-&#62;type);
    }
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo-&#62;name);
        printf("Table:    %s\n", $finfo-&#62;table);
        printf("max. Len: %d\n", $finfo-&#62;max_length);
        printf("Flags:    %d\n", $finfo-&#62;flags);
        printf("Type:     %d\n\n", $finfo-&#62;type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Column 1:
Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Column 2:
Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

mysqli_fetch_field()
mysqli_field_seek()

Prev | Home | Next
mysqli_field_seek | Up | mysqli_free_result


mysqli_free_result

(PHP 5)

mysqli_free_result

(no version information, might be only in CVS)

result->free() -- Frees the memory associated with a result

Description

Procedural style:

void mysqli_free_result ( mysqli_result result )

Object oriented style (all methods are equivalent):

class mysqli_result {

void free ( void )

void close ( void )

void free_result ( void )

}

Frees the memory associated with the result.

Note: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

No value is returned.

See Also

mysqli_query()
mysqli_stmt_store_result()
mysqli_store_result()
mysqli_use_result()

Prev | Home | Next
mysqli_field_tell | Up | mysqli_get_charset


mysqli_get_client_info

(PHP 5)

mysqli_get_client_info -- Returns the MySQL client version as a string

Description

string mysqli_get_client_info ( void )

The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.

Return Values

A string that represents the MySQL client library version

Examples

Example 1. mysqli_get_client_info

&#60;?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?&#62;

See Also

mysqli_get_client_version()
mysqli_get_server_info()
mysqli_get_server_version()

Prev | Home | Next
mysqli_get_charset | Up | mysqli_get_client_version


mysqli_get_client_version

(PHP 5)

mysqli_get_client_version -- Get MySQL client info

Description

int mysqli_get_client_version ( void )

Returns client version number as an integer.

Return Values

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exits.

Examples

Example 1. mysqli_get_client_version

&#60;?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?&#62;

See Also

mysqli_get_client_info()
mysqli_get_server_info()
mysqli_get_server_version()

Prev | Home | Next
mysqli_get_client_info | Up | mysqli_get_host_info


mysqli_get_host_info

(PHP 5)

mysqli_get_host_info

(no version information, might be only in CVS)

mysqli->host_info -- Returns a string representing the type of connection used

Description

Procdural style:

string mysqli_get_host_info ( mysqli link )

Object oriented style (property):

class mysqli {

string host_info

}

The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing the server hostname and the connection type.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli-&#62;host_info);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Host info: Localhost via UNIX socket

See Also

mysqli_get_proto_info()

Prev | Home | Next
mysqli_get_client_version | Up | mysqli_get_metadata


mysqli_get_metadata

(PHP 5)

mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()

Description

This function is an alias of mysqli_stmt_result_metadata().

Notes

Note: mysqli_get_metadata() is deprecated and will be removed.

See Also

mysqli_stmt_result_metadata()

Prev | Home | Next
mysqli_get_host_info | Up | mysqli_get_proto_info


mysqli_get_proto_info

(PHP 5)

mysqli_get_proto_info

(no version information, might be only in CVS)

mysqli->protocol_version -- Returns the version of the MySQL protocol used

Description

Procedural style:

int mysqli_get_proto_info ( mysqli link )

Object oriented style (property):

class mysqli {

string protocol_version

}

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an integer representing the protocol version.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli-&#62;protocol_version);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Protocol version: 10

See Also

mysqli_get_host_info()

Prev | Home | Next
mysqli_get_metadata | Up | mysqli_get_server_info


mysqli_get_server_info

(PHP 5)

mysqli_get_server_info

(no version information, might be only in CVS)

mysqli->server_info -- Returns the version of the MySQL server

Description

Procedural style:

string mysqli_get_server_info ( mysqli link )

Object oriented style (property):

class mysqli {

string server_info

}

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing the server version.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli-&#62;server_info);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Server version: 4.1.2-alpha-debug

See Also

mysqli_get_client_info()
mysqli_get_client_version()
mysqli_get_server_version()

Prev | Home | Next
mysqli_get_proto_info | Up | mysqli_get_server_version


mysqli_get_server_version

(PHP 5)

mysqli_get_server_version

(no version information, might be only in CVS)

mysqli->server_version -- Returns the version of the MySQL server as an integer

Description

Procedural style:

int mysqli_get_server_version ( mysqli link )

Object oriented style (property):

class mysqli {

int server_version

}

The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer representing the server version.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli-&#62;server_version);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Server version: 40102

See Also

mysqli_get_client_info()
mysqli_get_client_version()
mysqli_get_server_info()

Prev | Home | Next
mysqli_get_server_info | Up | mysqli_get_warnings


mysqli_info

(PHP 5)

mysqli_info

(no version information, might be only in CVS)

mysqli->info -- Retrieves information about the most recently executed query

Description

Procedural style:

string mysqli_info ( mysqli link )

Object oriented style (property)

class mysqli {

string info

}

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Table 1. Possible mysqli_info return values

Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Note: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing additional information about the most recently executed query.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli-&#62;query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli-&#62;info);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Records: 150  Duplicates: 0  Warnings: 0

See Also

mysqli_affected_rows()
mysqli_warning_count()
mysqli_num_rows()

Prev | Home | Next
mysqli_get_warnings | Up | mysqli_init


mysqli_init

(PHP 5)

mysqli_init -- Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

Procedural style:

mysqli mysqli_init ( void )

Object oriented style (method):

class mysqli {

mysqli init ( void )

}

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

Note: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Return Values

Returns an object.

See Also

mysqli_options()
mysqli_close()
mysqli_real_connect()
mysqli_connect()

Prev | Home | Next
mysqli_info | Up | mysqli_insert_id


mysqli_insert_id

(PHP 5)

mysqli_insert_id

(no version information, might be only in CVS)

mysqli->insert_id -- Returns the auto generated id used in the last query

Description

Procedural style:

int mysqli_insert_id ( mysqli link )

Object oriented style (property):

class mysqli {

int insert_id

}

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Note: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.

Note: If the number is greater than maximal int value, mysqli_insert_id() will return a string.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli-&#62;query($query);

printf ("New Record has id %d.\n", $mysqli-&#62;insert_id);

/* drop table */
$mysqli-&#62;query("DROP TABLE myCity");

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* drop table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

New Record has id 1.

Prev | Home | Next
mysqli_init | Up | mysqli_kill


mysqli_kill

(PHP 5)

mysqli_kill

(no version information, might be only in CVS)

mysqli->kill() -- Asks the server to kill a MySQL thread

Description

Procedural style:

bool mysqli_kill ( mysqli link, int processid )

Object oriented style (method)

class mysqli {

bool kill ( int processid )

}

This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.

To stop a running query you should use the SQL command KILL QUERY processid.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli-&#62;thread_id;

/* Kill connection */
$mysqli-&#62;kill($thread_id);

/* This should produce an error */
if (!$mysqli-&#62;query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli-&#62;error);
    exit;
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Error: MySQL server has gone away

See Also

mysqli_thread_id()

Prev | Home | Next
mysqli_insert_id | Up | mysqli_master_query


mysqli_master_query

(PHP 5)

mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup

Description

bool mysqli_master_query ( mysqli link, string query )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_kill | Up | mysqli_more_results


mysqli_more_results

(PHP 5)

mysqli_more_results

(no version information, might be only in CVS)

mysqli->more_results -- Check if there are any more query results from a multi query

Description

bool mysqli_more_results ( mysqli link )

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_multi_query().

See Also

mysqli_multi_query()
mysqli_next_result()
mysqli_store_result()
mysqli_use_result()

Prev | Home | Next
mysqli_master_query | Up | mysqli_multi_query


mysqli_multi_query

(PHP 5)

mysqli_multi_query

(no version information, might be only in CVS)

mysqli->multi_query() -- Performs a query on the database

Description

Procedural style:

bool mysqli_multi_query ( mysqli link, string query )

Object oriented style (method):

class mysqli {

bool multi_query ( string query )

}

Executes one or multiple queries which are concatenated by a semicolon.

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Return Values

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli-&#62;multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli-&#62;store_result()) {
            while ($row = $result-&#62;fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result-&#62;close();
        }
        /* print divider */
        if ($mysqli-&#62;more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli-&#62;next_result());
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

mysqli_use_result()
mysqli_store_result()
mysqli_next_result()
mysqli_more_results()

Prev | Home | Next
mysqli_more_results | Up | mysqli_next_result


mysqli_next_result

(PHP 5)

mysqli_next_result

(no version information, might be only in CVS)

mysqli->next_result() -- Prepare next result from multi_query

Description

bool mysqli_next_result ( mysqli link )

Prepares next result set from a previous call to
mysqli_multi_query() which can be retrieved by
mysqli_store_result() or
mysqli_use_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_multi_query().

See Also

mysqli_multi_query()
mysqli_more_results()
mysqli_store_result()
mysqli_use_result()

Prev | Home | Next
mysqli_multi_query | Up | mysqli_num_fields


mysqli_num_fields

(PHP 5)

mysqli_num_fields

(no version information, might be only in CVS)

result->field_count -- Get the number of fields in a result

Description

Procedural style:

int mysqli_num_fields ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

int field_count

}

Returns the number of fields from specified result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

The number of fields from a result set.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli-&#62;query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result-&#62;field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Result set has 5 fields.

See Also

mysqli_fetch_field()

Prev | Home | Next
mysqli_next_result | Up | mysqli_num_rows


mysqli_num_rows

(PHP 5)

mysqli_num_rows

(no version information, might be only in CVS)

result->num_rows -- Gets the number of rows in a result

Description

Procedural style:

int mysqli_num_rows ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

int num_rows

}

Returns the number of rows in the result set.

The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns number of rows in the result set.

Note: If the number of rows is greater than maximal int value, the number will be returned as a string.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli-&#62;query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result-&#62;num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Result set has 239 rows.

See Also

mysqli_affected_rows()
mysqli_store_result()
mysqli_use_result()
mysqli_query()

Prev | Home | Next
mysqli_num_fields | Up | mysqli_options


mysqli_options

(PHP 5)

mysqli_options

(no version information, might be only in CVS)

mysqli->options() -- Set options

Description

Procedural style:

bool mysqli_options ( mysqli link, int option, mixed value )

Object oriented style (method)

class mysqli {

bool options ( int option, mixed value )

}

Used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

mysqli_options() should be called after
mysqli_init() and before
mysqli_real_connect().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

option

The option that you want to set. It can be one of the following values:

Table 1. Valid options

Name | Description
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND | command to execute after when connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.

value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_real_connect().

See Also

mysqli_init()
mysqli_real_connect()

Prev | Home | Next
mysqli_num_rows | Up | mysqli_param_count


mysqli_param_count

(PHP 5)

mysqli_param_count -- Alias for mysqli_stmt_param_count()

Description

This function is an alias of mysqli_stmt_param_count().

Notes

Note: mysqli_param_count() is deprecated and will be removed.

See Also

mysqli_stmt_param_count()

Prev | Home | Next
mysqli_options | Up | mysqli_ping


mysqli_ping

(PHP 5)

mysqli_ping

(no version information, might be only in CVS)

mysqli->ping() -- Pings a server connection, or tries to reconnect if the connection has gone down

Description

Procedural style:

bool mysqli_ping ( mysqli link )

Object oriented style (method):

class mysqli {

bool ping ( void )

}

Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if ($mysqli-&#62;ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli-&#62;error);
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Our connection is ok!

Prev | Home | Next
mysqli_param_count | Up | mysqli_prepare


mysqli_prepare

(PHP 5)

mysqli_prepare

(no version information, might be only in CVS)

mysqli->prepare() -- Prepare a SQL statement for execution

Description

Procedure style:

mysqli_stmt mysqli_prepare ( mysqli link, string query )

Object oriented style (method)

class mysqli {

mysqli_stmt prepare ( string query )

}

Prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Note: You should not add a terminating semicolon or \g to the statement.

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

Return Values

mysqli_prepare() returns a statement object or FALSE if an error occured.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli-&#62;prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt-&#62;bind_param("s", $city);

    /* execute query */
    $stmt-&#62;execute();

    /* bind result variables */
    $stmt-&#62;bind_result($district);

    /* fetch value */
    $stmt-&#62;fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Amersfoort is in district Utrecht

See Also

mysqli_stmt_execute()
mysqli_stmt_fetch()
mysqli_stmt_bind_param()
mysqli_stmt_bind_result()
mysqli_stmt_close()

Prev | Home | Next
mysqli_ping | Up | mysqli_query


mysqli_query

(PHP 5)

mysqli_query

(no version information, might be only in CVS)

mysqli->query() -- Performs a query on the database

Description

Procedural style:

mixed mysqli_query ( mysqli link, string query [, int resultmode] )

Object oriented style (method):

class mysqli {

mixed query ( string query [, int resultmode] )

}

Performs a query against the database.

Functionally, using this function is identical to calling
mysqli_real_query() followed either by
mysqli_use_result() or
mysqli_store_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query string.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli-&#62;query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli-&#62;query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result-&#62;num_rows);

    /* free result set */
    $result-&#62;close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli-&#62;query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli-&#62;query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli-&#62;error);
    }
    $result-&#62;close();
}

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?&#62;

The above example will output:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

See Also

mysqli_real_query()
mysqli_multi_query()
mysqli_free_result()

Prev | Home | Next
mysqli_prepare | Up | mysqli_real_connect


mysqli_real_connect

(PHP 5)

mysqli_real_connect

(no version information, might be only in CVS)

mysqli->real_connect() -- Opens a connection to a mysql server

Description

Procedural style

bool mysqli_real_connect ( mysqli link [, string host [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]] )

Object oriented style (method)

class mysqli {

bool real_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]] )

}

Establish a connection to a MySQL database engine.

This function differs from mysqli_connect():

  • mysqli_real_connect() needs a valid object which has to be created by function mysqli_init()

  • With function mysqli_options() you can set various options for connection.

  • There is a flags parameter.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

flags

With the parameter flags you can set different connection options:

Table 1. Supported flags

Name | Description
MYSQLI_CLIENT_COMPRESS | Use compression protocol
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words.
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection
MYSQLI_CLIENT_SSL | Use SSL (encryption)

Note: For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php

/* create a connection object which is not connected */
$mysqli = mysqli_init();

/* set connection options */
$mysqli-&#62;options(MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
$mysqli-&#62;options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);

/* connect to server */
$mysqli-&#62;real_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("Connection: %s\n.", $mysqli-&#62;host_info);

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php

/* create a connection object which is not connected */
$link = mysqli_init();

/* set connection options */
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);

/* connect to server */
mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("Connection: %s\n.", mysqli_get_host_info($link));

mysqli_close($link);
?&#62;

The above example will output:

Connection: Localhost via UNIX socket

See Also

mysqli_connect()
mysqli_init()
mysqli_options()
mysqli_ssl_set()
mysqli_close()

Prev | Home | Next
mysqli_query | Up | mysqli_real_escape_string


mysqli_real_escape_string

(PHP 5)

mysqli_real_escape_string

(no version information, might be only in CVS)

mysqli->real_escape_string() -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

Description

Procedural style:

string mysqli_real_escape_string ( mysqli link, string escapestr )

Object oriented style (both methods are equivalent):

class mysqli {

string escape_string ( string escapestr )

string real_escape_string ( string escapestr )

}

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return Values

Returns an escaped string.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli-&#62;query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli-&#62;sqlstate);
}

$city = $mysqli-&#62;real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli-&#62;query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli-&#62;affected_rows);
}

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?&#62;

The above example will output:

Error: 42000
1 Row inserted.

See Also

mysqli_character_set_name()

Prev | Home | Next
mysqli_real_connect | Up | mysqli_real_query


mysqli_real_query

(PHP 5)

mysqli_real_query

(no version information, might be only in CVS)

mysqli->real_query() -- Execute an SQL query

Description

Procedural style

bool mysqli_real_query ( mysqli link, string query )

Object oriented style (method):

class mysqli {

bool real_query ( string query )

}

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.

In order to determine if a given query should return a result set or not, see mysqli_field_count().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_query()
mysqli_store_result()
mysqli_use_result()

Prev | Home | Next
mysqli_real_escape_string | Up | mysqli_report


mysqli_report

(PHP 5)

mysqli_report -- Enables or disables internal report functions

Description

bool mysqli_report ( int flags )

mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).

Parameters

flags

Table 1. Supported flags

Name | Description
MYSQLI_REPORT_OFF | Turns reporting off
MYSQLI_REPORT_ERROR | Report errors from mysqli function calls
MYSQLI_REPORT_STRICT | Report warnings from mysqli function calls
MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query
MYSQLI_REPORT_ALL | Set all options (report all)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = $mysqli-&#62;query("SELECT Name FROM Nonexistingtable WHERE population &#62; 50000");

/* this query should report a warning */
$result = $mysqli-&#62;query("SELECT Name FROM City WHERE population &#62; 50000");
$result-&#62;close();

$mysqli-&#62;close();
?&#62;

See Also

mysqli_debug()
mysqli_dump_debug_info()

Prev | Home | Next
mysqli_real_query | Up | mysqli_rollback


mysqli_rollback

(PHP 5)

mysqli_rollback

(no version information, might be only in CVS)

mysqli->rollback() -- Rolls back current transaction

Description

bool mysqli_rollback ( mysqli link )

class mysqli {

bool rollback ( void )

}

Rollbacks the current transaction for the database.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli-&#62;autocommit(FALSE);

$mysqli-&#62;query("CREATE TABLE myCity LIKE City");
$mysqli-&#62;query("ALTER TABLE myCity Type=InnoDB");
$mysqli-&#62;query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli-&#62;commit();

/* delete all rows */
$mysqli-&#62;query("DELETE FROM myCity");

if ($result = $mysqli-&#62;query("SELECT COUNT(*) FROM myCity")) {
    $row = $result-&#62;fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result-&#62;close();
}

/* Rollback */
$mysqli-&#62;rollback();

if ($result = $mysqli-&#62;query("SELECT COUNT(*) FROM myCity")) {
    $row = $result-&#62;fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result-&#62;close();
}

/* Drop table myCity */
$mysqli-&#62;query("DROP TABLE myCity");

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?&#62;

The above example will output:

0 rows in table myCity.
50 rows in table myCity (after rollback).

See Also

mysqli_commit()
mysqli_autocommit()

Prev | Home | Next
mysqli_report | Up | mysqli_rpl_parse_enabled


mysqli_rpl_parse_enabled

(PHP 5)

mysqli_rpl_parse_enabled -- Check if RPL parse is enabled

Description

int mysqli_rpl_parse_enabled ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_rollback | Up | mysqli_rpl_probe


mysqli_rpl_probe

(PHP 5)

mysqli_rpl_probe -- RPL probe

Description

bool mysqli_rpl_probe ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_rpl_parse_enabled | Up | mysqli_rpl_query_type


mysqli_rpl_query_type

(PHP 5)

mysqli_rpl_query_type

(no version information, might be only in CVS)

mysqli->rpl_query_type() -- Returns RPL query type

Description

Procedural style:

int mysqli_rpl_query_type ( mysqli link, string query )

Object oriented style (method)

class mysqli {

int rpl_query_type ( string query )

}

Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_rpl_probe | Up | mysqli_select_db


mysqli_select_db

(PHP 5)

mysqli_select_db

(no version information, might be only in CVS)

mysqli->select_db() -- Selects the default database for database queries

Description

Procedural style:

bool mysqli_select_db ( mysqli link, string dbname )

Object oriented style (method):

class mysqli {

bool select_db ( string dbname )

}

Selects the default database to be used when performing queries against the database connection.

Note: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli-&#62;query("SELECT DATABASE()")) {
    $row = $result-&#62;fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result-&#62;close();
}

/* change db to world db */
$mysqli-&#62;select_db("world");

/* return name of current default database */
if ($result = $mysqli-&#62;query("SELECT DATABASE()")) {
    $row = $result-&#62;fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result-&#62;close();
}

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?&#62;

The above example will output:

Default database is test.
Default database is world.

See Also

mysqli_connect()
mysqli_real_connect()

Prev | Home | Next
mysqli_rpl_query_type | Up | mysqli_send_long_data


mysqli_send_long_data

(PHP 5)

mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()

Description

This function is an alias of mysqli_stmt_send_long_data().

Notes

Note: mysqli_send_long_data() is deprecated and will be removed.

See Also

mysqli_stmt_send_long_data()

Prev | Home | Next
mysqli_select_db | Up | mysqli_send_query


mysqli_send_query

(PHP 5)

mysqli_send_query

(no version information, might be only in CVS)

mysqli->send_query() -- Send the query and return

Description

Procedural style:

bool mysqli_send_query ( mysqli link, string query )

Object oriented style (method)

class mysqli {

bool send_query ( string query )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_send_long_data | Up | mysqli_server_end


mysqli_server_end

(PHP 5 <= 5.0.4)

mysqli_server_end -- Shut down the embedded server

Description

void mysqli_server_end ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_send_query | Up | mysqli_server_init


mysqli_server_init

(PHP 5 <= 5.0.4)

mysqli_server_init -- Initialize embedded server

Description

bool mysqli_server_init ( [array server [, array groups]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_server_end | Up | mysqli_set_charset


mysqli_set_opt

(PHP 5)

mysqli_set_opt -- Alias of mysqli_options()

Description

This function is an alias of mysqli_options().

Prev | Home | Next
mysqli_set_local_infile_handler | Up | mysqli_slave_query


mysqli_sqlstate

(PHP 5)

mysqli_sqlstate

(no version information, might be only in CVS)

mysqli->sqlstate -- Returns the SQLSTATE error from previous MySQL operation

Description

Procedural style:

string mysqli_sqlstate ( mysqli link )

Object oriented style (property):

class mysqli {

string sqlstate

}

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.

Note: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!$mysqli-&#62;query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli-&#62;sqlstate);
}

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($link);
?&#62;

The above example will output:

Error - SQLSTATE 42S01.

See Also

mysqli_errno()
mysqli_error()

Prev | Home | Next
mysqli_slave_query | Up | mysqli_ssl_set


mysqli_ssl_set

(PHP 5)

mysqli_ssl_set

(no version information, might be only in CVS)

mysqli->ssl_set() -- Used for establishing secure connections using SSL

Description

Procedural style:

bool mysqli_ssl_set ( mysqli link, string key, string cert, string ca, string capath, string cipher )

Object oriented style (method):

class mysqli {

bool ssl_set ( string key, string cert, string ca, string capath, string cipher )

}

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Any unused SSL parameters may be given as NULL

Return Values

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

See Also

mysqli_options()
mysqli_real_connect()

Prev | Home | Next
mysqli_sqlstate | Up | mysqli_stat


mysqli_stat

(PHP 5)

mysqli_stat

(no version information, might be only in CVS)

mysqli->stat() -- Gets the current system status

Description

Procedural style:

string mysqli_stat ( mysqli link )

Object oriented style (method):

class mysqli {

string stat ( void )

}

mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A string describing the server status. FALSE if an error occurred.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli-&#62;stat());

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($link);
?&#62;

The above example will output:

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
Memory in use: 8496K  Max memory used: 8560K

See Also

mysqli_get_server_info()

Prev | Home | Next
mysqli_ssl_set | Up | mysqli_stmt_affected_rows


mysqli_stmt_affected_rows

(PHP 5)

mysqli_stmt_affected_rows

(no version information, might be only in CVS)

mysqli_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Procedural style :

int mysqli_stmt_affected_rows ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int affected_rows

}

Returns the number of rows affected by INSERT, UPDATE, or DELETE query.

This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error.

Note: If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
$mysqli-&#62;query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt-&#62;bind_param("s", $code);

    /* execute statement */
    $stmt-&#62;execute();

    printf("rows inserted: %d\n", $stmt-&#62;affected_rows);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = mysqli_prepare($link, $query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    mysqli_stmt_bind_param($stmt, "s", $code);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

rows inserted: 17

See Also

mysqli_stmt_num_rows()
mysqli_prepare()

Prev | Home | Next
mysqli_stat | Up | mysqli_stmt_attr_get


mysqli_stmt_bind_param

(PHP 5)

mysqli_stmt_bind_param

(no version information, might be only in CVS)

stmt->bind_param() -- Binds variables to a prepared statement as parameters

Description

Procedural style:

bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )

Object oriented style (method):

class mysqli_stmt {

bool bind_param ( string types, mixed &var1 [, mixed &...] )

}

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare().

Note: If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

types

A string that contains one or more characters which specify the types for the corresponding bind variables:

Table 1. Type specification chars

Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packets

var1

The number of variables and length of string types must match the parameters in the statement.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli-&#62;prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt-&#62;bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt-&#62;execute();

printf("%d Row inserted.\n", $stmt-&#62;affected_rows);

/* close statement and connection */
$stmt-&#62;close();

/* Clean up table CountryLanguage */
$mysqli-&#62;query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli-&#62;affected_rows);

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

1 Row inserted.
1 Row deleted.

See Also

mysqli_stmt_bind_result()
mysqli_stmt_execute()
mysqli_stmt_fetch()
mysqli_prepare()
mysqli_stmt_send_long_data()
mysqli_stmt_errno()
mysqli_stmt_error()

Prev | Home | Next
mysqli_stmt_attr_set | Up | mysqli_stmt_bind_result


mysqli_stmt_bind_result

(PHP 5)

mysqli_stmt_bind_result

(no version information, might be only in CVS)

stmt->bind_result() -- Binds variables to a prepared statement for result storage

Description

Procedural style:

bool mysqli_stmt_bind_result ( mysqli_stmt stmt, mixed &var1 [, mixed &...] )

Object oriented style (method):

class mysqli_stmt {

bool bind_result ( mixed &var1 [, mixed &...] )

}

Binds columns in the result set to variables.

When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....

Note: Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

var1

The variable to be bound.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli-&#62;prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt-&#62;execute();

    /* bind variables to prepared statement */
    $stmt-&#62;bind_result($col1, $col2);

    /* fetch values */
    while ($stmt-&#62;fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt-&#62;close();
}
/* close connection */
$mysqli-&#62;close();

?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    mysqli_stmt_execute($stmt);

    /* bind variables to prepared statement */
    mysqli_stmt_bind_result($stmt, $col1, $col2);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

See Also

mysqli_stmt_bind_param()
mysqli_stmt_execute()
mysqli_stmt_fetch()
mysqli_prepare()
mysqli_stmt_prepare()
mysqli_stmt_init()
mysqli_stmt_errno()
mysqli_stmt_error()

Prev | Home | Next
mysqli_stmt_bind_param | Up | mysqli_stmt_close


mysqli_stmt_close

(PHP 5)

mysqli_stmt_close

(no version information, might be only in CVS)

mysqli_stmt->close() -- Closes a prepared statement

Description

Procedural style:

bool mysqli_stmt_close ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool close ( void )

}

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_prepare()

Prev | Home | Next
mysqli_stmt_bind_result | Up | mysqli_stmt_data_seek


mysqli_stmt_data_seek

(PHP 5)

mysqli_stmt_data_seek

(no version information, might be only in CVS)

stmt->data_seek() -- Seeks to an arbitray row in statement result set

Description

Procedural style:

void mysqli_stmt_data_seek ( mysqli_stmt stmt, int offset )

Object oriented style (method):

class mysqli_stmt {

void data_seek ( int offset )

}

Seeks to an arbitrary result pointer in the statement result set.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

offset

Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

Return Values

No value is returned.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* execute query */
    $stmt-&#62;execute();

    /* bind result variables */
    $stmt-&#62;bind_result($name, $code);

    /* store result */
    $stmt-&#62;store_result();

    /* seek to row no. 400 */
    $stmt-&#62;data_seek(399);

    /* fetch values */
    $stmt-&#62;fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

City: Benin City  Countrycode: NGA

See Also

mysqli_prepare()

Prev | Home | Next
mysqli_stmt_close | Up | mysqli_stmt_errno


mysqli_stmt_errno

(PHP 5)

mysqli_stmt_errno

(no version information, might be only in CVS)

mysqli_stmt->errno -- Returns the error code for the most recent statement call

Description

Procedural style :

int mysqli_stmt_errno ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int errno

}

Returns the error code for the most recently invoked statement function that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An error code value. Zero means no error occurred.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCountry LIKE Country");
$mysqli-&#62;query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* drop table */
    $mysqli-&#62;query("DROP TABLE myCountry");

    /* execute query */
    $stmt-&#62;execute();

    printf("Error: %d.\n", $stmt-&#62;errno);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %d.\n", mysqli_stmt_errno($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Error: 1146.

See Also

mysqli_stmt_error()
mysqli_stmt_sqlstate()

Prev | Home | Next
mysqli_stmt_data_seek | Up | mysqli_stmt_error


mysqli_stmt_error

(PHP 5)

mysqli_stmt_error

(no version information, might be only in CVS)

mysqli_stmt->error -- Returns a string description for last statement error

Description

Procedural style:

string mysqli_stmt_error ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

string error

}

Returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCountry LIKE Country");
$mysqli-&#62;query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* drop table */
    $mysqli-&#62;query("DROP TABLE myCountry");

    /* execute query */
    $stmt-&#62;execute();

    printf("Error: %s.\n", $stmt-&#62;error);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_error($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Error: Table 'world.myCountry' doesn't exist.

See Also

mysqli_stmt_errno()
mysqli_stmt_sqlstate()

Prev | Home | Next
mysqli_stmt_errno | Up | mysqli_stmt_execute


mysqli_stmt_execute

(PHP 5)

mysqli_stmt_execute

(no version information, might be only in CVS)

stmt->execute() -- Executes a prepared Query

Description

Procedural style:

bool mysqli_stmt_execute ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool execute ( void )

}

Executes a query that has been previously prepared using the mysqli_prepare() function. When executed any parameter markers which exist will automatically be replaced with the appropiate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.

Note: When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli-&#62;prepare($query);

$stmt-&#62;bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt-&#62;execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt-&#62;execute();

/* close statement */
$stmt-&#62;close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli-&#62;query($query)) {
    while ($row = $result-&#62;fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result-&#62;close();
}

/* remove table */
$mysqli-&#62;query("DROP TABLE myCity");

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
mysqli_stmt_execute($stmt);

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

See Also

mysqli_prepare()
mysqli_stmt_bind_param()

Prev | Home | Next
mysqli_stmt_error | Up | mysqli_stmt_fetch


mysqli_stmt_fetch

(PHP 5)

mysqli_stmt_fetch

(no version information, might be only in CVS)

stmt->fetch() -- Fetch results from a prepared statement into the bound variables

Description

Procedural style:

bool mysqli_stmt_fetch ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool fetch ( void )

}

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Note: Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Table 1. Return Values

Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occured
NULL | No more rows/data exists or data truncation occurred

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli-&#62;prepare($query)) {

    /* execute statement */
    $stmt-&#62;execute();

    /* bind result variables */
    $stmt-&#62;bind_result($name, $code);

    /* fetch values */
    while ($stmt-&#62;fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

See Also

mysqli_prepare()
mysqli_stmt_errno()
mysqli_stmt_error()
mysqli_stmt_bind_result()

Prev | Home | Next
mysqli_stmt_execute | Up | mysqli_stmt_field_count


mysqli_stmt_free_result

(PHP 5)

mysqli_stmt_free_result

(no version information, might be only in CVS)

stmt->free_result() -- Frees stored result memory for the given statement handle

Description

Procedural style:

void mysqli_stmt_free_result ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

void free_result ( void )

}

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

No value is returned.

See Also

mysqli_stmt_store_result()

Prev | Home | Next
mysqli_stmt_field_count | Up | mysqli_stmt_get_warnings


mysqli_stmt_init

(PHP 5)

mysqli_stmt_init

(no version information, might be only in CVS)

mysqli->stmt_init() -- Initializes a statement and returns an object for use with mysqli_stmt_prepare

Description

Procedural style :

mysqli_stmt mysqli_stmt_init ( mysqli link )

Object oriented style (property):

class mysqli {

mysqli_stmt stmt_init ( void )

}

Allocates and initializes a statement object suitable for mysqli_stmt_prepare().

Note: Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an object.

See Also

mysqli_stmt_prepare()

Prev | Home | Next
mysqli_stmt_get_warnings | Up | mysqli_stmt_insert_id


mysqli_stmt_num_rows

(PHP 5)

mysqli_stmt_num_rows

(no version information, might be only in CVS)

stmt->num_rows -- Return the number of rows in statements result set

Description

Procedural style :

int mysqli_stmt_num_rows ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int num_rows

}

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An integer representing the number of rows in result set.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* execute query */
    $stmt-&#62;execute();

    /* store result */
    $stmt-&#62;store_result();

    printf("Number of rows: %d.\n", $stmt-&#62;num_rows);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Number of rows: 20.

See Also

mysqli_stmt_affected_rows()
mysqli_prepare()
mysqli_stmt_store_result()

Prev | Home | Next
mysqli_stmt_insert_id | Up | mysqli_stmt_param_count


mysqli_stmt_param_count

(PHP 5)

mysqli_stmt_param_count

(no version information, might be only in CVS)

stmt->param_count -- Returns the number of parameter for the given statement

Description

Procedural style:

int mysqli_stmt_param_count ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int param_count

}

Returns the number of parameter markers present in the prepared statement.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns an integer representing the number of parameters.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli-&#62;prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt-&#62;param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = mysqli_stmt_param_count($stmt);
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Statement has 2 markers.

See Also

mysqli_prepare()

Prev | Home | Next
mysqli_stmt_num_rows | Up | mysqli_stmt_prepare


mysqli_stmt_prepare

(PHP 5)

mysqli_stmt_prepare

(no version information, might be only in CVS)

stmt->prepare() -- Prepare a SQL statement for execution

Description

Procedure style:

bool mysqli_stmt_prepare ( mysqli_stmt stmt, string query )

Object oriented style (method)

class mysqli_stmt {

mixed prepare ( string query )

}

Prepares the SQL query pointed to by the null-terminated string query.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

query

The query, as a string. It must consist of a single SQL statement.

You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: You should not add a terminating semicolon or \g to the statement.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli-&#62;stmt_init();
if ($stmt-&#62;prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt-&#62;bind_param("s", $city);

    /* execute query */
    $stmt-&#62;execute();

    /* bind result variables */
    $stmt-&#62;bind_result($district);

    /* fetch value */
    $stmt-&#62;fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Amersfoort is in district Utrecht

See Also

mysqli_stmt_init(),
mysqli_stmt_execute(),
mysqli_stmt_fetch(),
mysqli_stmt_bind_param(),
mysqli_stmt_bind_result()
mysqli_stmt_close().

Prev | Home | Next
mysqli_stmt_param_count | Up | mysqli_stmt_reset


mysqli_stmt_reset

(PHP 5)

mysqli_stmt_reset

(no version information, might be only in CVS)

stmt->reset() -- Resets a prepared statement

Description

Procedural style:

bool mysqli_stmt_reset ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool reset ( void )

}

Resets a prepared statement on client and server to state after prepare.

For now this is mainly used to reset data sent with mysqli_stmt_send_long_data().

To prepare a statement with another query use function mysqli_stmt_prepare().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

mysqli_prepare()

Prev | Home | Next
mysqli_stmt_prepare | Up | mysqli_stmt_result_metadata


mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt_result_metadata

(no version information, might be only in CVS)

stmt->result_metadata() -- Returns result set metadata from a prepared statement

Description

Procedural style:

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

mysqli_result result_metadata ( void )

}

If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.

Note: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • mysqli_num_fields()

  • mysqli_fetch_field()

  • mysqli_fetch_field_direct()

  • mysqli_fetch_fields()

  • mysqli_field_count()

  • mysqli_field_seek()

  • mysqli_field_tell()

  • mysqli_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()

Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a result object or FALSE if an error occured.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli-&#62;query("DROP TABLE IF EXISTS friends");
$mysqli-&#62;query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli-&#62;query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli-&#62;prepare("SELECT id, name FROM friends");
$stmt-&#62;execute();

/* get resultset for metadata */
$result = $stmt-&#62;result_metadata();

/* retrieve field information from metadata result set */
$field = $result-&#62;fetch_field();

printf("Fieldname: %s\n", $field-&#62;name);

/* close resultset */
$result-&#62;close();

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field-&#62;name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?&#62;

See Also

mysqli_prepare()
mysqli_free_result()

Prev | Home | Next
mysqli_stmt_reset | Up | mysqli_stmt_send_long_data


mysqli_stmt_send_long_data

(PHP 5)

mysqli_stmt_send_long_data

(no version information, might be only in CVS)

stmt->send_long_data() -- Send data in blocks

Description

Procedural style:

bool mysqli_stmt_send_long_data ( mysqli_stmt stmt, int param_nr, string data )

Object oriented style (method)

class mysqli_stmt {

bool send_long_data ( int param_nr, string data )

}

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

param_nr

Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

data

A string containing data to be sent.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
$stmt = $mysqli-&#62;prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt-&#62;bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt-&#62;send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt-&#62;execute();
?&#62;

See Also

mysqli_prepare()
mysqli_stmt_bind_param()

Prev | Home | Next
mysqli_stmt_result_metadata | Up | mysqli_stmt_sqlstate


mysqli_stmt_sqlstate

(PHP 5)

mysqli_stmt_sqlstate

(no version information, might be only in CVS)

mysqli_stmt->sqlstate() -- Returns SQLSTATE error from previous statement operation

Description

string mysqli_stmt_sqlstate ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

string sqlstate

}

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Notes

Note: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCountry LIKE Country");
$mysqli-&#62;query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* drop table */
    $mysqli-&#62;query("DROP TABLE myCountry");

    /* execute query */
    $stmt-&#62;execute();

    printf("Error: %s.\n", $stmt-&#62;sqlstate);

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Error: 42S02.

See Also

mysqli_stmt_errno()
mysqli_stmt_error()

Prev | Home | Next
mysqli_stmt_send_long_data | Up | mysqli_stmt_store_result


mysqli_stmt_store_result

(PHP 5)

mysqli_stmt_store_result

(no version information, might be only in CVS)

mysqli_stmt->store_result() -- Transfers a result set from a prepared statement

Description

Procedural style:

bool mysqli_stmt_store_result ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool store_result ( void )

}

You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.

Note: It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Object oriented style

&#60;?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli-&#62;prepare($query)) {

    /* execute query */
    $stmt-&#62;execute();

    /* store result */
    $stmt-&#62;store_result();

    printf("Number of rows: %d.\n", $stmt-&#62;num_rows);

    /* free result */
    $stmt-&#62;free_result();

    /* close statement */
    $stmt-&#62;close();
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Number of rows: 20.

See Also

mysqli_prepare()
mysqli_stmt_result_metadata()
mysqli_stmt_fetch()

Prev | Home | Next
mysqli_stmt_sqlstate | Up | mysqli_store_result


mysqli_store_result

(PHP 5)

mysqli_store_result

(no version information, might be only in CVS)

mysqli->store_result() -- Transfers a result set from the last query

Description

Procedural style:

mysqli_result mysqli_store_result ( mysqli link )

Object oriented style (method):

class mysqli {

mysqli_result store_result ( void )

}

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns a buffered result object or FALSE if an error occurred.

Note: mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successfull call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.

Notes

Note: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transfering large result sets using the mysqli_store_result() this becomes particularly important.

Examples

See mysqli_multi_query().

See Also

mysqli_real_query()
mysqli_use_result()

Prev | Home | Next
mysqli_stmt_store_result | Up | mysqli_thread_id


mysqli_thread_id

(PHP 5)

mysqli_thread_id

(no version information, might be only in CVS)

mysqli->thread_id -- Returns the thread ID for the current connection

Description

Procedural style:

int mysqli_thread_id ( mysqli link )

Object oriented style (property):

class mysqli {

int thread_id

}

The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Note: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

To kill a running query you can use the SQL command KILL QUERY processid.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns the Thread ID for the current connection.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli-&#62;thread_id;

/* Kill connection */
$mysqli-&#62;kill($thread_id);

/* This should produce an error */
if (!$mysqli-&#62;query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli-&#62;error);
    exit;
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Error: MySQL server has gone away

See Also

mysqli_kill()

Prev | Home | Next
mysqli_store_result | Up | mysqli_thread_safe


mysqli_thread_safe

(PHP 5)

mysqli_thread_safe -- Returns whether thread safety is given or not

Description

Procedural style:

bool mysqli_thread_safe ( void )

Tells whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE.

Prev | Home | Next
mysqli_thread_id | Up | mysqli_use_result


mysqli_use_result

(PHP 5)

mysqli_use_result

(no version information, might be only in CVS)

mysqli->use_result() -- Initiate a result set retrieval

Description

Procedural style:

mysqli_result mysqli_use_result ( mysqli link )

Object oriented style (method):

class mysqli {

mysqli_result use_result ( void )

}

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection.

Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Note: The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Return Values

Returns an unbuffered result object or FALSE if an error occurred.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli-&#62;multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli-&#62;use_result()) {
            while ($row = $result-&#62;fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result-&#62;close();
        }
        /* print divider */
        if ($mysqli-&#62;more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli-&#62;next_result());
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_use_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

mysqli_real_query()
mysqli_store_result()

Prev | Home | Next
mysqli_thread_safe | Up | mysqli_warning_count


mysqli_warning_count

(PHP 5)

mysqli_warning_count

(no version information, might be only in CVS)

mysqli->warning_count -- Returns the number of warnings from the last query for the given link

Description

Procedural style:

int mysqli_warning_count ( mysqli link )

Object oriented style (property):

class mysqli {

int warning_count

}

Returns the number of warnings from the last query in the connection.

Note: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Number of warnings or zero if there are no warnings.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli-&#62;query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli-&#62;query($query);

if ($mysqli-&#62;warning_count) {
    if ($result = $mysqli-&#62;query("SHOW WARNINGS")) {
        $row = $result-&#62;fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result-&#62;close();
    }
}

/* close connection */
$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?&#62;

The above example will output:

Warning (1264): Data truncated for column 'Name' at row 1

See Also

mysqli_errno()
mysqli_error()
mysqli_sqlstate()

Prev | Home | Next
mysqli_use_result | Up | Ncurses Terminal Screen Control Functions


Ncurses Terminal Screen Control Functions

PHP Manual
Prev Next

XCIX. Ncurses Terminal Screen Control Functions

Introduction

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

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.

Ncurses is available for the following platforms:

  • AIX

  • BeOS

  • Cygwin

  • Digital Unix (aka OSF1)

  • FreeBSD

  • GNU/Linux

  • HPUX

  • IRIX

  • OS/2

  • SCO OpenServer

  • Solaris

  • SunOS

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 6.0.0

Requirements

You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.

Installation

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].

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.

Error codes

On error ncurses functions return NCURSES_ERR.

Colors

Table 1. ncurses color constants

constant | meaning
NCURSES_COLOR_BLACK | no color (black)
NCURSES_COLOR_WHITE | white
NCURSES_COLOR_RED | red - supported when terminal is in color mode
NCURSES_COLOR_GREEN | green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode

Keys

Table 2. ncurses key constants

constant | meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64
NCURSES_KEY_DOWN | down arrow
NCURSES_KEY_UP | up arrow
NCURSES_KEY_LEFT | left arrow
NCURSES_KEY_RIGHT | right arrow
NCURSES_KEY_HOME | home key (upward+left arrow)
NCURSES_KEY_BACKSPACE | backspace
NCURSES_KEY_DL | delete line
NCURSES_KEY_IL | insert line
NCURSES_KEY_DC | delete character
NCURSES_KEY_IC | insert char or enter insert mode
NCURSES_KEY_EIC | exit insert char mode
NCURSES_KEY_CLEAR | clear screen
NCURSES_KEY_EOS | clear to end of screen
NCURSES_KEY_EOL | clear to end of line
NCURSES_KEY_SF | scroll one line forward
NCURSES_KEY_SR | scroll one line backward
NCURSES_KEY_NPAGE | next page
NCURSES_KEY_PPAGE | previous page
NCURSES_KEY_STAB | set tab
NCURSES_KEY_CTAB | clear tab
NCURSES_KEY_CATAB | clear all tabs
NCURSES_KEY_SRESET | soft (partial) reset
NCURSES_KEY_RESET | reset or hard reset
NCURSES_KEY_PRINT | print
NCURSES_KEY_LL | lower left
NCURSES_KEY_A1 | upper left of keypad
NCURSES_KEY_A3 | upper right of keypad
NCURSES_KEY_B2 | center of keypad
NCURSES_KEY_C1 | lower left of keypad
NCURSES_KEY_C3 | lower right of keypad
NCURSES_KEY_BTAB | back tab
NCURSES_KEY_BEG | beginning
NCURSES_KEY_CANCEL | cancel
NCURSES_KEY_CLOSE | close
NCURSES_KEY_COMMAND | cmd (command)
NCURSES_KEY_COPY | copy
NCURSES_KEY_CREATE | create
NCURSES_KEY_END | end
NCURSES_KEY_EXIT | exit
NCURSES_KEY_FIND | find
NCURSES_KEY_HELP | help
NCURSES_KEY_MARK | mark
NCURSES_KEY_MESSAGE | message
NCURSES_KEY_MOVE | move
NCURSES_KEY_NEXT | next
NCURSES_KEY_OPEN | open
NCURSES_KEY_OPTIONS | options
NCURSES_KEY_PREVIOUS | previous
NCURSES_KEY_REDO | redo
NCURSES_KEY_REFERENCE | ref (reference)
NCURSES_KEY_REFRESH | refresh
NCURSES_KEY_REPLACE | replace
NCURSES_KEY_RESTART | restart
NCURSES_KEY_RESUME | resume
NCURSES_KEY_SAVE | save
NCURSES_KEY_SBEG | shiftet beg (beginning)
NCURSES_KEY_SCANCEL | shifted cancel
NCURSES_KEY_SCOMMAND | shifted command
NCURSES_KEY_SCOPY | shifted copy
NCURSES_KEY_SCREATE | shifted create
NCURSES_KEY_SDC | shifted delete char
NCURSES_KEY_SDL | shifted delete line
NCURSES_KEY_SELECT | select
NCURSES_KEY_SEND | shifted end
NCURSES_KEY_SEOL | shifted end of line
NCURSES_KEY_SEXIT | shifted exit
NCURSES_KEY_SFIND | shifted find
NCURSES_KEY_SHELP | shifted help
NCURSES_KEY_SHOME | shifted home
NCURSES_KEY_SIC | shifted input
NCURSES_KEY_SLEFT | shifted left arrow
NCURSES_KEY_SMESSAGE | shifted message
NCURSES_KEY_SMOVE | shifted move
NCURSES_KEY_SNEXT | shifted next
NCURSES_KEY_SOPTIONS | shifted options
NCURSES_KEY_SPREVIOUS | shifted previous
NCURSES_KEY_SPRINT | shifted print
NCURSES_KEY_SREDO | shifted redo
NCURSES_KEY_SREPLACE | shifted replace
NCURSES_KEY_SRIGHT | shifted right arrow
NCURSES_KEY_SRSUME | shifted resume
NCURSES_KEY_SSAVE | shifted save
NCURSES_KEY_SSUSPEND | shifted suspend
NCURSES_KEY_UNDO | undo
NCURSES_KEY_MOUSE | mouse event has occurred
NCURSES_KEY_MAX | maximum key value

Mouse

Table 3. mouse constants

Constant | meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked
NCURSES_BUTTON_CTRL | ctrl pressed during click
NCURSES_BUTTON_SHIFT | shift pressed during click
NCURSES_BUTTON_ALT | alt pressed during click
NCURSES_ALL_MOUSE_EVENTS | report all mouse events
NCURSES_REPORT_MOUSE_POSITION | report mouse position
Table of Contents
ncurses_addch -- Add character at current position and advance cursor
ncurses_addchnstr -- Add attributed string with specified length at current position
ncurses_addchstr -- Add attributed string at current position
ncurses_addnstr -- Add string with specified length at current position
ncurses_addstr -- Output text at current position
ncurses_assume_default_colors -- Define default colors for color 0
ncurses_attroff -- Turn off the given attributes
ncurses_attron -- Turn on the given attributes
ncurses_attrset -- Set given attributes
ncurses_baudrate -- Returns baudrate of terminal
ncurses_beep -- Let the terminal beep
ncurses_bkgd -- Set background property for terminal screen
ncurses_bkgdset -- Control screen background
ncurses_border -- Draw a border around the screen using attributed characters
ncurses_bottom_panel -- Moves a visible panel to the bottom of the stack
ncurses_can_change_color -- Check if we can change terminals colors
ncurses_cbreak -- Switch of input buffering
ncurses_clear -- Clear screen
ncurses_clrtobot -- Clear screen from current position to bottom
ncurses_clrtoeol -- Clear screen from current position to end of line
ncurses_color_content -- Gets the RGB value for color
ncurses_color_set -- Set fore- and background color
ncurses_curs_set -- Set cursor state
ncurses_def_prog_mode -- Saves terminals (program) mode
ncurses_def_shell_mode -- Saves terminals (shell) mode
ncurses_define_key -- Define a keycode
ncurses_del_panel -- Remove panel from the stack and delete it (but not the associated window)
ncurses_delay_output -- Delay output on terminal using padding characters
ncurses_delch -- Delete character at current position, move rest of line left
ncurses_deleteln -- Delete line at current position, move rest of screen up
ncurses_delwin -- Delete a ncurses window
ncurses_doupdate -- Write all prepared refreshes to terminal
ncurses_echo -- Activate keyboard input echo
ncurses_echochar -- Single character output including refresh
ncurses_end -- Stop using ncurses, clean up the screen
ncurses_erase -- Erase terminal screen
ncurses_erasechar -- Returns current erase character
ncurses_filter -- Set LINES for iniscr() and newterm() to 1
ncurses_flash -- Flash terminal screen (visual bell)
ncurses_flushinp -- Flush keyboard input buffer
ncurses_getch -- Read a character from keyboard
ncurses_getmaxyx -- Returns the size of a window
ncurses_getmouse -- Reads mouse event
ncurses_getyx -- Returns the current cursor position for a window
ncurses_halfdelay -- Put terminal into halfdelay mode
ncurses_has_colors -- Check if terminal has colors
ncurses_has_ic -- Check for insert- and delete-capabilities
ncurses_has_il -- Check for line insert- and delete-capabilities
ncurses_has_key -- Check for presence of a function key on terminal keyboard
ncurses_hide_panel -- Remove panel from the stack, making it invisible
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long
ncurses_inch -- Get character and attribute at current position
ncurses_init_color -- Set new RGB value for color
ncurses_init_pair -- Allocate a color pair
ncurses_init -- Initialize ncurses
ncurses_insch -- Insert character moving rest of line including character at current position
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)
ncurses_insertln -- Insert a line, move rest of screen down
ncurses_insstr -- Insert string at current position, moving rest of line right
ncurses_instr -- Reads string from terminal screen
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed
ncurses_keyok -- Enable or disable a keycode
ncurses_keypad -- Turns keypad on or off
ncurses_killchar -- Returns current line kill character
ncurses_longname -- Returns terminals description
ncurses_meta -- Enables/Disable 8-bit meta key information
ncurses_mouse_trafo -- Transforms coordinates
ncurses_mouseinterval -- Set timeout for mouse button clicks
ncurses_mousemask -- Sets mouse options
ncurses_move_panel -- Moves a panel so that its upper-left corner is at [startx, starty]
ncurses_move -- Move output position
ncurses_mvaddch -- Move current position and add character
ncurses_mvaddchnstr -- Move position and add attributed string with specified length
ncurses_mvaddchstr -- Move position and add attributed string
ncurses_mvaddnstr -- Move position and add string with specified length
ncurses_mvaddstr -- Move position and add string
ncurses_mvcur -- Move cursor immediately
ncurses_mvdelch -- Move position and delete character, shift rest of line left
ncurses_mvgetch -- Move position and get character at new position
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long
ncurses_mvinch -- Move position and get attributed character at new position
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long
ncurses_mvwaddstr -- Add string at new position in window
ncurses_napms -- Sleep
ncurses_new_panel -- Create a new panel and associate it with window
ncurses_newpad -- Creates a new pad (window)
ncurses_newwin -- Create a new window
ncurses_nl -- Translate newline and carriage return / line feed
ncurses_nocbreak -- Switch terminal to cooked mode
ncurses_noecho -- Switch off keyboard input echo
ncurses_nonl -- Do not translate newline and carriage return / line feed
ncurses_noqiflush -- Do not flush on signal characters
ncurses_noraw -- Switch terminal out of raw mode
ncurses_pair_content -- Gets the RGB value for color
ncurses_panel_above -- Returns the panel above panel
ncurses_panel_below -- Returns the panel below panel
ncurses_panel_window -- Returns the window associated with panel
ncurses_pnoutrefresh -- Copies a region from a pad into the virtual screen
ncurses_prefresh -- Copies a region from a pad into the virtual screen
ncurses_putp -- Apply padding information to the string and output it
ncurses_qiflush -- Flush on signal characters
ncurses_raw -- Switch terminal into raw mode
ncurses_refresh -- Refresh screen
ncurses_replace_panel -- Replaces the window associated with panel
ncurses_reset_prog_mode -- Resets the prog mode saved by def_prog_mode
ncurses_reset_shell_mode -- Resets the shell mode saved by def_shell_mode
ncurses_resetty -- Restores saved terminal state
ncurses_savetty -- Saves terminal state
ncurses_scr_dump -- Dump screen content to file
ncurses_scr_init -- Initialize screen from file dump
ncurses_scr_restore -- Restore screen from file dump
ncurses_scr_set -- Inherit screen from file dump
ncurses_scrl -- Scroll window content up or down without changing current position
ncurses_show_panel -- Places an invisible panel on top of the stack, making it visible
ncurses_slk_attr -- Returns current soft label key attribute
ncurses_slk_attroff -- Turn off the given attributes for soft function-key labels
ncurses_slk_attron -- Turn on the given attributes for soft function-key labels
ncurses_slk_attrset -- Set given attributes for soft function-key labels
ncurses_slk_clear -- Clears soft labels from screen
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions
ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen
ncurses_slk_refresh -- Copies soft label keys to screen
ncurses_slk_restore -- Restores soft label keys
ncurses_slk_set -- Sets function key labels
ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed
ncurses_standend -- Stop using 'standout' attribute
ncurses_standout -- Start using 'standout' attribute
ncurses_start_color -- Start using colors
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal
ncurses_termname -- Returns terminals (short)-name
ncurses_timeout -- Set timeout for special key sequences
ncurses_top_panel -- Moves a visible panel to the top of the stack
ncurses_typeahead -- Specify different filedescriptor for typeahead checking
ncurses_ungetch -- Put a character back into the input stream
ncurses_ungetmouse -- Pushes mouse event to queue
ncurses_update_panels -- Refreshes the virtual screen to reflect the relations between panels in the stack
ncurses_use_default_colors -- Assign terminal default colors to color id -1
ncurses_use_env -- Control use of environment information about terminal size
ncurses_use_extended_names -- Control use of extended names in terminfo descriptions
ncurses_vidattr -- Display the string on the terminal in the video attribute mode
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long
ncurses_waddch -- Adds character at current position in a window and advance cursor
ncurses_waddstr -- Outputs text at current postion in window
ncurses_wattroff -- Turns off attributes for a window
ncurses_wattron -- Turns on attributes for a window
ncurses_wattrset -- Set the attributes for a window
ncurses_wborder -- Draws a border around the window using attributed characters
ncurses_wclear -- Clears window
ncurses_wcolor_set -- Sets windows color pairings
ncurses_werase -- Erase window contents
ncurses_wgetch -- Reads a character from keyboard (window)
ncurses_whline -- Draws a horizontal line in a window at current position using an attributed character and max. n characters long
ncurses_wmouse_trafo -- Transforms window/stdscr coordinates
ncurses_wmove -- Moves windows output position
ncurses_wnoutrefresh -- Copies window to virtual screen
ncurses_wrefresh -- Refresh window on terminal screen
ncurses_wstandend -- End standout mode for a window
ncurses_wstandout -- Enter standout mode for a window
ncurses_wvline -- Draws a vertical line in a window at current position using an attributed character and max. n characters long

Prev | Home | Next
mysqli_warning_count | Up | ncurses_addch


ncurses_addch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_addch -- Add character at current position and advance cursor

Description

int ncurses_addch ( int ch )

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.

Parameters

ch

Prev | Home | Next
Ncurses Terminal Screen Control Functions | Up | ncurses_addchnstr


ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addchnstr -- Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string s, int n )

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.

Parameters

s

n

Prev | Home | Next
ncurses_addch | Up | ncurses_addchstr


ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addchstr -- Add attributed string at current position

Description

int ncurses_addchstr ( string s )

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.

Parameters

s

Prev | Home | Next
ncurses_addchnstr | Up | ncurses_addnstr


ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addnstr -- Add string with specified length at current position

Description

int ncurses_addnstr ( string s, int n )

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.

Parameters

s

n

Prev | Home | Next
ncurses_addchstr | Up | ncurses_addstr


ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addstr -- Output text at current position

Description

int ncurses_addstr ( string text )

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.

Parameters

text

Prev | Home | Next
ncurses_addnstr | Up | ncurses_assume_default_colors


ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5)

ncurses_assume_default_colors -- Define default colors for color 0

Description

int ncurses_assume_default_colors ( int fg, int bg )

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.

Parameters

fg

bg

Prev | Home | Next
ncurses_addstr | Up | ncurses_attroff


ncurses_attroff

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attroff -- Turn off the given attributes

Description

int ncurses_attroff ( int attributes )

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.

Parameters

attributes

Prev | Home | Next
ncurses_assume_default_colors | Up | ncurses_attron


ncurses_attron

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attron -- Turn on the given attributes

Description

int ncurses_attron ( int attributes )

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.

Parameters

attributes

Prev | Home | Next
ncurses_attroff | Up | ncurses_attrset


ncurses_attrset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attrset -- Set given attributes

Description

int ncurses_attrset ( int attributes )

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.

Parameters

attributes

Prev | Home | Next
ncurses_attron | Up | ncurses_baudrate


ncurses_baudrate

(PHP 4 >= 4.1.0, PHP 5)

ncurses_baudrate -- Returns baudrate of terminal

Description

int ncurses_baudrate ( void )

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.

Prev | Home | Next
ncurses_attrset | Up | ncurses_beep


ncurses_beep

(PHP 4 >= 4.1.0, PHP 5)

ncurses_beep -- Let the terminal beep

Description

int ncurses_beep ( void )

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.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

See Also

ncurses_flash()

Prev | Home | Next
ncurses_baudrate | Up | ncurses_bkgd


ncurses_bkgd

(PHP 4 >= 4.1.0, PHP 5)

ncurses_bkgd -- Set background property for terminal screen

Description

int ncurses_bkgd ( int attrchar )

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.

Parameters

attrchar

Prev | Home | Next
ncurses_beep | Up | ncurses_bkgdset


ncurses_bkgdset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_bkgdset -- Control screen background

Description

void ncurses_bkgdset ( int attrchar )

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.

Parameters

attrchar

Prev | Home | Next
ncurses_bkgd | Up | ncurses_border


ncurses_border

(PHP 4 >= 4.2.0, PHP 5)

ncurses_border -- Draw a border around the screen using attributed characters

Description

int ncurses_border ( int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner )

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.

Draws the specified lines and corners around the main window.

Use ncurses_wborder() for borders around subwindows!

Parameters

Every parameter expects 0 to draw a line or 1 to skip it.

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

ncurses_wborder()

Prev | Home | Next
ncurses_bkgdset | Up | ncurses_bottom_panel


ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_bottom_panel -- Moves a visible panel to the bottom of the stack

Description

int ncurses_bottom_panel ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_border | Up | ncurses_can_change_color


ncurses_can_change_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_can_change_color -- Check if we can change terminals colors

Description

bool ncurses_can_change_color ( void )

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.

Tells whether the terminal has color capabilities and whether the programmer can change the colors.

Return Values

Return TRUE if the terminal has color capabilities and you can change the colors, FALSE otherwise.

Prev | Home | Next
ncurses_bottom_panel | Up | ncurses_cbreak


ncurses_cbreak

(PHP 4 >= 4.1.0, PHP 5)

ncurses_cbreak -- Switch of input buffering

Description

bool ncurses_cbreak ( void )

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.

Disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

Return Values

Returns TRUE or NCURSES_ERR if any error occurred.

See Also

ncurses_nocbreak()

Prev | Home | Next
ncurses_can_change_color | Up | ncurses_clear


ncurses_clear

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clear -- Clear screen

Description

bool ncurses_clear ( void )

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.

Clears the screen completely without setting blanks.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ncurses_erase()

Prev | Home | Next
ncurses_cbreak | Up | ncurses_clrtobot


ncurses_clrtobot

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clrtobot -- Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void )

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.

Erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ncurses_clear()
ncurses_clrtoeol()

Prev | Home | Next
ncurses_clear | Up | ncurses_clrtoeol


ncurses_clrtoeol

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clrtoeol -- Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void )

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.

Erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ncurses_clear()
ncurses_clrtobot()

Prev | Home | Next
ncurses_clrtobot | Up | ncurses_color_content


ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5)

ncurses_color_content -- Gets the RGB value for color

Description

int ncurses_color_content ( int color, int &r, int &g, int &b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

color

r

g

b

Prev | Home | Next
ncurses_clrtoeol | Up | ncurses_color_set


ncurses_color_set

(PHP 4 >= 4.1.0, PHP 5)

ncurses_color_set -- Set fore- and background color

Description

int ncurses_color_set ( int pair )

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.

Parameters

pair

Prev | Home | Next
ncurses_color_content | Up | ncurses_curs_set


ncurses_curs_set

(PHP 4 >= 4.1.0, PHP 5)

ncurses_curs_set -- Set cursor state

Description

int ncurses_curs_set ( int visibility )

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.

Parameters

visibility

Prev | Home | Next
ncurses_color_set | Up | ncurses_def_prog_mode


ncurses_def_prog_mode

(PHP 4 >= 4.1.0, PHP 5)

ncurses_def_prog_mode -- Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void )

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.

Saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode().

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

ncurses_reset_prog_mode()

Prev | Home | Next
ncurses_curs_set | Up | ncurses_def_shell_mode


ncurses_def_shell_mode

(PHP 4 >= 4.1.0, PHP 5)

ncurses_def_shell_mode -- Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void )

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.

Saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode().

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

ncurses_reset_shell_mode()

Prev | Home | Next
ncurses_def_prog_mode | Up | ncurses_define_key


ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5)

ncurses_define_key -- Define a keycode

Description

int ncurses_define_key ( string definition, int keycode )

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.

Parameters

definition

keycode

Prev | Home | Next
ncurses_def_shell_mode | Up | ncurses_del_panel


ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_del_panel -- Remove panel from the stack and delete it (but not the associated window)

Description

bool ncurses_del_panel ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_define_key | Up | ncurses_delay_output


ncurses_delay_output

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delay_output -- Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int milliseconds )

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.

Parameters

milliseconds

Prev | Home | Next
ncurses_del_panel | Up | ncurses_delch


ncurses_delch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delch -- Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void )

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.

Deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change.

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

ncurses_deleteln()

Prev | Home | Next
ncurses_delay_output | Up | ncurses_deleteln


ncurses_deleteln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_deleteln -- Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void )

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.

Deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change.

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

ncurses_delch()

Prev | Home | Next
ncurses_delch | Up | ncurses_delwin


ncurses_delwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delwin -- Delete a ncurses window

Description

bool ncurses_delwin ( resource window )

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.

Parameters

window

Prev | Home | Next
ncurses_deleteln | Up | ncurses_doupdate


ncurses_doupdate

(PHP 4 >= 4.1.0, PHP 5)

ncurses_doupdate -- Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void )

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.

Compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ncurses_delwin | Up | ncurses_echo


ncurses_echo

(PHP 4 >= 4.1.0, PHP 5)

ncurses_echo -- Activate keyboard input echo

Description

bool ncurses_echo ( void )

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.

Enables echo mode. All characters typed by user are echoed by ncurses_getch().

Return Values

Returns FALSE on success, TRUE if any error occurred.

See Also

ncurses_noecho() to disable echo mode

Prev | Home | Next
ncurses_doupdate | Up | ncurses_echochar


ncurses_echochar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_echochar -- Single character output including refresh

Description

int ncurses_echochar ( int character )

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.

Parameters

character

Prev | Home | Next
ncurses_echo | Up | ncurses_end


ncurses_end

(PHP 4 >= 4.1.0, PHP 5)

ncurses_end -- Stop using ncurses, clean up the screen

Description

int ncurses_end ( void )

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.

Prev | Home | Next
ncurses_echochar | Up | ncurses_erase


ncurses_erase

(PHP 4 >= 4.1.0, PHP 5)

ncurses_erase -- Erase terminal screen

Description

bool ncurses_erase ( void )

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.

Fills the terminal screen with blanks.

Created blanks have the current background rendition, set by ncurses_bkgd().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ncurses_bkgd()
ncurses_clear()

Prev | Home | Next
ncurses_end | Up | ncurses_erasechar


ncurses_erasechar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_erasechar -- Returns current erase character

Description

string ncurses_erasechar ( void )

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.

Returns the current erase character.

Return Values

The current erase char, as a string.

See Also

ncurses_killchar()

Prev | Home | Next
ncurses_erase | Up | ncurses_filter


ncurses_filter

(PHP 4 >= 4.1.0, PHP 5)

ncurses_filter -- Set LINES for iniscr() and newterm() to 1

Description

void ncurses_filter ( void )

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.

Prev | Home | Next
ncurses_erasechar | Up | ncurses_flash


ncurses_flash

(PHP 4 >= 4.1.0, PHP 5)

ncurses_flash -- Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void )

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.

Flashes the screen, and if its not possible, sends an audible alert (bell).

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

ncurses_beep()

Prev | Home | Next
ncurses_filter | Up | ncurses_flushinp


ncurses_flushinp

(PHP 4 >= 4.1.0, PHP 5)

ncurses_flushinp -- Flush keyboard input buffer

Description

bool ncurses_flushinp ( void )

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.

Throws away any typeahead that has been typed and has not yet been read by your program.

Return Values

Returns FALSE on success, otherwise TRUE.

Prev | Home | Next
ncurses_flash | Up | ncurses_getch


ncurses_getch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_getch -- Read a character from keyboard

Description

int ncurses_getch ( void )

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.

Prev | Home | Next
ncurses_flushinp | Up | ncurses_getmaxyx


ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5)

ncurses_getmaxyx -- Returns the size of a window

Description

void ncurses_getmaxyx ( resource window, int &y, int &x )

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.

Gets the horizontal and vertical size of the given window into the given variables.

Variables must be passed as reference, so they are updated when the user changes the terminal size.

Parameters

window

The measured window

x

This will be set to the window width

y

This will be set to the window height

Return Values

No value is returned.

Prev | Home | Next
ncurses_getch | Up | ncurses_getmouse


ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5)

ncurses_getmouse -- Reads mouse event

Description

bool ncurses_getmouse ( array &mevent )

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.

ncurses_getmouse() reads mouse event out of queue.

Parameters

mevent

Event options will be delivered in this parameter which has to be an array, passed by reference (see example below).

On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE if a mouse event is actually visible in the given window, otherwise returns TRUE.

Examples

Example 1. ncurses_getmouse() example

&#60;?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse(&#38;$mevent)){
      if ($mevent["mmask"] &#38; NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?&#62;

See Also

ncurses_ungetmouse()

Prev | Home | Next
ncurses_getmaxyx | Up | ncurses_getyx


ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5)

ncurses_getyx -- Returns the current cursor position for a window

Description

void ncurses_getyx ( resource window, int &y, int &x )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

y

x

Prev | Home | Next
ncurses_getmouse | Up | ncurses_halfdelay


ncurses_halfdelay

(PHP 4 >= 4.1.0, PHP 5)

ncurses_halfdelay -- Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int tenth )

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.

Parameters

tenth

Prev | Home | Next
ncurses_getyx | Up | ncurses_has_colors


ncurses_has_colors

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_colors -- Check if terminal has colors

Description

bool ncurses_has_colors ( void )

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.

Checks wether the terminal has color capacities.

Return Values

Return TRUE if the terminal has color capacities, FALSE otherwise.

See Also

ncurses_can_change_color()

Prev | Home | Next
ncurses_halfdelay | Up | ncurses_has_ic


ncurses_has_ic

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_ic -- Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void )

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.

Checks whether the terminal has insert and delete capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-capabilities, FALSE otherwise.

See Also

ncurses_has_il()

Prev | Home | Next
ncurses_has_colors | Up | ncurses_has_il


ncurses_has_il

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_il -- Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void )

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.

Checks whether the terminal has insert- and delete-line-capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-line capabilities, FALSE otherwise.

See Also

ncurses_has_ic()

Prev | Home | Next
ncurses_has_ic | Up | ncurses_has_key


ncurses_has_key

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_key -- Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int keycode )

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.

Parameters

keycode

Prev | Home | Next
ncurses_has_il | Up | ncurses_hide_panel


ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_hide_panel -- Remove panel from the stack, making it invisible

Description

int ncurses_hide_panel ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_has_key | Up | ncurses_hline


ncurses_hline

(PHP 4 >= 4.2.0, PHP 5)

ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int charattr, int n )

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.

Parameters

charattr

n

Prev | Home | Next
ncurses_hide_panel | Up | ncurses_inch


ncurses_inch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_inch -- Get character and attribute at current position

Description

string ncurses_inch ( void )

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.

Returns the character from the current position.

Return Values

Returns the character, as a string.

Prev | Home | Next
ncurses_hline | Up | ncurses_init_color


ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5)

ncurses_init_color -- Set new RGB value for color

Description

int ncurses_init_color ( int color, int r, int g, int b )

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.

Parameters

color

r

g

b

Prev | Home | Next
ncurses_inch | Up | ncurses_init_pair


ncurses_init_pair

(PHP 4 >= 4.1.0, PHP 5)

ncurses_init_pair -- Allocate a color pair

Description

int ncurses_init_pair ( int pair, int fg, int bg )

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.

Parameters

pair

fg

bg

Prev | Home | Next
ncurses_init_color | Up | ncurses_init


ncurses_init

(PHP 4 >= 4.1.0, PHP 5)

ncurses_init -- Initialize ncurses

Description

void ncurses_init ( void )

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.

Initializes the ncurses interface and must be used before any other ncurses function call.

Return Values

No value is returned.

Prev | Home | Next
ncurses_init_pair | Up | ncurses_insch


ncurses_insch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insch -- Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int character )

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.

Parameters

character

Prev | Home | Next
ncurses_init | Up | ncurses_insdelln


ncurses_insdelln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int count )

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.

Parameters

count

Prev | Home | Next
ncurses_insch | Up | ncurses_insertln


ncurses_insertln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insertln -- Insert a line, move rest of screen down

Description

int ncurses_insertln ( void )

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.

Inserts a new line above the current line. The bottom line will be lost.

Prev | Home | Next
ncurses_insdelln | Up | ncurses_insstr


ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_insstr -- Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string text )

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.

Parameters

text

Prev | Home | Next
ncurses_insertln | Up | ncurses_instr


ncurses_instr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_instr -- Reads string from terminal screen

Description

int ncurses_instr ( string &buffer )

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.

Reads a string from the terminal screen and returns the number of characters read from the current character position until end of line.

Parameters

buffer

The characters. Attributes will be stripped.

Return Values

Returns the number of characters.

Prev | Home | Next
ncurses_insstr | Up | ncurses_isendwin


ncurses_isendwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void )

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.

Checks if ncurses is in endwin mode.

Return Values

Returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), FALSE otherwise.

See Also

ncurses_endwin()
ncurses_wrefresh()

Prev | Home | Next
ncurses_instr | Up | ncurses_keyok


ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5)

ncurses_keyok -- Enable or disable a keycode

Description

int ncurses_keyok ( int keycode, bool enable )

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.

Parameters

keycode

enable

Prev | Home | Next
ncurses_isendwin | Up | ncurses_keypad


ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5)

ncurses_keypad -- Turns keypad on or off

Description

int ncurses_keypad ( resource window, bool bf )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

bf

Prev | Home | Next
ncurses_keyok | Up | ncurses_killchar


ncurses_killchar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_killchar -- Returns current line kill character

Description

string ncurses_killchar ( void )

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.

Returns the current line kill character.

Return Values

Returns the kill character, as a string.

See Also

ncurses_erasechar()

Prev | Home | Next
ncurses_keypad | Up | ncurses_longname


ncurses_longname

(PHP 4 >= 4.2.0, PHP 5)

ncurses_longname -- Returns terminals description

Description

string ncurses_longname ( void )

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.

Returns a verbose description of the terminal.

Return Values

Returns the description, as a string truncated to 128 characters. On errors, returns NULL.

See Also

ncurses_termname()

Prev | Home | Next
ncurses_killchar | Up | ncurses_meta


ncurses_meta

(PHP 4 >= 4.3.0, PHP 5)

ncurses_meta -- Enables/Disable 8-bit meta key information

Description

int ncurses_meta ( resource window, bool 8bit )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

8bit

Prev | Home | Next
ncurses_longname | Up | ncurses_mouse_trafo


ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mouse_trafo -- Transforms coordinates

Description

bool ncurses_mouse_trafo ( int &y, int &x, bool toscreen )

Warning

This function is currently not documented; only the argument list is available.

Parameters

y

x

toscreen

Prev | Home | Next
ncurses_meta | Up | ncurses_mouseinterval


ncurses_mouseinterval

(PHP 4 >= 4.1.0, PHP 5)

ncurses_mouseinterval -- Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int milliseconds )

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.

Parameters

milliseconds

Prev | Home | Next
ncurses_mouse_trafo | Up | ncurses_mousemask


ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mousemask -- Sets mouse options

Description

int ncurses_mousemask ( int newmask, int &oldmask )

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.

Sets mouse events to be reported. By default no mouse events will be reported.

Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of queue, call ncurses_getmouse().

Parameters

newmask

Mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

oldmask

This will be set to the previous value of the mouse event mask.

Return Values

Returns a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0.

Examples

Example 1. ncurses_mousemask() example

&#60;?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, &#38;$oldmask);
if ($mask &#38; $newmask){
    printf("All specified mouse options will be supported\n");
}
?&#62;

See Also

ncurses_getmouse()
ncurses_ungetmouse()
ncurese_getch()

Prev | Home | Next
ncurses_mouseinterval | Up | ncurses_move_panel


ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_move_panel -- Moves a panel so that its upper-left corner is at [startx, starty]

Description

int ncurses_move_panel ( resource panel, int startx, int starty )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

startx

starty

Prev | Home | Next
ncurses_mousemask | Up | ncurses_move


ncurses_move

(PHP 4 >= 4.1.0, PHP 5)

ncurses_move -- Move output position

Description

int ncurses_move ( int y, int x )

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.

Parameters

y

x

Prev | Home | Next
ncurses_move_panel | Up | ncurses_mvaddch


ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddch -- Move current position and add character

Description

int ncurses_mvaddch ( int y, int x, int c )

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.

Parameters

y

x

c

Prev | Home | Next
ncurses_move | Up | ncurses_mvaddchnstr


ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddchnstr -- Move position and add attributed string with specified length

Description

int ncurses_mvaddchnstr ( int y, int x, string s, int n )

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.

Parameters

y

x

s

n

Prev | Home | Next
ncurses_mvaddch | Up | ncurses_mvaddchstr


ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddchstr -- Move position and add attributed string

Description

int ncurses_mvaddchstr ( int y, int x, string s )

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.

Parameters

y

x

s

Prev | Home | Next
ncurses_mvaddchnstr | Up | ncurses_mvaddnstr


ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddnstr -- Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int y, int x, string s, int n )

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.

Parameters

y

x

s

n

Prev | Home | Next
ncurses_mvaddchstr | Up | ncurses_mvaddstr


ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddstr -- Move position and add string

Description

int ncurses_mvaddstr ( int y, int x, string s )

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.

Parameters

y

x

s

Prev | Home | Next
ncurses_mvaddnstr | Up | ncurses_mvcur


ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvcur -- Move cursor immediately

Description

int ncurses_mvcur ( int old_y, int old_x, int new_y, int new_x )

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.

Parameters

old_y

old_x

new_y

new_x

Prev | Home | Next
ncurses_mvaddstr | Up | ncurses_mvdelch


ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvdelch -- Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int y, int x )

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.

Parameters

y

x

Prev | Home | Next
ncurses_mvcur | Up | ncurses_mvgetch


ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvgetch -- Move position and get character at new position

Description

int ncurses_mvgetch ( int y, int x )

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.

Parameters

y

x

Prev | Home | Next
ncurses_mvdelch | Up | ncurses_mvhline


ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int y, int x, int attrchar, int n )

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.

Parameters

y

x

attrchar

n

Prev | Home | Next
ncurses_mvgetch | Up | ncurses_mvinch


ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvinch -- Move position and get attributed character at new position

Description

int ncurses_mvinch ( int y, int x )

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.

Parameters

y

x

Prev | Home | Next
ncurses_mvhline | Up | ncurses_mvvline


ncurses_mvvline

(no version information, might be only in CVS)

ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int y, int x, int attrchar, int n )

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.

Parameters

y

x

attrchar

n

Prev | Home | Next
ncurses_mvinch | Up | ncurses_mvwaddstr


ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvwaddstr -- Add string at new position in window

Description

int ncurses_mvwaddstr ( resource window, int y, int x, string text )

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.

Parameters

window

y

x

text

Prev | Home | Next
ncurses_mvvline | Up | ncurses_napms


ncurses_napms

(PHP 4 >= 4.1.0, PHP 5)

ncurses_napms -- Sleep

Description

int ncurses_napms ( int milliseconds )

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.

Parameters

milliseconds

Prev | Home | Next
ncurses_mvwaddstr | Up | ncurses_new_panel


ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_new_panel -- Create a new panel and associate it with window

Description

resource ncurses_new_panel ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_napms | Up | ncurses_newpad


ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5)

ncurses_newpad -- Creates a new pad (window)

Description

resource ncurses_newpad ( int rows, int cols )

Warning

This function is currently not documented; only the argument list is available.

Parameters

rows

cols

Prev | Home | Next
ncurses_new_panel | Up | ncurses_newwin


ncurses_newwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_newwin -- Create a new window

Description

resource ncurses_newwin ( int rows, int cols, int y, int x )

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.

Creates a new window to draw elements in.

When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary.

Parameters

rows

Number of rows

cols

Number of columns

y

y-ccordinate of the origin

x

x-ccordinate of the origin

Return Values

Returns a resource ID for the new window.

Prev | Home | Next
ncurses_newpad | Up | ncurses_nl


ncurses_nl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nl -- Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void )

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.

Prev | Home | Next
ncurses_newwin | Up | ncurses_nocbreak


ncurses_nocbreak

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nocbreak -- Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void )

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.

Returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

ncurses_cbreak()

Prev | Home | Next
ncurses_nl | Up | ncurses_noecho


ncurses_noecho

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noecho -- Switch off keyboard input echo

Description

bool ncurses_noecho ( void )

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.

Prevents echoing of user typed characters.

Return Values

Returns TRUE if any error occurred, FALSE otherwise.

See Also

ncurses_echo()
ncurses_getch()

Prev | Home | Next
ncurses_nocbreak | Up | ncurses_nonl


ncurses_nonl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nonl -- Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void )

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.

Prev | Home | Next
ncurses_noecho | Up | ncurses_noqiflush


ncurses_noqiflush

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noqiflush -- Do not flush on signal characters

Description

void ncurses_noqiflush ( void )

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.

Prev | Home | Next
ncurses_nonl | Up | ncurses_noraw


ncurses_noraw

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noraw -- Switch terminal out of raw mode

Description

bool ncurses_noraw ( void )

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.

Switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

ncurses_raw()
ncurses_cbreak()
ncurses_nocbreak()

Prev | Home | Next
ncurses_noqiflush | Up | ncurses_pair_content


ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5)

ncurses_pair_content -- Gets the RGB value for color

Description

int ncurses_pair_content ( int pair, int &f, int &b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

pair

f

b

Prev | Home | Next
ncurses_noraw | Up | ncurses_panel_above


ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_above -- Returns the panel above panel

Description

resource ncurses_panel_above ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Return Values

If panel is null, returns the bottom panel in the stack.

Prev | Home | Next
ncurses_pair_content | Up | ncurses_panel_below


ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_below -- Returns the panel below panel

Description

resource ncurses_panel_below ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Parameters

If panel is null, returns the top panel in the stack.

Prev | Home | Next
ncurses_panel_above | Up | ncurses_panel_window


ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_window -- Returns the window associated with panel

Description

resource ncurses_panel_window ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_panel_below | Up | ncurses_pnoutrefresh


ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5)

ncurses_pnoutrefresh -- Copies a region from a pad into the virtual screen

Description

int ncurses_pnoutrefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol )

Warning

This function is currently not documented; only the argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

Prev | Home | Next
ncurses_panel_window | Up | ncurses_prefresh


ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5)

ncurses_prefresh -- Copies a region from a pad into the virtual screen

Description

int ncurses_prefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol )

Warning

This function is currently not documented; only the argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

Prev | Home | Next
ncurses_pnoutrefresh | Up | ncurses_putp


ncurses_putp

(PHP 4 >= 4.2.0, PHP 5)

ncurses_putp -- Apply padding information to the string and output it

Description

int ncurses_putp ( string text )

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.

Parameters

text

Prev | Home | Next
ncurses_prefresh | Up | ncurses_qiflush


ncurses_qiflush

(PHP 4 >= 4.1.0, PHP 5)

ncurses_qiflush -- Flush on signal characters

Description

void ncurses_qiflush ( void )

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.

Prev | Home | Next
ncurses_putp | Up | ncurses_raw


ncurses_raw

(PHP 4 >= 4.1.0, PHP 5)

ncurses_raw -- Switch terminal into raw mode

Description

bool ncurses_raw ( void )

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.

Places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

ncurses_noraw()
ncurses_cbreak()
ncurses_nocbreak()

Prev | Home | Next
ncurses_qiflush | Up | ncurses_refresh


ncurses_refresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_refresh -- Refresh screen

Description

int ncurses_refresh ( int ch )

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.

Parameters

ch

Prev | Home | Next
ncurses_raw | Up | ncurses_replace_panel


ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_replace_panel -- Replaces the window associated with panel

Description

int ncurses_replace_panel ( resource panel, resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

window

Prev | Home | Next
ncurses_refresh | Up | ncurses_reset_prog_mode


ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5)

ncurses_reset_prog_mode -- Resets the prog mode saved by def_prog_mode

Description

int ncurses_reset_prog_mode ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ncurses_replace_panel | Up | ncurses_reset_shell_mode


ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5)

ncurses_reset_shell_mode -- Resets the shell mode saved by def_shell_mode

Description

int ncurses_reset_shell_mode ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ncurses_reset_prog_mode | Up | ncurses_resetty


ncurses_resetty

(PHP 4 >= 4.1.0, PHP 5)

ncurses_resetty -- Restores saved terminal state

Description

bool ncurses_resetty ( void )

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.

Restores the terminal state, which was previously saved by calling ncurses_savetty().

Return Values

Always returns FALSE.

See Also

ncurses_savetty()

Prev | Home | Next
ncurses_reset_shell_mode | Up | ncurses_savetty


ncurses_savetty

(PHP 4 >= 4.1.0, PHP 5)

ncurses_savetty -- Saves terminal state

Description

bool ncurses_savetty ( void )

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.

Saves the current terminal state. The saved terminal state can be restored with ncurses_resetty().

Return Values

Always returns FALSE.

See Also

ncurses_resetty()

Prev | Home | Next
ncurses_resetty | Up | ncurses_scr_dump


ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_dump -- Dump screen content to file

Description

int ncurses_scr_dump ( string filename )

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.

Parameters

filename

Prev | Home | Next
ncurses_savetty | Up | ncurses_scr_init


ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_init -- Initialize screen from file dump

Description

int ncurses_scr_init ( string filename )

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.

Parameters

filename

Prev | Home | Next
ncurses_scr_dump | Up | ncurses_scr_restore


ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_restore -- Restore screen from file dump

Description

int ncurses_scr_restore ( string filename )

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.

Parameters

filename

Prev | Home | Next
ncurses_scr_init | Up | ncurses_scr_set


ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_set -- Inherit screen from file dump

Description

int ncurses_scr_set ( string filename )

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.

Parameters

filename

Prev | Home | Next
ncurses_scr_restore | Up | ncurses_scrl


ncurses_scrl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_scrl -- Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int count )

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.

Parameters

count

Prev | Home | Next
ncurses_scr_set | Up | ncurses_show_panel


ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_show_panel -- Places an invisible panel on top of the stack, making it visible

Description

int ncurses_show_panel ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_scrl | Up | ncurses_slk_attr


ncurses_slk_attr

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attr -- Returns current soft label key attribute

Description

int ncurses_slk_attr ( void )

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.

Returns the current soft label key attribute.

Return Values

The attribute, as an integer.

Prev | Home | Next
ncurses_show_panel | Up | ncurses_slk_attroff


ncurses_slk_attroff

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attroff -- Turn off the given attributes for soft function-key labels

Description

int ncurses_slk_attroff ( int intarg )

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.

Parameters

intarg

Prev | Home | Next
ncurses_slk_attr | Up | ncurses_slk_attron


ncurses_slk_attron

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attron -- Turn on the given attributes for soft function-key labels

Description

int ncurses_slk_attron ( int intarg )

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.

Parameters

intarg

Prev | Home | Next
ncurses_slk_attroff | Up | ncurses_slk_attrset


ncurses_slk_attrset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attrset -- Set given attributes for soft function-key labels

Description

int ncurses_slk_attrset ( int intarg )

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.

Parameters

intarg

Prev | Home | Next
ncurses_slk_attron | Up | ncurses_slk_clear


ncurses_slk_clear

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_clear -- Clears soft labels from screen

Description

bool ncurses_slk_clear ( void )

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.

The function ncurses_slk_clear() clears soft label keys from screen.

Return Values

Returns TRUE on errors, FALSE otherwise.

Prev | Home | Next
ncurses_slk_attrset | Up | ncurses_slk_color


ncurses_slk_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_color -- Sets color for soft label keys

Description

int ncurses_slk_color ( int intarg )

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.

Parameters

intarg

Prev | Home | Next
ncurses_slk_clear | Up | ncurses_slk_init


ncurses_slk_init

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_init -- Initializes soft label key functions

Description

bool ncurses_slk_init ( int format )

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.

Initializes soft label key functions

This function must be called before ncurses_initscr() or ncurses_newterm() is called.

Parameters

format

If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then this parameter determines how the labels are arranged of the screen.

0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ncurses_slk_color | Up | ncurses_slk_noutrefresh


ncurses_slk_noutrefresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void )

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.

Prev | Home | Next
ncurses_slk_init | Up | ncurses_slk_refresh


ncurses_slk_refresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_refresh -- Copies soft label keys to screen

Description

int ncurses_slk_refresh ( void )

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.

Copies soft label keys from virtual screen to physical screen.

Prev | Home | Next
ncurses_slk_noutrefresh | Up | ncurses_slk_restore


ncurses_slk_restore

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_restore -- Restores soft label keys

Description

int ncurses_slk_restore ( void )

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.

Restores the soft label keys after ncurses_slk_clear() has been performed.

Prev | Home | Next
ncurses_slk_refresh | Up | ncurses_slk_set


ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_slk_set -- Sets function key labels

Description

bool ncurses_slk_set ( int labelnr, string label, int format )

Warning

This function is currently not documented; only the argument list is available.

Parameters

labelnr

label

format

Prev | Home | Next
ncurses_slk_restore | Up | ncurses_slk_touch


ncurses_slk_touch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed

Description

int ncurses_slk_touch ( void )

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.

Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

Prev | Home | Next
ncurses_slk_set | Up | ncurses_standend


ncurses_standend

(PHP 4 >= 4.1.0, PHP 5)

ncurses_standend -- Stop using 'standout' attribute

Description

int ncurses_standend ( void )

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.

Prev | Home | Next
ncurses_slk_touch | Up | ncurses_standout


ncurses_standout

(PHP 4 >= 4.1.0, PHP 5)

ncurses_standout -- Start using 'standout' attribute

Description

int ncurses_standout ( void )

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.

Prev | Home | Next
ncurses_standend | Up | ncurses_start_color


ncurses_start_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_start_color -- Start using colors

Description

int ncurses_start_color ( void )

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.

Prev | Home | Next
ncurses_standout | Up | ncurses_termattrs


ncurses_termattrs

(PHP 4 >= 4.1.0, PHP 5)

ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void )

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.

Prev | Home | Next
ncurses_start_color | Up | ncurses_termname


ncurses_termname

(PHP 4 >= 4.2.0, PHP 5)

ncurses_termname -- Returns terminals (short)-name

Description

string ncurses_termname ( void )

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.

Returns terminals shortname.

Return Values

Returns the shortname of the terminal, truncated to 14 characters. On errors, returns NULL.

See Also

ncurses_longname()

Prev | Home | Next
ncurses_termattrs | Up | ncurses_timeout


ncurses_timeout

(PHP 4 >= 4.1.0, PHP 5)

ncurses_timeout -- Set timeout for special key sequences

Description

void ncurses_timeout ( int millisec )

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.

Parameters

millisec

Prev | Home | Next
ncurses_termname | Up | ncurses_top_panel


ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_top_panel -- Moves a visible panel to the top of the stack

Description

int ncurses_top_panel ( resource panel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

panel

Prev | Home | Next
ncurses_timeout | Up | ncurses_typeahead


ncurses_typeahead

(PHP 4 >= 4.1.0, PHP 5)

ncurses_typeahead -- Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int fd )

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.

Parameters

fd

Prev | Home | Next
ncurses_top_panel | Up | ncurses_ungetch


ncurses_ungetch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_ungetch -- Put a character back into the input stream

Description

int ncurses_ungetch ( int keycode )

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.

Parameters

keycode

Prev | Home | Next
ncurses_typeahead | Up | ncurses_ungetmouse


ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5)

ncurses_ungetmouse -- Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array mevent )

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.

Pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent.

Parameters

mevent

An associative array specifying the event options:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

ncurses_getmouse()

Prev | Home | Next
ncurses_ungetch | Up | ncurses_update_panels


ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5)

ncurses_update_panels -- Refreshes the virtual screen to reflect the relations between panels in the stack

Description

void ncurses_update_panels ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ncurses_ungetmouse | Up | ncurses_use_default_colors


ncurses_use_default_colors

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_default_colors -- Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void )

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.

Prev | Home | Next
ncurses_update_panels | Up | ncurses_use_env


ncurses_use_env

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_env -- Control use of environment information about terminal size

Description

void ncurses_use_env ( bool flag )

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.

Parameters

flag

Prev | Home | Next
ncurses_use_default_colors | Up | ncurses_use_extended_names


ncurses_use_extended_names

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_extended_names -- Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool flag )

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.

Parameters

flag

Prev | Home | Next
ncurses_use_env | Up | ncurses_vidattr


ncurses_vidattr

(PHP 4 >= 4.1.0, PHP 5)

ncurses_vidattr -- Display the string on the terminal in the video attribute mode

Description

int ncurses_vidattr ( int intarg )

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.

Parameters

intarg

Prev | Home | Next
ncurses_use_extended_names | Up | ncurses_vline


ncurses_vline

(PHP 4 >= 4.2.0, PHP 5)

ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int charattr, int n )

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.

Parameters

charattr

n

Prev | Home | Next
ncurses_vidattr | Up | ncurses_waddch


ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5)

ncurses_waddch -- Adds character at current position in a window and advance cursor

Description

int ncurses_waddch ( resource window, int ch )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

ch

Prev | Home | Next
ncurses_vline | Up | ncurses_waddstr


ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_waddstr -- Outputs text at current postion in window

Description

int ncurses_waddstr ( resource window, string str [, int n] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

str

n

Prev | Home | Next
ncurses_waddch | Up | ncurses_wattroff


ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattroff -- Turns off attributes for a window

Description

int ncurses_wattroff ( resource window, int attrs )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

attrs

Prev | Home | Next
ncurses_waddstr | Up | ncurses_wattron


ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattron -- Turns on attributes for a window

Description

int ncurses_wattron ( resource window, int attrs )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

attrs

Prev | Home | Next
ncurses_wattroff | Up | ncurses_wattrset


ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattrset -- Set the attributes for a window

Description

int ncurses_wattrset ( resource window, int attrs )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

attrs

Prev | Home | Next
ncurses_wattron | Up | ncurses_wborder


ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wborder -- Draws a border around the window using attributed characters

Description

int ncurses_wborder ( resource window, int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner )

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.

Draws the specified lines and corners around the passed window.

Use ncurses_border() for borders around the main window.

Parameters

Each parameter expects 0 to draw a line and 1 to skip it.

window

The window on which we operate

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

ncurses_border()

Prev | Home | Next
ncurses_wattrset | Up | ncurses_wclear


ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wclear -- Clears window

Description

int ncurses_wclear ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_wborder | Up | ncurses_wcolor_set


ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wcolor_set -- Sets windows color pairings

Description

int ncurses_wcolor_set ( resource window, int color_pair )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

color_pair

Prev | Home | Next
ncurses_wclear | Up | ncurses_werase


ncurses_werase

(PHP 4 >= 4.3.0, PHP 5)

ncurses_werase -- Erase window contents

Description

int ncurses_werase ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_wcolor_set | Up | ncurses_wgetch


ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wgetch -- Reads a character from keyboard (window)

Description

int ncurses_wgetch ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_werase | Up | ncurses_whline


ncurses_whline

(PHP 4 >= 4.3.0, PHP 5)

ncurses_whline -- Draws a horizontal line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_whline ( resource window, int charattr, int n )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

charattr

n

Prev | Home | Next
ncurses_wgetch | Up | ncurses_wmouse_trafo


ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wmouse_trafo -- Transforms window/stdscr coordinates

Description

bool ncurses_wmouse_trafo ( resource window, int &y, int &x, bool toscreen )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

x

y

toscreen

Prev | Home | Next
ncurses_whline | Up | ncurses_wmove


ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wmove -- Moves windows output position

Description

int ncurses_wmove ( resource window, int y, int x )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

y

x

Prev | Home | Next
ncurses_wmouse_trafo | Up | ncurses_wnoutrefresh


ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wnoutrefresh -- Copies window to virtual screen

Description

int ncurses_wnoutrefresh ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_wmove | Up | ncurses_wrefresh


ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wrefresh -- Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource window )

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.

Parameters

window

Prev | Home | Next
ncurses_wnoutrefresh | Up | ncurses_wstandend


ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wstandend -- End standout mode for a window

Description

int ncurses_wstandend ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_wrefresh | Up | ncurses_wstandout


ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wstandout -- Enter standout mode for a window

Description

int ncurses_wstandout ( resource window )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

Prev | Home | Next
ncurses_wstandend | Up | ncurses_wvline


ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wvline -- Draws a vertical line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_wvline ( resource window, int charattr, int n )

Warning

This function is currently not documented; only the argument list is available.

Parameters

window

charattr

n

Prev | Home | Next
ncurses_wstandout | Up | Network Functions


Network Functions

PHP Manual
Prev Next

C. Network Functions

Introduction

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. Network Configuration Options

Name | Default | Changeable | Changelog
define_syslog_variables | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

define_syslog_variables boolean

Whether or not to define the various syslog variables (e.g. $LOG_PID, $LOG_CRON, etc.). Turning it off is a good idea performance-wise. At runtime, you can define these variables by calling define_syslog_variables().

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are always available as part of the PHP core.

Table 2. openlog() Options

Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_NOWAIT |
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message

Table 3. openlog() Facilities

Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

Table 4. syslog() Priorities (in descending order)

Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

Table 5. dns_get_record() Options

Constant | Description
DNS_A | IPv4 Address Resource
DNS_MX | Mail Exchanger Resource
DNS_CNAME | Alias (Canonical Name) Resource
DNS_NS | Authoritative Name Server Resource
DNS_PTR | Pointer Resource
DNS_HINFO | Host Info Resource (See IANA's Operating System Names for the meaning of these values)
DNS_SOA | Start of Authority Resource
DNS_TXT | Text Resource
DNS_ANY | Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA | IPv6 Address Resource
DNS_ALL | Iteratively query the name server for each available record type.
Table of Contents
checkdnsrr -- Check DNS records corresponding to a given Internet host name or IP address
closelog -- Close connection to system logger
debugger_off -- Disable internal PHP debugger (PHP 3)
debugger_on -- Enable internal PHP debugger (PHP 3)
define_syslog_variables -- Initializes all syslog related constants
dns_check_record -- Synonym for checkdnsrr()
dns_get_mx -- Synonym for getmxrr()
dns_get_record -- Fetch DNS Resource Records associated with a hostname
fsockopen -- Open Internet or Unix domain socket connection
gethostbyaddr -- Get the Internet host name corresponding to a given IP address
gethostbyname -- Get the IP address corresponding to a given Internet host name
gethostbynamel -- Get a list of IP addresses corresponding to a given Internet host name
getmxrr -- Get MX records corresponding to a given Internet host name
getprotobyname -- Get protocol number associated with protocol name
getprotobynumber -- Get protocol name associated with protocol number
getservbyname -- Get port number associated with an Internet service and protocol
getservbyport -- Get Internet service which corresponds to port and protocol
header -- Send a raw HTTP header
headers_list -- Returns a list of response headers sent (or ready to send)
headers_sent -- Checks if or where headers have been sent
inet_ntop -- Converts a packed internet address to a human readable representation
inet_pton -- Converts a human readable IP address to its packed in_addr representation
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
long2ip -- Converts an (IPv4) Internet network address into a string in Internet standard dotted format
openlog -- Open connection to system logger
pfsockopen -- Open persistent Internet or Unix domain socket connection
setcookie -- Send a cookie
setrawcookie -- Send a cookie without urlencoding the cookie value
socket_get_status -- Alias of stream_get_meta_data()
socket_set_blocking -- Alias of stream_set_blocking()
socket_set_timeout -- Alias of stream_set_timeout()
syslog -- Generate a system log message

Prev | Home | Next
ncurses_wvline | Up | checkdnsrr


checkdnsrr

(PHP 3, PHP 4, PHP 5)

checkdnsrr -- Check DNS records corresponding to a given Internet host name or IP address

Description

int checkdnsrr ( string host [, string type] )

Searches DNS for records of type type corresponding to host. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR or ANY. The default is MX.

host may either be the IP address in dotted-quad notation or the host name.

Note: AAAA type added with PHP 5.0.0

Note: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

See also dns_get_record(),
getmxrr(),
gethostbyaddr(),
gethostbyname(),
gethostbynamel(), and the named(8) manual
page.

Prev | Home | Next
Network Functions | Up | closelog


closelog

(PHP 3, PHP 4, PHP 5)

closelog -- Close connection to system logger

Description

bool closelog ( void )

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

See also define_syslog_variables(),
syslog() and
openlog().

Prev | Home | Next
checkdnsrr | Up | debugger_off


debugger_off

(PHP 3)

debugger_off -- Disable internal PHP debugger (PHP 3)

Description

int debugger_off ( void )

Disables the internal PHP debugger. This function is only available in PHP 3.

For more information see the appendix on Debugging PHP.

Prev | Home | Next
closelog | Up | debugger_on


debugger_on

(PHP 3)

debugger_on -- Enable internal PHP debugger (PHP 3)

Description

int debugger_on ( string address )

Enables the internal PHP debugger, connecting it to address. This function is only available in PHP 3.

For more information see the appendix on Debugging PHP.

Prev | Home | Next
debugger_off | Up | define_syslog_variables


define_syslog_variables

(PHP 3, PHP 4, PHP 5)

define_syslog_variables -- Initializes all syslog related constants

Description

void define_syslog_variables ( void )

Initializes all constants used in the syslog functions.

See also openlog(),
syslog() and
closelog().

Prev | Home | Next
debugger_on | Up | dns_check_record


dns_check_record

(PHP 5)

dns_check_record -- Synonym for checkdnsrr()

Description

bool dns_check_record ( string host [, string type] )

Check DNS records corresponding to a given Internet host name or IP address

Prev | Home | Next
define_syslog_variables | Up | dns_get_mx


dns_get_mx

(PHP 5)

dns_get_mx -- Synonym for getmxrr()

Description

bool dns_get_mx ( string hostname, array &mxhosts [, array &weight] )

Get MX records corresponding to a given Internet host name.

Prev | Home | Next
dns_check_record | Up | dns_get_record


dns_get_record

(PHP 5)

dns_get_record -- Fetch DNS Resource Records associated with a hostname

Description

array dns_get_record ( string hostname [, int type [, array &authns, array &addtl]] )

Note: This function is not implemented on Windows platforms, nor does it (currently) work on *BSD systems. Try the PEAR class Net_DNS.

This function returns an array of associative arrays. Each associative array contains at minimum the following keys:

Table 1. Basic DNS attributes

Attribute | Meaning
host | The record in the DNS namespace to which the rest of the associated data refers.
class | dns_get_record() only returns Internet class records and as such this parameter will always return IN.
type | String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below.
ttl | Time To Live remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.

hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY. The default is DNS_ANY.

Note: Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.

The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.

Table 2. Other keys in associative arrays dependant on 'type'

Type | Extra Columns
A | ip: An IPv4 addresses in dotted decimal notation.
MX | pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME | target: FQDN of location in DNS namespace to which the record is aliased.
NS | target: FQDN of the name server which is authoritative for this hostname.
PTR | target: Location within the DNS namespace to which this record points.
TXT | txt: Arbitrary string data associated with this record.
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's Operating System Names for the meaning of these values.
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA | ipv6: IPv6 address
A6(PHP >= 5.1.0) | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data.
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: RFC 2782
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by RFC 2915.

Note: Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().

Example 1. Using dns_get_record()

&#60;?php
$result = dns_get_record("php.net");
print_r($result);
?&#62;

Produces output similar to the following:

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.

Example 2. Using dns_get_record() and DNS_ANY

&#60;?php
/* Request "ANY" record for php.net,
   and create $authns and $addtl arrays
   containing list of name servers and
   any additional records which go with
   them */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?&#62;

Produces output similar to the following:

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)

See also dns_get_mx(), and dns_check_record()

Prev | Home | Next
dns_get_mx | Up | fsockopen


fsockopen

(PHP 3, PHP 4, PHP 5)

fsockopen -- Open Internet or Unix domain socket connection

Description

resource fsockopen ( string target [, int port [, int &errno [, string &errstr [, float timeout]]]] )

Initiates a socket connection to the resource specified by target. PHP supports targets in the Internet and Unix domains as described in Appendix O. A list of supported transports can also be retrieved using stream_get_transports().

Note: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

As of PHP 4.3.0, if you have compiled in OpenSSL support, you may prefix the hostname with either 'ssl://' or 'tls://' to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

fsockopen() returns a file pointer which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Example 1. fsockopen() Example

&#60;?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)&#60;br /&#62;\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?&#62;
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Example 2. Using UDP connection

&#60;?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr&#60;br /&#62;\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?&#62;

Warning

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1) you must enclose the IP in square brackets. For example, tcp://[fe80::1]:80.

Note: The timeout parameter was introduced in PHP 3.0.9 and UDP support was added in PHP 4.

See also pfsockopen(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.

Prev | Home | Next
dns_get_record | Up | gethostbyaddr


gethostbyaddr

(PHP 3, PHP 4, PHP 5)

gethostbyaddr -- Get the Internet host name corresponding to a given IP address

Description

string gethostbyaddr ( string ip_address )

Returns the host name of the Internet host specified by ip_address or a string containing the unmodified ip_address on failure.

Example 1. A simple gethostbyaddr() example

&#60;?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?&#62;

See Also

gethostbyname()
gethostbynamel()

Prev | Home | Next
fsockopen | Up | gethostbyname


gethostbyname

(PHP 3, PHP 4, PHP 5)

gethostbyname -- Get the IP address corresponding to a given Internet host name

Description

string gethostbyname ( string hostname )

Returns the IP address of the Internet host specified by hostname or a string containing the unmodified hostname on failure.

Example 1. A simple gethostbyname() example

&#60;?php
$ip = gethostbyname('www.example.com');

echo $ip;
?&#62;

See Also

gethostbyaddr()
gethostbynamel()

Prev | Home | Next
gethostbyaddr | Up | gethostbynamel


gethostbynamel

(PHP 3, PHP 4, PHP 5)

gethostbynamel -- Get a list of IP addresses corresponding to a given Internet host name

Description

array gethostbynamel ( string hostname )

Returns a list of IP addresses to which the Internet host specified by hostname resolves. Returns FALSE if hostname could not be resolved.

Example 1. gethostbynamel() example

&#60;?php
  $hosts = gethostbynamel('www.example.com');
  print_r($hosts);
?&#62;

The printout of the above program will be:

Array
(
    [0] => 192.0.34.166
)

See Also

gethostbyname()
gethostbyaddr()
checkdnsrr()
getmxrr()
the named(8) manual page

Prev | Home | Next
gethostbyname | Up | getmxrr


getmxrr

(PHP 3, PHP 4, PHP 5)

getmxrr -- Get MX records corresponding to a given Internet host name

Description

bool getmxrr ( string hostname, array &mxhosts [, array &weight] )

Searches DNS for MX records corresponding to hostname. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.

Note: This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to RFC 2821 when no mail exchangers are listed, hostname itself should be used as the only mail exchanger with a priority of 0.

Note: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

See also checkdnsrr(),
dns_get_record(),
gethostbyname(),
gethostbynamel(),
gethostbyaddr(), and the
named(8) manual page.

Prev | Home | Next
gethostbynamel | Up | getprotobyname


getprotobyname

(PHP 4, PHP 5)

getprotobyname -- Get protocol number associated with protocol name

Description

int getprotobyname ( string name )

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

Example 1. getprotobyname() example

&#60;?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot == -1) {
    // if nothing found, returns -1
    echo 'Invalid Protocol';
} else {
    echo 'Protocol #' . $get_prot;
}
?&#62;

See also: getprotobynumber().

Prev | Home | Next
getmxrr | Up | getprotobynumber


getprotobynumber

(PHP 4, PHP 5)

getprotobynumber -- Get protocol name associated with protocol number

Description

string getprotobynumber ( int number )

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

See also: getprotobyname().

Prev | Home | Next
getprotobyname | Up | getservbyname


getservbyname

(PHP 4, PHP 5)

getservbyname -- Get port number associated with an Internet service and protocol

Description

int getservbyname ( string service, string protocol )

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase). Returns FALSE if service or protocol is not found.

Example 1. getservbyname() example

&#60;?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
    $port = getservbyname($service, 'tcp');
    echo $service . ": " . $port . "&#60;br /&#62;\n";
}
?&#62;

For complete list of port numbers see: http://www.iana.org/assignments/port-numbers.

See also: getservbyport().

Prev | Home | Next
getprotobynumber | Up | getservbyport


getservbyport

(PHP 4, PHP 5)

getservbyport -- Get Internet service which corresponds to port and protocol

Description

string getservbyport ( int port, string protocol )

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase).

See also: getservbyname().

Prev | Home | Next
getservbyname | Up | header


inet_ntop

(PHP 5 >= 5.1.0RC1)

inet_ntop -- Converts a packed internet address to a human readable representation

Description

string inet_ntop ( string in_addr )

This function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation. Returns FALSE on failure.

Example 1. inet_ntop() Example

&#60;?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?&#62;

Note: This function is not implemented on Windows platforms.

See also long2ip(),
inet_pton(), and
ip2long().

Prev | Home | Next
headers_sent | Up | inet_pton


inet_pton

(PHP 5 >= 5.1.0RC1)

inet_pton -- Converts a human readable IP address to its packed in_addr representation

Description

string inet_pton ( string address )

This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.

Example 1. inet_pton() Example

&#60;?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');

?&#62;

Note: This function is not implemented on Windows platforms.

See also ip2long(),
inet_ntop(), and
long2ip().

Prev | Home | Next
inet_ntop | Up | ip2long


ip2long

(PHP 4, PHP 5)

ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

Description

int ip2long ( string ip_address )

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation. If ip_address is invalid then -1 is returned. Note that -1 does not evaluate as FALSE in PHP.

Note: As of PHP 5.0.0 ip2long() returns FALSE when ip_address is invalid.

Example 1. ip2long() Example

&#60;?php
$ip = gethostbyname('www.example.com');
$out = "The following URLs are equivalent:&#60;br /&#62;\n";
$out .= 'http://www.example.com/, http://' . $ip . '/, and http://' . sprintf("%u", ip2long($ip)) . "/&#60;br /&#62;\n";
echo $out;
?&#62;

Note: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

This second example shows how to print a converted address with the printf() function in both PHP 4 and PHP 5:

Example 2. Displaying an IP address

&#60;?php
$ip   = gethostbyname('www.example.com');
$long = ip2long($ip);

if ($long == -1 || $long === FALSE) {
    echo 'Invalid IP, please try again';
} else {
    echo $ip   . "\n";           // 192.0.34.166
    echo $long . "\n";           // -1073732954
    printf("%u\n", ip2long($ip)); // 3221234342
}
?&#62;

ip2long() should not be used as the sole form of IP validation. Combine it with long2ip():

Example 3. IP validation

&#60;?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip = long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); // "10.0.1.0"
?&#62;

ip2long() will also work with non-complete IP addresses. Read http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm for more info.

Note: ip2long() will return FALSE for the IP 255.255.255.255 in PHP 5 <= 5.0.2. It was fixed in PHP 5.0.3 where it returns -1 (same as PHP 4).

See also long2ip() and sprintf().

Prev | Home | Next
inet_pton | Up | long2ip


long2ip

(PHP 4, PHP 5)

long2ip -- Converts an (IPv4) Internet network address into a string in Internet standard dotted format

Description

string long2ip ( int proper_address )

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

See also: ip2long()

Prev | Home | Next
ip2long | Up | openlog


openlog

(PHP 3, PHP 4, PHP 5)

openlog -- Open connection to system logger

Description

bool openlog ( string ident, int option, int facility )

openlog() opens a connection to the system logger for a program. The string ident is added to each message. Values for option and facility are given below. The option argument is used to indicate what logging options will be used when generating a log message. The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled. The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

Table 1. openlog() Options

Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
You can use one or more of this options. When using multiple options you need to OR them, i.e. to open the connection immediately, write to the console and include the PID in each message, you will use: LOG_CONS | LOG_NDELAY | LOG_PID

Table 2. openlog() Facilities

Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

Note: LOG_USER is the only valid log type under Windows operating systems

See also define_syslog_variables(),
syslog() and
closelog().

Prev | Home | Next
long2ip | Up | pfsockopen


pfsockopen

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

pfsockopen -- Open persistent Internet or Unix domain socket connection

Description

resource pfsockopen ( string hostname [, int port [, int &errno [, string &errstr [, float timeout]]]] )

This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().

Prev | Home | Next
openlog | Up | setcookie


socket_get_status

(PHP 4, PHP 5)

socket_get_status -- Alias of stream_get_meta_data()

Description

This function is an alias of: stream_get_meta_data().

Prev | Home | Next
setrawcookie | Up | socket_set_blocking


socket_set_blocking

(PHP 4, PHP 5)

socket_set_blocking -- Alias of stream_set_blocking()

Description

This function is an alias of: stream_set_blocking().

Prev | Home | Next
socket_get_status | Up | socket_set_timeout


socket_set_timeout

(PHP 4, PHP 5)

socket_set_timeout -- Alias of stream_set_timeout()

Description

This function is an alias of: stream_set_timeout().

Prev | Home | Next
socket_set_blocking | Up | syslog


syslog

(PHP 3, PHP 4, PHP 5)

syslog -- Generate a system log message

Description

bool syslog ( int priority, string message )

syslog() generates a log message that will be distributed by the system logger. priority is a combination of the facility and the level, values for which are given in the next section. The remaining argument is the message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

Table 1. syslog() Priorities (in descending order)

Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

Example 1. Using syslog()

&#60;?php
define_syslog_variables();
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
}

closelog();
?&#62;
For information on setting up a user defined log handler, see the syslog.conf(5) Unix manual page. More information on the syslog facilities and option can be found in the man pages for syslog(3) on Unix machines.

On Windows NT, the syslog service is emulated using the Event Log.

Note: Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

See also define_syslog_variables(),
openlog() and
closelog().

Prev | Home | Next
socket_set_timeout | Up | Newt Functions


YP/NIS Functions

PHP Manual
Prev Next

CLXXXIV. YP/NIS Functions

Introduction

NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called Managing NFS and NIS by Hal Stern.

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

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).

Installation

To get these functions to work, you have to configure PHP with --enable-yp.

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.

YPERR_ACCESS (integer)

access violation (this has only been added recently and is only available from PECL CVS for now)

YPERR_BADARGS (integer)

The function arguments are bad

YPERR_BADDB (integer)

YP database is bad

YPERR_BUSY (integer)

Database busy

YPERR_DOMAIN (integer)

cannot bind to server in this domain

YPERR_KEY (integer)

no such key in map

YPERR_MAP (integer)

no such map in server's domain

YPERR_NODOM (integer)

Local domain name not set

YPERR_NOMORE (integer)

No more records in map database

YPERR_PMAP (integer)

Can't communicate with portmapper

YPERR_RESRC (integer)

resource allocation failure

YPERR_RPC (integer)

RPC failure - domain has been unbound

YPERR_YPBIND (integer)

Can't communicate with ypbind

YPERR_YPERR (integer)

internal yp server or client error

YPERR_YPSERV (integer)

Can't communicate with ypserv

YPERR_VERS (integer)

YP version mismatch

Table of Contents
yp_all -- Traverse the map and call a function on each entry
yp_cat -- Return an array containing the entire map
yp_err_string -- Returns the error string associated with the given error code
yp_errno -- Returns the error code of the previous operation
yp_first -- Returns the first key-value pair from the named map
yp_get_default_domain -- Fetches the machine's default NIS domain
yp_master -- Returns the machine name of the master NIS server for a map
yp_match -- Returns the matched line
yp_next -- Returns the next key-value pair in the named map
yp_order -- Returns the order number for a map

Prev | Home | Next
yaz_wait | Up | yp_all


yp_all

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_all -- Traverse the map and call a function on each entry

Description

void yp_all ( string domain, string map, string callback )

Warning

This function is currently not documented; only the argument list is available.

Parameters

domain

The NIS domain name.

map

The NIS map.

callback

Return Values

No value is returned.

Prev | Home | Next
YP/NIS Functions | Up | yp_cat


yp_cat

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_cat -- Return an array containing the entire map

Description

array yp_cat ( string domain, string map )

Returns all map entries.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Returns an array of all map entries, the maps key values as array indices and the maps entries as array data.

Prev | Home | Next
yp_all | Up | yp_err_string


yp_err_string

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_err_string -- Returns the error string associated with the given error code

Description

string yp_err_string ( int errorcode )

Returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Parameters

errorcode

The error code.

Return Values

Returns the error message, as a string.

Examples

Example 1. Example for NIS errors

&#60;?php
echo "Error: " . yp_err_string(yp_errno());
?&#62;

See Also

yp_errno()

Prev | Home | Next
yp_cat | Up | yp_errno


yp_errno

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_errno -- Returns the error code of the previous operation

Description

int yp_errno ( void )

Returns the error code of the previous operation.

Return Values

Returns one of the YPERR_XXX error constants.

See Also

yp_err_string()

Prev | Home | Next
yp_err_string | Up | yp_first


yp_first

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_first -- Returns the first key-value pair from the named map

Description

array yp_first ( string domain, string map )

Gets the first key-value pair from the named map in the named domain.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Returns the first key-value pair as an array on success, or FALSE on errors.

Examples

Example 1. Example for the NIS first

&#60;?php
$entry = yp_first($domain, "passwd.byname");

$key = key($entry);
$value = $entry[$key];

echo "First entry in this map has key " . $key . " and value " . $value;
?&#62;

See Also

yp_next()
yp_get_default_domain()

Prev | Home | Next
yp_errno | Up | yp_get_default_domain


yp_get_default_domain

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_get_default_domain -- Fetches the machine's default NIS domain

Description

string yp_get_default_domain ( void )

Returns the default domain of the node. Can be used as the domain parameter for successive NIS calls.

A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.

Return Values

Returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

Examples

Example 1. Example for the default domain

&#60;?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?&#62;

Prev | Home | Next
yp_first | Up | yp_master


yp_master

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_master -- Returns the machine name of the master NIS server for a map

Description

string yp_master ( string domain, string map )

Returns the machine name of the master NIS server for a map.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Examples

Example 1. Example for the NIS master

&#60;?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?&#62;

See Also

yp_get_default_domain()

Prev | Home | Next
yp_get_default_domain | Up | yp_match


yp_match

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_match -- Returns the matched line

Description

string yp_match ( string domain, string map, string key )

Returns the value associated with the passed key out of the specified map.

Parameters

domain

The NIS domain name.

map

The NIS map.

key

This key must be exact.

Return Values

Returns the value, or FALSE on errors.

Examples

Example 1. Example for NIS match

&#60;?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?&#62;

The above example will output something similar to:

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

See Also

yp_get_default_domain()

Prev | Home | Next
yp_master | Up | yp_next


yp_next

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_next -- Returns the next key-value pair in the named map

Description

array yp_next ( string domain, string map, string key )

Returns the next key-value pair in the named map after the specified key.

Parameters

domain

map

key

Return Values

Returns the next key-value pair as an array, or FALSE on errors.

Examples

Example 1. Example for NIS next

&#60;?php
$entry = yp_next($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    echo "&#60;!--" . yp_errno() . ": " . yp_err_string() . "--&#62;";
}

$key = key($entry);

echo "The next entry after joe has key " . $key
      . " and value " . $entry[$key];
?&#62;

See Also

yp_first()
yp_get_default_domain()

Prev | Home | Next
yp_match | Up | yp_order


yp_order

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_order -- Returns the order number for a map

Description

int yp_order ( string domain, string map )

Gets the order number for a map.

Parameters

domain

map

Return Values

Returns the order number for a map or FALSE on error.

Examples

Example 1. Example for the NIS order

&#60;?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?&#62;

See Also

yp_get_default_domain()

Prev | Home | Next
yp_next | Up | Zip File Functions


Lotus Notes Functions

PHP Manual
Prev Next

LXXV. Lotus Notes 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.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0. 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/notes.

Warning

This extension is currently not supported, thus looking for a maintainer.

Table of Contents
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db -- Copy a Lotus Notes database
notes_create_db -- Create a Lotus Notes database
notes_create_note -- Create a note using form form_name
notes_drop_db -- Drop a Lotus Notes database
notes_find_note -- Returns a note id found in database_name
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs -- Returns the notes from a selected database_name
notes_mark_read -- Mark a note_id as read for the User user_name
notes_mark_unread -- Mark a note_id as unread for the User user_name
notes_nav_create -- Create a navigator name, in database_name
notes_search -- Find notes that match keywords in database_name
notes_unread -- Returns the unread note id's for the current User user_name
notes_version -- Get the version Lotus Notes

Prev | Home | Next
libxml_use_internal_errors | Up | notes_body


notes_body

(PHP 4 >= 4.0.5, PECL)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number )

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.

Prev | Home | Next
Lotus Notes Functions | Up | notes_copy_db


notes_copy_db

(PHP 4 >= 4.0.5, PECL)

notes_copy_db -- Copy a Lotus Notes database

Description

bool notes_copy_db ( string from_database_name, string to_database_name )

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.

Prev | Home | Next
notes_body | Up | notes_create_db


notes_create_db

(PHP 4 >= 4.0.5, PECL)

notes_create_db -- Create a Lotus Notes database

Description

bool notes_create_db ( string database_name )

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.

Prev | Home | Next
notes_copy_db | Up | notes_create_note


notes_create_note

(PHP 4 >= 4.0.5, PECL)

notes_create_note -- Create a note using form form_name

Description

bool notes_create_note ( string database_name, string form_name )

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.

Prev | Home | Next
notes_create_db | Up | notes_drop_db


notes_drop_db

(PHP 4 >= 4.0.5, PECL)

notes_drop_db -- Drop a Lotus Notes database

Description

bool notes_drop_db ( string database_name )

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.

Prev | Home | Next
notes_create_note | Up | notes_find_note


notes_find_note

(PHP 4 >= 4.0.5, PECL)

notes_find_note -- Returns a note id found in database_name

Description

int notes_find_note ( string database_name, string name [, string type] )

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.

Prev | Home | Next
notes_drop_db | Up | notes_header_info


notes_header_info

(PHP 4 >= 4.0.5, PECL)

notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string server, string mailbox, int msg_number )

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.

Prev | Home | Next
notes_find_note | Up | notes_list_msgs


notes_list_msgs

(PHP 4 >= 4.0.5, PECL)

notes_list_msgs -- Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string db )

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.

Prev | Home | Next
notes_header_info | Up | notes_mark_read


notes_mark_read

(PHP 4 >= 4.0.5, PECL)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

bool notes_mark_read ( string database_name, string user_name, string note_id )

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.

Prev | Home | Next
notes_list_msgs | Up | notes_mark_unread


notes_mark_unread

(PHP 4 >= 4.0.5, PECL)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

bool notes_mark_unread ( string database_name, string user_name, string note_id )

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.

Prev | Home | Next
notes_mark_read | Up | notes_nav_create


notes_nav_create

(PHP 4 >= 4.0.5, PECL)

notes_nav_create -- Create a navigator name, in database_name

Description

bool notes_nav_create ( string database_name, string name )

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.

Prev | Home | Next
notes_mark_unread | Up | notes_search


notes_search

(PHP 4 >= 4.0.5, PECL)

notes_search -- Find notes that match keywords in database_name

Description

array notes_search ( string database_name, string keywords )

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.

Prev | Home | Next
notes_nav_create | Up | notes_unread


notes_unread

(PHP 4 >= 4.0.5, PECL)

notes_unread -- Returns the unread note id's for the current User user_name

Description

array notes_unread ( string database_name, string user_name )

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.

Prev | Home | Next
notes_search | Up | notes_version


notes_version

(PHP 4 >= 4.0.5, PECL)

notes_version -- Get the version Lotus Notes

Description

float notes_version ( string database_name )

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.

Prev | Home | Next
notes_unread | Up | LZF Functions


NSAPI-specific Functions

PHP Manual
Prev Next

CII. NSAPI-specific Functions

Introduction

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/Sun webservers.

Installation

For PHP installation on Netscape/iPlanet/Sun webservers see the NSAPI section (UNIX, Windows) in the installation chapter.

Runtime Configuration

The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf

Table 1. NSAPI configuration options

Name | Default | Changeable | Changelog
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

nsapi.read_timeout integer

Sets the time in seconds the plugin is waiting for POST data from the client.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

See Also

NSAPI implements a subset of the functions from the Apache module for maximum compatibility.

Table 2. Apache functions implemented by NSAPI

Apache function (only as alias) | NSAPI function | Description
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers
virtual() | nsapi_virtual() | Make NSAPI sub-request

Table of Contents
nsapi_request_headers -- Fetch all HTTP request headers
nsapi_response_headers -- Fetch all HTTP response headers
nsapi_virtual -- Perform an NSAPI sub-request

Prev | Home | Next
newt_win_ternary | Up | nsapi_request_headers


nsapi_request_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_request_headers -- Fetch all HTTP request headers

Description

array nsapi_request_headers ( void )

nsapi_request_headers() gets all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.

Note: Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.

Note: You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.

Return Values

Returns an associative array with all the HTTP headers.

Examples

Example 1. nsapi_request_headers() example

&#60;?php
$headers = nsapi_request_headers();

foreach ($headers as $header =&#62; $value) {
  echo "$header: $value &#60;br /&#62;\n";
}
?&#62;

Prev | Home | Next
NSAPI-specific Functions | Up | nsapi_response_headers


nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_response_headers -- Fetch all HTTP response headers

Description

array nsapi_response_headers ( void )

Gets all the NSAPI response headers.

Return Values

Returns an associative array with all the NSAPI response headers.

See Also

nsapi_request_headers()
headers_sent()

Prev | Home | Next
nsapi_request_headers | Up | nsapi_virtual


nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5)

nsapi_virtual -- Perform an NSAPI sub-request

Description

bool nsapi_virtual ( string uri )

nsapi_virtual() is an NSAPI-specific function which is equivalent to <!--#include virtual...--> in SSI (.shtml files). It does an NSAPI sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you'd parse through webserver.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

You cannot make recursive requests with this function to other PHP scripts. If you want to include PHP scripts, use include() or require().

Note: This function depends on a undocumented feature of the Netscape/iPlanet/Sun webservers. Use phpinfo() to determine if it is available. In the Unix environment it should always work, in windows it depends on the name of a ns-httpdXX.dll file.

Read the note about subrequests in the NSAPI section (UNIX, Windows) if you experience this problem.

Parameters

uri

The URI of the script.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
nsapi_response_headers | Up | Object Aggregation/Composition Functions


Object Aggregation/Composition Functions

PHP Manual
Prev Next

CIII. Object Aggregation/Composition 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

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Example 1. Class association

&#60;?php
class DateTime {

   function DateTime()
   {
       // empty constructor
   }

   function now()
   {
       return date("Y-m-d H:i:s");
   }
}

class Report {
   var $_dt;
   // more properties ...

   function Report()
   {
       $this-&#62;_dt = new DateTime();
       // initialization code ...
   }

   function generateReport()
   {
       $dateTime = $this-&#62;_dt-&#62;now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
?&#62;
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Example 2. Object association

&#60;?php
class DateTime {
   // same as previous example
}

class DateTimePlus {
   var $_format;

   function DateTimePlus($format="Y-m-d H:i:s")
   {
       $this-&#62;_format = $format;
   }

   function now()
   {
       return date($this-&#62;_format);
   }
}

class Report {
   var $_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   function Report()
   {
       // do some initialization
   }

   function setDateTime(&#38;$dt)
   {
       $this-&#62;_dt =&#38; $dt;
   }

   function generateReport()
   {
       $dateTime = $this-&#62;_dt-&#62;now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep-&#62;setDateTime(&#38;$dt);
echo $rep-&#62;generateReport();

// later on in the code ...

// generate report with fancy date
$rep-&#62;setDateTime(&#38;$dtp);
$output = $rep-&#62;generateReport();
// save $output in database
// ... etc ...
?&#62;

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.

Examples

We define 3 classes, each implementing a different storage method:

Example 3. storage_classes.inc

&#60;?php
class FileStorage {
    var $data;

    function FileStorage($data)
    {
        $this-&#62;data = $data;
    }

    function write($name)
    {
        $fp = fopen(name, "w");
        fwrite($fp, $this-&#62;data);
        fclose($data);
    }
}

class WDDXStorage {
    var $data;
    var $version = "1.0";
    var $_id; // "private" variable

    function WDDXStorage($data)
    {
        $this-&#62;data = $data;
        $this-&#62;_id = $this-&#62;_genID();
    }

    function store()
    {
        if ($this-&#62;_id) {
            $pid = wddx_packet_start($this-&#62;_id);
            wddx_add_vars($pid, "this-&#62;data");
            $packet = wddx_packet_end($pid);
        } else {
            $packet = wddx_serialize_value($this-&#62;data);
        }
        $dbh = dba_open("varstore", "w", "gdbm");
        dba_insert(md5(uniqid("", true)), $packet, $dbh);
        dba_close($dbh);
    }

    // a private method
    function _genID()
    {
        return md5(uniqid(rand(), true));
    }
}

class DBStorage {
    var $data;
    var $dbtype = "mysql";

    function DBStorage($data)
    {
        $this-&#62;data = $data;
    }

    function save()
    {
        $dbh = mysql_connect();
        mysql_select_db("storage", $dbh);
        $serdata = serialize($this-&#62;data);
        mysql_query("insert into vars ('$serdata',now())", $dbh);
        mysql_close($dbh);
    }
}

?&#62;

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Example 4. test_aggregation.php

&#60;?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr)
{
    foreach ($arr as $k =&#62; $v)
        $out[] = "\t$k =&#62; $v";
    return implode("\n", $out);
}

function object_info($obj)
{
    $out[] = "Class: " . get_class($obj);
    foreach (get_object_vars($obj) as $var=&#62;$val) {
        if (is_array($val)) {
            $out[] = "property: $var (array)\n" . p_arr($val);
        } else {
            $out[] = "property: $var = $val";
        }
    }
    foreach (get_class_methods($obj) as $method) {
        $out[] = "method: $method";
    }
    return implode("\n", $out);
}

$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs) . "\n";
echo "\n\$ws object\n";
echo object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

?&#62;

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The process of aggregation is cumulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

Table of Contents
aggregate_info -- Returns an associative array of the methods and properties from each class that has been aggregated to the object
aggregate_methods_by_list -- Selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp -- Selective class methods aggregation to an object using a regular expression
aggregate_methods -- Dynamic class and object aggregation of methods
aggregate_properties_by_list -- Selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp -- Selective class properties aggregation to an object using a regular expression
aggregate_properties -- Dynamic aggregation of class properties to an object
aggregate -- Dynamic class and object aggregation of methods and properties
aggregation_info -- Alias of aggregate_info()
deaggregate -- Removes the aggregated methods and properties from an object

Prev | Home | Next
nsapi_virtual | Up | aggregate_info


aggregate_info

(no version information, might be only in CVS)

aggregate_info -- Returns an associative array of the methods and properties from each class that has been aggregated to the object

Description

array aggregate_info ( object object )

Will return the aggregation information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

For example the code below

Example 1. Using aggregate_info()

&#60;?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable)
    {
        $this-&#62;vegetable = $vegetable;
    }

    function slice_it($num_cuts)
    {
        echo "Doing some simple slicing\n";
        for ($i=0; $i &#60; $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable)
    {
        $this-&#62;vegetable = $vegetable;
    }

    function dice_it($num_cuts)
    {
        echo "Cutting in one direction\n";
        for ($i=0; $i &#60; $num_cuts; $i++) {
            // do some cutting
        }
        $this-&#62;rotate($this-&#62;rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i &#60; $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg)
    {
        echo "Now rotating {$this-&#62;vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts)
    {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?&#62;

Will produce the output

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)
As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

Prev | Home | Next
Object Aggregation/Composition Functions | Up | aggregate_methods_by_list


aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list -- Selective dynamic class methods aggregation to an object

Description

void aggregate_methods_by_list ( object object, string class_name, array methods_list [, bool exclude] )

Aggregates methods from a class to an existing object using a list of method names. The optional parameter exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

Prev | Home | Next
aggregate_info | Up | aggregate_methods_by_regexp


aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp -- Selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, bool exclude] )

Aggregates methods from a class to an existing object using a regular expression to match method names. The optional parameter exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

Prev | Home | Next
aggregate_methods_by_list | Up | aggregate_methods


aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods -- Dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name )

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also
aggregate(),
aggregate_info(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

Prev | Home | Next
aggregate_methods_by_regexp | Up | aggregate_properties_by_list


aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list -- Selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, bool exclude] )

Aggregates properties from a class to an existing object using a list of property names. The optional parameter exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_regexp(),
aggregate_info(),
deaggregate()

Prev | Home | Next
aggregate_methods | Up | aggregate_properties_by_regexp


aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp -- Selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, bool exclude] )

Aggregates properties from a class to an existing object using a regular expression to match their names. The optional parameter exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_info(),
deaggregate()

Prev | Home | Next
aggregate_properties_by_list | Up | aggregate_properties


aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties -- Dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name )

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
aggregate_info(),
deaggregate()

Prev | Home | Next
aggregate_properties_by_regexp | Up | aggregate


aggregate

(PHP 4 >= 4.2.0)

aggregate -- Dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name )

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

Prev | Home | Next
aggregate_properties | Up | aggregation_info


aggregation_info

(PHP 4 >= 4.2.0)

aggregation_info -- Alias of aggregate_info()

Description

This function is an alias of: aggregate_info().

Prev | Home | Next
aggregate | Up | deaggregate


deaggregate

(PHP 4 >= 4.2.0)

deaggregate -- Removes the aggregated methods and properties from an object

Description

void deaggregate ( object object [, string class_name] )

Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
aggregate_info()

Prev | Home | Next
aggregation_info | Up | Object property and method call overloading


Oracle Functions

PHP Manual
Prev Next

CV. Oracle Functions

Introduction

These functions allow you to access Oracle 10, Oracle 9, Oracle 8 and Oracle 7 databases using the Oracle Call Interface (OCI). They support binding of PHP variables to Oracle placeholders, have full LOB, FILE and ROWID support, and allow you to use user-supplied define variables.

Requirements

You will need the Oracle client libraries to use this extension. Windows users will need libraries with version at least 10 to use the php_oci8.dll.

The most convenient way to install all the required files is to use Oracle Instant Client, which is available from here: http://www.oracle.com/technology/tech/oci/instantclient/instantclient.html. To work with OCI8 module "basic" version of Oracle Instant Client is enough. Instant Client does not need ORACLE_SID or ORACLE_HOME environment variables set. You still may need to set LD_LIBRARY_PATH and NLS_LANG, though.

Before using this extension, make sure that you have set up your Oracle environment variables properly for the Oracle user, as well as your web daemon user. These variables should be set up before you start your web-server. The variables you might need to set are as follows:

  • ORACLE_HOME

  • ORACLE_SID

  • LD_PRELOAD

  • LD_LIBRARY_PATH

  • NLS_LANG

For less frequently used Oracle environment variables such as TNS_ADMIN, TWO_TASK, ORA_TZFILE, and the various Oracle globalization settings like ORA_NLS33, ORA_NLS10 and the NLS_* variables refer to Oracle documentation.

After setting up the environment variables for your webserver user, be sure to also add the webserver user (nobody, www) to the oracle group.

If your webserver doesn't start or crashes at startup: Check that Apache is linked with the pthread library:

# ldd /www/apache/bin/httpd
    libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
    libm.so.6 => /lib/libm.so.6 (0x4002f000)
    libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
    libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
    libc.so.6 => /lib/libc.so.6 (0x4007e000)
    /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

If the libpthread is not listed you have to reinstall Apache:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Please note that on some systems, like UnixWare it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. OCI8 Configuration Options

Name | Default | Changeable | Changelog
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.

Here's a short explanation of the configuration directives.

oci8.privileged_connect boolean

This option enables privileged connections using external credentials (OCI_SYSOPER, OCI_SYSDBA).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per process. Setting this option to -1 means that there is no limit.

oci8.persistent_timeout int

The maximum length of time (in seconds) that a given process is allowed to maintain an idle persistent connection. Setting this option to -1 means that idle persistent connections will be maintained forever.

oci8.ping_interval int

The length of time (in seconds) that must pass before issuing a ping during oci_pconnect(). When set to 0, persistent connections will be pinged every time they are reused. To disable pings completely, set this option to -1.

Note: Disabling pings will cause oci_pconnect() calls to operate at the highest efficiency, but may cause PHP to not detect faulty connections, such as those caused by network partitions, or if the Oracle server has gone down since PHP connected, until later in the script. Consult the oci_pconnect() documentation for more information.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Note: A larger cache can result in improved performance, at the cost of increased memory usage.

oci8.default_prefetch int

This option enables statement prefetching and sets the default number of rows that will be fetched automatically after statement execution.

Note: A larger prefetch can result in improved performance, at the cost of increased memory usage.

oci8.old_oci_close_semantics boolean

This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to remove the oci_close() calls from your application instead of enabling this option.

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.

OCI_DEFAULT (integer)

Statement execution mode. Statement is not committed automatically when using this mode.

OCI_DESCRIBE_ONLY (integer)

Statement execution mode. Use this mode if you don't want to execute the query, but get the select-list's description.

OCI_COMMIT_ON_SUCCESS (integer)

Statement execution mode. Statement is automatically committed after oci_execute() call.

OCI_EXACT_FETCH (integer)

Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. Cursor is cancelled after the desired rows are fetched and may result in reduced server-side resource usage.

OCI_SYSDATE (integer)

OCI_B_BFILE (integer)

Used with oci_bind_by_name() when binding BFILEs.

OCI_B_CFILEE (integer)

Used with oci_bind_by_name() when binding CFILEs.

OCI_B_CLOB (integer)

Used with oci_bind_by_name() when binding CLOBs.

OCI_B_BLOB (integer)

Used with oci_bind_by_name() when binding BLOBs.

OCI_B_ROWID (integer)

Used with oci_bind_by_name() when binding ROWIDs.

OCI_B_CURSOR (integer)

Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().

OCI_B_NTY (integer)

Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.

OCI_B_BIN (integer)

SQLT_BFILEE (integer)

The same as OCI_B_BFILE.

SQLT_CFILEE (integer)

The same as OCI_B_CFILEE.

SQLT_CLOB (integer)

The same as OCI_B_CLOB.

SQLT_BLOB (integer)

The same as OCI_B_BLOB.

SQLT_RDD (integer)

The same as OCI_B_ROWID.

SQLT_NTY (integer)

The same as OCI_B_NTY.

SQLT_LNG (integer)

Used with oci_bind_by_name() to bind LONG values.

SQLT_LBI (integer)

Used with oci_bind_by_name() to bind LONG RAW values.

SQLT_BIN (integer)

Used with oci_bind_by_name() to bind RAW values.

SQLT_NUM (integer)

Used with oci_bind_array_by_name() to bind arrays of NUMBER.

SQLT_INT (integer)

Used with oci_bind_array_by_name() to bind arrays of INTEGER.

SQLT_AFC (integer)

Used with oci_bind_array_by_name() to bind arrays of CHAR.

SQLT_CHR (integer)

Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().

SQLT_VCS (integer)

Used with oci_bind_array_by_name() to bind arrays of VARCHAR.

SQLT_AVC (integer)

Used with oci_bind_array_by_name() to bind arrays of CHARZ.

SQLT_STR (integer)

Used with oci_bind_array_by_name() to bind arrays of STRING.

SQLT_LVC (integer)

Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.

SQLT_FLT (integer)

Used with oci_bind_array_by_name() to bind arrays of FLOAT.

SQLT_ODT (integer)

Used with oci_bind_array_by_name() to bind arrays of LONG.

SQLT_BDOUBLE (integer)

SQLT_BFLOAT (integer)

OCI_FETCHSTATEMENT_BY_COLUMN (integer)

Default mode of oci_fetch_all().

OCI_FETCHSTATEMENT_BY_ROW (integer)

Alternative mode of oci_fetch_all().

OCI_ASSOC (integer)

Used with oci_fetch_all() and oci_fetch_array() to get an associative array as a result.

OCI_NUM (integer)

Used with oci_fetch_all() and oci_fetch_array() to get an enumerated array as a result.

OCI_BOTH (integer)

Used with oci_fetch_all() and oci_fetch_array() to get an array with both associative and number indices.

OCI_RETURN_NULLS (integer)

Used with oci_fetch_array() to get empty array elements if field's value is NULL.

OCI_RETURN_LOBS (integer)

Used with oci_fetch_array() to get value of LOB instead of the descriptor.

OCI_DTYPE_FILE (integer)

This flag tells oci_new_descriptor() to initialize new FILE descriptor.

OCI_DTYPE_LOB (integer)

This flag tells oci_new_descriptor() to initialize new LOB descriptor.

OCI_DTYPE_ROWID (integer)

This flag tells oci_new_descriptor() to initialize new ROWID descriptor.

OCI_D_FILE (integer)

The same as OCI_DTYPE_FILE.

OCI_D_LOB (integer)

The same as OCI_DTYPE_LOB.

OCI_D_ROWID (integer)

The same as OCI_DTYPE_ROWID.

OCI_SYSOPER (integer)

Used with oci_connect() to connect as SYSOPER using external credentials (oci8.privileged_connect should be enabled for this).

OCI_SYSDBA (integer)

Used with oci_connect() to connect as SYSDBA using external credentials (oci8.privileged_connect should be enabled for this).

OCI_LOB_BUFFER_FREE (integer)

Used with OCI-Lob->flush to free buffers used.

OCI_TEMP_CLOB (integer)

Used with OCI-Lob->writeTemporary to indicate explicilty that temporary CLOB should be created.

OCI_TEMP_BLOB (integer)

Used with OCI-Lob->writeTemporary to indicate explicilty that temporary BLOB should be created.

Examples

Example 1. Basic query

&#60;?php

  $conn = oci_connect('hr', 'hr', 'orcl');
  if (!$conn) {
    $e = oci_error();
    print htmlentities($e['message']);
    exit;
  }

  $query = 'SELECT * FROM DEPARTMENTS';

  $stid = oci_parse($conn, $query);
  if (!$stid) {
    $e = oci_error($conn);
    print htmlentities($e['message']);
    exit;
  }

  $r = oci_execute($stid, OCI_DEFAULT);
  if (!$r) {
    $e = oci_error($stid);
    echo htmlentities($e['message']);
    exit;
  }

  print '&#60;table border="1"&#62;';
  while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) {
    print '&#60;tr&#62;';
       foreach ($row as $item) {
         print '&#60;td&#62;'.($item?htmlentities($item):'&#38;nbsp;').'&#60;/td&#62;';
       }
       print '&#60;/tr&#62;';
  }
  print '&#60;/table&#62;';

  oci_close($conn);
?&#62;

Example 2. Insert with bind variables

&#60;?php

  // Before running, create the table:
  //   CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

  $conn = oci_connect('scott', 'tiger', 'orcl');

  $query = 'INSERT INTO MYTABLE VALUES(:myid, :mydata)';

  $stid = oci_parse($conn, $query);

  $id = 60;
  $data = 'Some data';

  oci_bind_by_name($stid, ':myid', $id);
  oci_bind_by_name($stid, ':mydata', $data);

  $r = oci_execute($stid);

  if ($r)
    print "One row inserted";

  oci_close($conn);

?&#62;

Example 3. Inserting data into a CLOB column

&#60;?php

// Before running, create the table:
//     CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn = oci_connect('scott', 'tiger', 'orcl');

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytable (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob-&#62;save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid, OCI_DEFAULT);

print '&#60;table border="1"&#62;';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
  $result = $row['MYCLOB']-&#62;load();
  print '&#60;tr&#62;&#60;td&#62;'.$result.'&#60;/td&#62;&#60;/tr&#62;';
}
print '&#60;/table&#62;';

?&#62;

You can easily access stored procedures in the same way as you would from the command line.

Example 4. Using Stored Procedures

&#60;?php
// by webmaster at remoterealty dot com
$sth = oci_parse($dbh, "begin sp_newaddress( :address_id, '$firstname',
 '$lastname', '$company', '$address1', '$address2', '$city', '$state',
 '$postalcode', '$country', :error_code );end;");

// This calls stored procedure sp_newaddress, with :address_id being an
// in/out variable and :error_code being an out variable.
// Then you do the binding:

   oci_bind_by_name($sth, ":address_id", $addr_id, 10);
   oci_bind_by_name($sth, ":error_code", $errorcode, 10);
   oci_execute($sth);

?&#62;

Connecting Handling

The oci8 extension provides you with 3 different functions for connecting to Oracle. It is up to you to use the most appropriate function for your application, and the information in this section is intended to help you make an informed choice.

Connecting to an Oracle server is a reasonably expensive operation, in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that you will typically only incur the connection overhead once per php process (or apache child).

If your application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of your Oracle server due to maintaining too many idle connections. If your application is structured in this way, it is recommended that you either tune your application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give you control over the persistent connection cache size and lifetime) or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if you make multiple calls to oci_connect(), using the same parameters, in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when you explicitly close the connection handle. oci_pconnect() has similar behaviour, although its cache is maintained separately and survives between requests.

This caching feature is important to remember, because it gives the appearance that the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If your application needs two separate, transactionally isolated connections, you should use oci_new_connect().

oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should try to avoid using oci_new_connect(), especially in the busiest sections of the application.

Datatypes supported by the driver

Table 2. The driver supports the following types when binding parameters using oci_bind_by_name() function:

Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.

Table 3. The following types are supported when retrieving columns from a result set:

Type | Mapping
SQLT_RSET | Creates an oci statement resource to represent the the cursor.
SQLT_RDD | Creates a ROWID object.
SQLT_BLOB | Creates a LOB object.
SQLT_CLOB | Creates a LOB object.
SQLT_BFILE | Creates a LOB object.
SQLT_LNG | Bound as SQLT_CHR, returned as a string
SQLT_LBI | Bound as SQLT_BIN, returned as a string
Any other type | Bound as SQLT_CHR, returned as a string
Table of Contents
oci_bind_array_by_name -- Binds PHP array to Oracle PL/SQL array by name
oci_bind_by_name -- Binds the PHP variable to the Oracle placeholder
oci_cancel -- Cancels reading from cursor
oci_close -- Closes Oracle connection
OCI-Collection->append -- Appends element to the collection
OCI-Collection->assign -- Assigns a value to the collection from another existing collection
OCI-Collection->assignElem -- Assigns a value to the element of the collection
OCI-Collection->free -- Frees the resources associated with the collection object
OCI-Collection->getElem -- Returns value of the element
OCI-Collection->max -- Returns the maximum number of elements in the collection
OCI-Collection->size -- Returns size of the collection
OCI-Collection->trim -- Trims elements from the end of the collection
oci_commit -- Commits outstanding statements
oci_connect -- Establishes a connection to the Oracle server
oci_define_by_name -- Uses a PHP variable for the define-step during a SELECT
oci_error -- Returns the last error found
oci_execute -- Executes a statement
oci_fetch_all -- Fetches all rows of result data into an array
oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or both
oci_fetch_assoc -- Returns the next row from the result data as an associative array
oci_fetch_object -- Returns the next row from the result data as an object
oci_fetch_row -- Returns the next row from the result data as a numeric array
oci_fetch -- Fetches the next row into result-buffer
oci_field_is_null -- Checks if the field is NULL
oci_field_name -- Returns the name of a field from the statement
oci_field_precision -- Tell the precision of a field
oci_field_scale -- Tell the scale of the field
oci_field_size -- Returns field's size
oci_field_type_raw -- Tell the raw Oracle data type of the field
oci_field_type -- Returns field's data type
oci_free_statement -- Frees all resources associated with statement or cursor
oci_internal_debug -- Enables or disables internal debug output
OCI-Lob->append -- Appends data from the large object to another large object
OCI-Lob->close -- Closes LOB descriptor
oci_lob_copy -- Copies large object
OCI-Lob->eof -- Tests for end-of-file on a large object's descriptor
OCI-Lob->erase -- Erases a specified portion of the internal LOB data
OCI-Lob->export -- Exports LOB's contents to a file
OCI-Lob->flush -- Flushes/writes buffer of the LOB to the server
OCI-Lob->free -- Frees resources associated with the LOB descriptor
OCI-Lob->getBuffering -- Returns current state of buffering for the large object
OCI-Lob->import -- Imports file data to the LOB
oci_lob_is_equal -- Compares two LOB/FILE locators for equality
OCI-Lob->load -- Returns large object's contents
OCI-Lob->read -- Reads part of the large object
OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large object
OCI-Lob->save -- Saves data to the large object
OCI-Lob->saveFile -- Alias of oci_lob_import()
OCI-Lob->seek -- Sets the internal pointer of the large object
OCI-Lob->setBuffering -- Changes current state of buffering for the large object
OCI-Lob->size -- Returns size of large object
OCI-Lob->tell -- Returns current position of internal pointer of large object
OCI-Lob->truncate -- Truncates large object
OCI-Lob->write -- Writes data to the large object
OCI-Lob->writeTemporary -- Writes temporary large object
OCI-Lob->writeToFile -- Alias of oci_lob_export()
oci_new_collection -- Allocates new collection object
oci_new_connect -- Establishes a new connection to the Oracle server
oci_new_cursor -- Allocates and returns a new cursor (statement handle)
oci_new_descriptor -- Initializes a new empty LOB or FILE descriptor
oci_num_fields -- Returns the number of result columns in a statement
oci_num_rows -- Returns number of rows affected during statement execution
oci_parse -- Prepares Oracle statement for execution
oci_password_change -- Changes password of Oracle's user
oci_pconnect -- Connect to an Oracle database using a persistent connection
oci_result -- Returns field's value from the fetched row
oci_rollback -- Rolls back outstanding transaction
oci_server_version -- Returns server version
oci_set_prefetch -- Sets number of rows to be prefetched
oci_statement_type -- Returns the type of an OCI statement
ocibindbyname -- Alias of oci_bind_by_name()
ocicancel -- Alias of oci_cancel()
ocicloselob -- Alias of OCI-Lob->close
ocicollappend -- Alias of OCI-Collection->append
ocicollassign -- Alias of OCI-Collection->assign
ocicollassignelem -- Alias of OCI-Collection->assignElem
ocicollgetelem -- Alias of OCI-Collection->getElem
ocicollmax -- Alias of OCI-Collection->max
ocicollsize -- Alias of OCI-Collection->size
ocicolltrim -- Alias of OCI-Collection->trim
ocicolumnisnull -- Alias of oci_field_is_null()
ocicolumnname -- Alias of oci_field_name()
ocicolumnprecision -- Alias of oci_field_precision()
ocicolumnscale -- Alias of oci_field_scale()
ocicolumnsize -- Alias of oci_field_size()
ocicolumntype -- Alias of oci_field_type()
ocicolumntyperaw -- Alias of oci_field_type_raw()
ocicommit -- Alias of oci_commit()
ocidefinebyname -- Alias of oci_define_by_name()
ocierror -- Alias of oci_error()
ociexecute -- Alias of oci_execute()
ocifetch -- Alias of oci_fetch()
ocifetchinto -- Fetches the next row into an array (deprecated)
ocifetchstatement -- Alias of oci_fetch_all()
ocifreecollection -- Alias of OCI-Collection->free
ocifreecursor -- Alias of oci_free_statement()
ocifreedesc -- Alias of OCI-Lob->free
ocifreestatement -- Alias of oci_free_statement()
ociinternaldebug -- Alias of oci_internal_debug()
ociloadlob -- Alias of OCI-Lob->load
ocilogoff -- Alias of oci_close()
ocilogon -- Alias of oci_connect()
ocinewcollection -- Alias of oci_new_collection()
ocinewcursor -- Alias of oci_new_cursor()
ocinewdescriptor -- Alias of oci_new_descriptor()
ocinlogon -- Alias of oci_new_connect()
ocinumcols -- Alias of oci_num_fields()
ociparse -- Alias of oci_parse()
ociplogon -- Alias of oci_pconnect()
ociresult -- Alias of oci_result()
ocirollback -- Alias of oci_rollback()
ocirowcount -- Alias of oci_num_rows()
ocisavelob -- Alias of OCI-Lob->save
ocisavelobfile -- Alias of OCI-Lob->import
ociserverversion -- Alias of oci_server_version()
ocisetprefetch -- Alias of oci_set_prefetch()
ocistatementtype -- Alias of oci_statement_type()
ociwritelobtofile -- Alias of OCI-Lob->export
ociwritetemporarylob -- Alias of OCI-Lob->writeTemporary

Prev | Home | Next
overload | Up | oci_bind_array_by_name


oci_bind_by_name

(PHP 5)

oci_bind_by_name -- Binds the PHP variable to the Oracle placeholder

Description

bool oci_bind_by_name ( resource statement, string ph_name, mixed &variable [, int maxlength [, int type]] )

Binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined at run-time and the necessary storage space will be allocated.

Parameters

statement

An OCI statement.

ph_name

The placeholder.

variable

The PHP variable.

maxlength

Sets the maximum length for the bind. If you set it to -1, this function will use the current length of variable to set the maximum length.

type

If you need to bind an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using the oci_new_descriptor() function. The length is not used for abstract datatypes and should be set to -1. The type parameter tells Oracle which descriptor is used. Possible values are:

  • SQLT_FILE - for BFILEs;

  • SQLT_CFILE - for CFILEs;

  • SQLT_CLOB - for CLOBs;

  • SQLT_BLOB - for BLOBs;

  • SQLT_RDD - for ROWIDs;

  • SQLT_NTY - for named datatypes;

  • SQLT_INT - for integers;

  • SQLT_CHR - for VARCHARs;

  • SQLT_BIN - for RAW columns;

  • SQLT_LNG - for LONG columns;

  • SQLT_LBI - for LONG RAW columns;

  • SQLT_RSET - for cursors, that were created before with oci_new_cursor().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. oci_bind_by_name()example

&#60;?php
/* oci_bind_by_name example thies at thieso dot net (980221)
  inserts 3 records into emp, and uses the ROWID for updating the
  records just after the insert.
*/

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "
                          INSERT INTO
                                     emp (empno, ename)
                                              VALUES
                                     (:empno,:ename)
                            RETURNING
                                     ROWID
                                 INTO
                                     :rid
                                         ");

$data = array(
              1111 =&#62; "Larry",
              2222 =&#62; "Bill",
              3333 =&#62; "Jim"
             );

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);

oci_bind_by_name($stmt, ":empno", $empno, 32);
oci_bind_by_name($stmt, ":ename", $ename, 32);
oci_bind_by_name($stmt, ":rid",   $rowid, -1, OCI_B_ROWID);

$update = oci_parse($conn, "
                            UPDATE
                                  emp
                               SET
                                  sal = :sal
                             WHERE
                                  ROWID = :rid
                             ");
oci_bind_by_name($update, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($update, ":sal", $sal,   32);

$sal = 10000;

foreach ($data as $empno =&#62; $ename) {
    oci_execute($stmt);
    oci_execute($update);
}

$rowid-&#62;free();

oci_free_statement($update);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "
                          SELECT
                                *
                            FROM
                                emp
                           WHERE
                                empno
                              IN
                                (1111,2222,3333)
                              ");
oci_execute($stmt);

while ($row = oci_fetch_assoc($stmt)) {
    var_dump($row);
}

oci_free_statement($stmt);

/* delete our "junk" from the emp table.... */
$stmt = oci_parse($conn, "
                          DELETE FROM
                                     emp
                                WHERE
                                     empno
                                   IN
                                     (1111,2222,3333)
                                   ");
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?&#62;

Remember, this function strips trailing whitespaces. See the following example:

Example 2. oci_bind_by_name() example

&#60;?php
    $connection = oci_connect('apelsin','kanistra');
    $query = "INSERT INTO test_table VALUES(:id, :text)";

    $statement = oci_parse($query);
    oci_bind_by_name($statement, ":id", 1);
    oci_bind_by_name($statement, ":text", "trailing spaces follow     ");
    oci_execute($statement);
    /*
     This code will insert into DB string 'trailing spaces follow', without
     trailing spaces
    */
?&#62;

Example 3. oci_bind_by_name() example

&#60;?php
    $connection = oci_connect('apelsin','kanistra');
    $query = "INSERT INTO test_table VALUES(:id, 'trailing spaces follow      ')";

    $statement = oci_parse($query);
    oci_bind_by_name($statement, ":id", 1);
    oci_execute($statement);
    /*
     And this code will add 'trailing spaces follow      ', preserving
     trailing whitespaces
    */
?&#62;

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name() simultaneously as no quoting is needed and any magically applied quotes will be written into your database as oci_bind_by_name() is not able to distinguish magically added quotings from those added intentionally.

Note: In PHP versions before 5.0.0 you must use ocibindbyname() instead. This name still can be used, it was left as alias of oci_bind_by_name() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_bind_array_by_name | Up | oci_cancel


oci_cancel

(PHP 5)

oci_cancel -- Cancels reading from cursor

Description

bool oci_cancel ( resource statement )

Invalidates a cursor, freeing all associated resources and cancels the ability to read from it.

Parameters

statement

An OCI statement.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
oci_bind_by_name | Up | oci_close


oci_close

(PHP 5)

oci_close -- Closes Oracle connection

Description

bool oci_close ( resource connection )

Closes the Oracle connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Starting from the version 1.1 oci_close() correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behaviour of this function.

Prev | Home | Next
oci_cancel | Up | OCI-Collection->append


OCI-Collection->append

(no version information, might be only in CVS)

OCI-Collection->append -- Appends element to the collection

Description

class OCI-Collection {

bool append ( mixed value )

}

Appends element to the end of the collection.

Parameters

value

The value to be added to the collection. Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Collection->assign

Prev | Home | Next
oci_close | Up | OCI-Collection->assign


OCI-Collection->assign

(no version information, might be only in CVS)

OCI-Collection->assign -- Assigns a value to the collection from another existing collection

Description

class OCI-Collection {

bool assign ( OCI-Collection from )

}

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

Parameters

from

An instance of OCI-Collection.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Collection->append

Prev | Home | Next
OCI-Collection->append | Up | OCI-Collection->assignElem


OCI-Collection->free

(no version information, might be only in CVS)

OCI-Collection->free -- Frees the resources associated with the collection object

Description

class OCI-Collection {

bool free ( void )

}

Frees the resources associated with the collection object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

oci_new_collection

Prev | Home | Next
OCI-Collection->assignElem | Up | OCI-Collection->getElem


OCI-Collection->max

(no version information, might be only in CVS)

OCI-Collection->max -- Returns the maximum number of elements in the collection

Description

class OCI-Collection {

int max ( void )

}

Returns the maximum number of elements in the collection.

Return Values

Returns the maximum number as an integer, or FALSE on errors.

If the returned value is 0, then the number of elements is not limited.

See Also

OCI-Collection->size

Prev | Home | Next
OCI-Collection->getElem | Up | OCI-Collection->size


OCI-Collection->size

(no version information, might be only in CVS)

OCI-Collection->size -- Returns size of the collection

Description

class OCI-Collection {

int size ( void )

}

Returns the size of the collection.

Return Values

Returns the number of elements in the collection or FALSE on error.

See Also

OCI-Collection->max

Prev | Home | Next
OCI-Collection->max | Up | OCI-Collection->trim


OCI-Collection->trim

(no version information, might be only in CVS)

OCI-Collection->trim -- Trims elements from the end of the collection

Description

class OCI-Collection {

bool trim ( int num )

}

Trims num of elements from the end of the collection.

Parameters

num

The number of elements to be trimmed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Collection->size

Prev | Home | Next
OCI-Collection->size | Up | oci_commit


oci_commit

(PHP 5)

oci_commit -- Commits outstanding statements

Description

bool oci_commit ( resource connection )

Commits all outstanding statements for the active transaction on the Oracle connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. oci_commit() example

&#60;?php
// Login to Oracle server
$conn = oci_connect('scott', 'tiger');

// Parse SQL
$stmt = oci_parse($conn, "
                          INSERT INTO
                                     employees (name, surname)
                               VALUES
                                     ('Maxim', 'Maletsky')
                         ");

/* Execute statement
   OCI_DEFAULT tells oci_execute()
   not to commit statement immediately */
oci_execute($stmt, OCI_DEFAULT);

/*
....
Parsing and executing other statements here ...
....
*/

// Commit transaction
$committed = oci_commit($conn);

// Test whether commit was successful. If error occurred, return error message
if (!$committed) {
    $error = oci_error($conn);
    echo 'Commit failed. Oracle reports: ' . $error['message'];
}

?&#62;

Notes

Note: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.

See Also

oci_rollback()
oci_execute()

Prev | Home | Next
OCI-Collection->trim | Up | oci_connect


oci_connect

(PHP 5)

oci_connect -- Establishes a connection to the Oracle server

Description

resource oci_connect ( string username, string password [, string db [, string charset [, int session_mode]]] )

Rturns a connection identifier needed for most other OCI calls.

Parameters

username

The Oracle user name.

password

The password for username.

db

This optional parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora.

If the not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.

charset

Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.

session_mode

This parameter is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example 1. oci_connect() example

&#60;?php
echo "&#60;pre&#62;";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_connect("scott", "tiger", $db);

function create_table($conn)
{
  $stmt = oci_parse($conn, "create table scott.hallo (test varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn)
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn)
{
  $stmt = oci_parse($conn, "insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn)
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn)
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn)
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn)
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " [" . oci_result($stmt, "TEST") . "]\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insert a row using c1
insert_data($c2);   // Insert a row using c2

select_data($c1);   // Results of both inserts are returned
select_data($c2);

rollback($c1);      // Rollback using c1

select_data($c1);   // Both inserts have been rolled back
select_data($c2);

insert_data($c2);   // Insert a row using c2
commit($c2);        // Commit using c2

select_data($c1);   // Result of c2 insert is returned

delete_data($c1);   // Delete all rows in table using c1
select_data($c1);   // No rows returned
select_data($c2);   // No rows returned
commit($c1);        // Commit using c1

select_data($c1);   // No rows returned
select_data($c2);   // No rows returned

drop_table($c1);
echo "&#60;/pre&#62;";
?&#62;

Notes

Note: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.

Note: The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that queries issued against one handle are also applied to the other handles, because they are the same handle. This behaviour is demonstrated in Example 1 below. If you require two handles to be transactionally isolated from each other, you should use oci_new_connect() instead.

Note: In PHP versions before 5.0.0 you must use ocilogon() instead. This name still can be used, it was left as the alias of oci_connect() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_pconnect()
oci_new_connect()
oci_close()

Prev | Home | Next
oci_commit | Up | oci_define_by_name


oci_define_by_name

(PHP 5)

oci_define_by_name -- Uses a PHP variable for the define-step during a SELECT

Description

bool oci_define_by_name ( resource statement, string column_name, mixed &variable [, int type] )

Defines PHP variables for fetches of SQL-Columns.

Parameters

statement

A valid OCI statement identifier.

column_name

The column name. Must be uppercased.

Take into consideration that Oracle uses ALL-UPPERCASE column names, whereby in your select you can also use lowercase. If you define a variable that doesn't exists in your select statement, no error will be issued.

variable

The PHP variable.

type

If you need to define an abstract datatype (LOB/ROWID/BFILE) you must allocate it first using oci_new_descriptor(). See also the oci_bind_by_name() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. oci_define_by_name() example

&#60;?php
/* oci_define_by_name example - thies at thieso dot net (980219) */

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "SELECT empno, ename FROM emp");

/* the define MUST be done BEFORE oci_execute! */

oci_define_by_name($stmt, "EMPNO", $empno);
oci_define_by_name($stmt, "ENAME", $ename);

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "empno:" . $empno . "\n";
    echo "ename:" . $ename . "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocidefinebyname() instead. This name still can be used, it was left as alias of oci_define_by_name() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_connect | Up | oci_error


oci_error

(PHP 5)

oci_error -- Returns the last error found

Description

array oci_error ( [resource source] )

Returns the last error found.

Parameters

source

For most errors, the parameter is the most appropriate resource
handle. For connection errors with oci_connect(),
oci_new_connect() or
oci_pconnect() do not pass a parameter.

Return Values

If no error is found, oci_error() returns FALSE. oci_error() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle error string.

ChangeLog

Version | Description
4.3 | offset and sqltext will also be included in the return array to indicate the location of the error and the original SQL text which caused it.

Examples

Example 1. Displaying the Oracle error message after a connection error

$conn = @oci_connect("scott", "tiger", "mydb");
if (!$conn) {
  $e = oci_error();   // For oci_connect errors pass no handle
  echo htmlentities($e['message']);
}

Example 2. Displaying the Oracle error message after a parsing error

$stmt = @oci_parse($conn, "select ' from dual");  // note mismatched quote
if (!$stmt) {
  $e = oci_error($conn);  // For oci_parse errors pass the connection handle
  echo htmlentities($e['message']);
}

Example 3. Displaying the Oracle error message and problematic statement after an execution error

$r = oci_execute($stmt);
if (!$r) {
  $e = oci_error($stmt); // For oci_execute errors pass the statementhandle
  echo htmlentities($e['message']);
  echo "&#60;pre&#62;";
  echo htmlentities($e['sqltext']);
  printf("\n%".($e['offset']+1)."s", "^");
  echo "&#60;/pre&#62;";
}

Notes

Note: In PHP versions before 5.0.0 you must use ocierror() instead. This name still can be used, it was left as alias of oci_error() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_define_by_name | Up | oci_execute


oci_execute

(PHP 5)

oci_execute -- Executes a statement

Description

bool oci_execute ( resource statement [, int mode] )

Executes a previously parsed statement.

Parameters

statement

A valid OCI statement identifier.

mode

Allows you to specify the execution mode (default is OCI_COMMIT_ON_SUCCESS).

If you don't want statements to be committed automatically, you should specify OCI_DEFAULT as your mode.

When using OCI_DEFAULT mode, you're creating a transaction. Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: In PHP versions before 5.0.0 you must use ociexecute() instead. This name still can be used, it was left as alias of oci_execute() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_parse()

Prev | Home | Next
oci_error | Up | oci_fetch_all


oci_fetch_all

(PHP 5)

oci_fetch_all -- Fetches all rows of result data into an array

Description

int oci_fetch_all ( resource statement, array &output [, int skip [, int maxrows [, int flags]]] )

Fetches all the rows from a result into a user-defined array.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

A valid OCI statement identifier.

output

Note: This function sets NULL fields to PHP NULL value.

skip

The number of initial rows to ignore when fetching the result (default value of 0, to start at the first line).

maxrows

The number of rows to read, starting at the skipth row (default to -1, meaning all the rows).

flags

Parameter flags can be any combination of the following:

OCI_FETCHSTATEMENT_BY_ROW
OCI_FETCHSTATEMENT_BY_COLUMN (default value)
OCI_NUM
OCI_ASSOC

Return Values

Returns the number of rows fetched or FALSE in case of an error.

Examples

Example 1. oci_fetch_all() example

&#60;?php
/* oci_fetch_all example mbritton at verinet dot com (990624) */

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

$nrows = oci_fetch_all($stmt, $results);
if ($nrows &#62; 0) {
   echo "&#60;table border=\"1\"&#62;\n";
   echo "&#60;tr&#62;\n";
   foreach ($results as $key =&#62; $val) {
      echo "&#60;th&#62;$key&#60;/th&#62;\n";
   }
   echo "&#60;/tr&#62;\n";

   for ($i = 0; $i &#60; $nrows; $i++) {
      echo "&#60;tr&#62;\n";
      foreach ($results as $data) {
         echo "&#60;td&#62;$data[$i]&#60;/td&#62;\n";
      }
      echo "&#60;/tr&#62;\n";
   }
   echo "&#60;/table&#62;\n";
} else {
   echo "No data found&#60;br /&#62;\n";
}
echo "$nrows Records Selected&#60;br /&#62;\n";

oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocifetchstatement() instead. This name still can be used, it was left as alias of oci_fetch_all() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_execute | Up | oci_fetch_array


oci_fetch_array

(PHP 5)

oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or both

Description

array oci_fetch_array ( resource statement [, int mode] )

Returns an array, which corresponds to the next result row.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

It should be mentioned here, that oci_fetch_array() is insignificantly slower, than oci_fetch_row(), but much more handy.

Parameters

statement

A valid OCI statement identifier.

statement

An optional second parameter can be any combination of the following constants:

OCI_BOTH - return an array with both associative and numeric indices (the same as OCI_ASSOC + OCI_NUM). This is the default behavior.
OCI_ASSOC - return an associative array (as oci_fetch_assoc() works).
OCI_NUM - return a numeric array, (as oci_fetch_row() works).
OCI_RETURN_NULLS - create empty elements for the NULL fields.
OCI_RETURN_LOBS - return the value of a LOB of the descriptor.

Default mode is OCI_BOTH.

Return Values

Returns an array with both associative and numeric indices, or FALSE if there are no more rows in the statement.

Note: This function sets NULL fields to PHP NULL value.

Note: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.

Examples

Example 1. oci_fetch_array() with OCI_BOTH example

&#60;?php
$connection = oci_connect("apelsin", "kanistra");

$query = "SELECT id, name FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_BOTH)) {
    echo $row[0]." and ".$row['ID']." is the same&#60;br&#62;";
    echo $row[1]." and ".$row['NAME']." is the same&#60;br&#62;";
}
?&#62;

Example 2. oci_fetch_array() with OCI_NUM example

&#60;?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_NUM)) {
    echo $row[0]."&#60;br&#62;";
    echo $row[1]."&#60;br&#62;";
    echo $row[2]-&#62;read(100)."&#60;br&#62;";  //this will output first 100 bytes from LOB
}
?&#62;

Example 3. oci_fetch_array() with OCI_ASSOC example

&#60;?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_ASSOC)) {
    echo $row['ID']."&#60;br&#62;";
    echo $row['NAME']."&#60;br&#62;";
    echo $row['LOB_FIELD']."&#60;br&#62;";  //this will output "Object id #1"
}
?&#62;

Example 4. oci_fetch_array() with OCI_RETURN_LOBS example

&#60;?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, (OCI_NUM+OCI_RETURN_LOBS))) {
    echo $row[0]."&#60;br&#62;";
    echo $row[1]."&#60;br&#62;";
    echo $row['LOB_FIELD']."&#60;br&#62;";  //this will output LOB's content
}
?&#62;

See Also

oci_fetch_assoc()
oci_fetch_object()
oci_fetch_row()
oci_fetch_all()

Prev | Home | Next
oci_fetch_all | Up | oci_fetch_assoc


oci_fetch_assoc

(PHP 5)

oci_fetch_assoc -- Returns the next row from the result data as an associative array

Description

array oci_fetch_assoc ( resource statement )

Returns the next row from the result data as an associative array.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC.

A subsequent call to oci_fetch_assoc() will return the next row or FALSE if there are no more rows.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns an associative array, or FALSE if there are no more rows in the statement.

Note: This function sets NULL fields to PHP NULL value.

Note: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.

See Also

oci_fetch_array()
oci_fetch_object()
oci_fetch_row()
oci_fetch_all()

Prev | Home | Next
oci_fetch_array | Up | oci_fetch_object


oci_fetch_object

(PHP 5)

oci_fetch_object -- Returns the next row from the result data as an object

Description

object oci_fetch_object ( resource statement )

Returns the next row from the result data as an object.

Subsequent calls to oci_fetch_object() will return the next row from the result or FALSE if there are no more rows.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns an object, which attributes correspond to fields in statement, or FALSE if there are no more rows in the statement.

Note: This function sets NULL fields to PHP NULL value.

Note: Oracle returns all field names in uppercase and associative indices in the result object will be uppercased too.

See Also

oci_fetch_array()
oci_fetch_assoc()
oci_fetch_row()
oci_fetch_all()

Prev | Home | Next
oci_fetch_assoc | Up | oci_fetch_row


oci_fetch_row

(PHP 5)

oci_fetch_row -- Returns the next row from the result data as a numeric array

Description

array oci_fetch_row ( resource statement )

Returns the next row from the result data as an indexed array.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM.

Subsequent calls to oci_fetch_row() will return the next row from the result data or FALSE if there are no more rows.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns an indexed array with the field information, or FALSE if there are no more rows in the statement.

Note: This function sets NULL fields to PHP NULL value.

See Also

oci_fetch_array()
oci_fetch_assoc()
oci_fetch_object()
oci_fetch_all()

Prev | Home | Next
oci_fetch_object | Up | oci_fetch


oci_fetch

(PHP 5)

oci_fetch -- Fetches the next row into result-buffer

Description

bool oci_fetch ( resource statement )

Fetches the next row (for SELECT statements) into the internal result-buffer.

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: In PHP versions before 5.0.0 you must use ocifetch() instead. This name still can be used, it was left as alias of oci_fetch() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_fetch_row | Up | oci_field_is_null


oci_field_is_null

(PHP 5)

oci_field_is_null -- Checks if the field is NULL

Description

bool oci_field_is_null ( resource statement, mixed field )

Checks if the given field from the statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be a field's index or a field's name (uppercased).

Return Values

Returns TRUE if field is NULL, FALSE otherwise.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_fetch | Up | oci_field_name


oci_field_name

(PHP 5)

oci_field_name -- Returns the name of a field from the statement

Description

string oci_field_name ( resource statement, int field )

Returns the name of the field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the name as a string, or FALSE on errors.

Examples

Example 1. oci_field_name() example

&#60;?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "&#60;table border=\"1\"&#62;";
echo "&#60;tr&#62;";
echo "&#60;th&#62;Name&#60;/th&#62;";
echo "&#60;th&#62;Type&#60;/th&#62;";
echo "&#60;th&#62;Length&#60;/th&#62;";
echo "&#60;/tr&#62;";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i &#60;= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "&#60;tr&#62;";
    echo "&#60;td&#62;$column_name&#60;/td&#62;";
    echo "&#60;td&#62;$column_type&#60;/td&#62;";
    echo "&#60;td&#62;$column_size&#60;/td&#62;";
    echo "&#60;/tr&#62;";
}

echo "&#60;/table&#62;\n";
oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_num_fields()
oci_field_type()
oci_field_size()

Prev | Home | Next
oci_field_is_null | Up | oci_field_precision


oci_field_precision

(PHP 5)

oci_field_precision -- Tell the precision of a field

Description

int oci_field_precision ( resource statement, int field )

Returns precision of the field.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the precision as an integer, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_field_scale()
oci_field_type()

Prev | Home | Next
oci_field_name | Up | oci_field_scale


oci_field_scale

(PHP 5)

oci_field_scale -- Tell the scale of the field

Description

int oci_field_scale ( resource statement, int field )

Returns the scale of the column with field index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the scale as an integer, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_field_precision()
oci_field_type()

Prev | Home | Next
oci_field_precision | Up | oci_field_size


oci_field_size

(PHP 5)

oci_field_size -- Returns field's size

Description

int oci_field_size ( resource statement, mixed field )

Returns the size of a field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the size of a field in bytes, or FALSE on errors.

Examples

Example 1. oci_field_size()example

&#60;?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "&#60;table border=\"1\"&#62;";
echo "&#60;tr&#62;";
echo "&#60;th&#62;Name&#60;/th&#62;";
echo "&#60;th&#62;Type&#60;/th&#62;";
echo "&#60;th&#62;Length&#60;/th&#62;";
echo "&#60;/tr&#62;";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i &#60;= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);
    echo "&#60;tr&#62;";
    echo "&#60;td&#62;$column_name&#60;/td&#62;";
    echo "&#60;td&#62;$column_type&#60;/td&#62;";
    echo "&#60;td&#62;$column_size&#60;/td&#62;";
    echo "&#60;/tr&#62;";
}

echo "&#60;/table&#62;";

oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_num_fields()
oci_field_name()

Prev | Home | Next
oci_field_scale | Up | oci_field_type_raw


oci_field_type_raw

(PHP 5)

oci_field_type_raw -- Tell the raw Oracle data type of the field

Description

int oci_field_type_raw ( resource statement, int field )

Returns Oracle's raw data type of the field.

However, if you want to get field's type, then oci_field_type() will suit you better.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns Oracle's raw data type as a string, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_field_size | Up | oci_field_type


oci_field_type

(PHP 5)

oci_field_type -- Returns field's data type

Description

mixed oci_field_type ( resource statement, int field )

Returns a field's data type.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the field data type as a string, or FALSE on errors.

Return Values

Example 1. oci_field_type() example

&#60;?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "&#60;table border=\"1\"&#62;";
echo "&#60;tr&#62;";
echo "&#60;th&#62;Name&#60;/th&#62;";
echo "&#60;th&#62;Type&#60;/th&#62;";
echo "&#60;th&#62;Length&#60;/th&#62;";
echo "&#60;/tr&#62;";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i &#60;= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "&#60;tr&#62;";
    echo "&#60;td&#62;$column_name&#60;/td&#62;";
    echo "&#60;td&#62;$column_type&#60;/td&#62;";
    echo "&#60;td&#62;$column_size&#60;/td&#62;";
    echo "&#60;/tr&#62;";
}

echo "&#60;/table&#62;\n";

oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_num_fields()
oci_field_name()
oci_field_size()

Prev | Home | Next
oci_field_type_raw | Up | oci_free_statement


oci_free_statement

(PHP 5)

oci_free_statement -- Frees all resources associated with statement or cursor

Description

bool oci_free_statement ( resource statement )

Frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
oci_field_type | Up | oci_internal_debug


oci_internal_debug

(PHP 5)

oci_internal_debug -- Enables or disables internal debug output

Description

void oci_internal_debug ( int onoff )

Enables or disables internal debug output.

Parameters

onoff

Set this to 0 to turn debug output off or 1 to turn it on.

Return Values

No value is returned.

Notes

Note: In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_free_statement | Up | OCI-Lob->append


OCI-Lob->append

(no version information, might be only in CVS)

OCI-Lob->append -- Appends data from the large object to another large object

Description

class OCI-Lob {

bool append ( OCI-Lob lob_from )

}

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob->flush before disabling buffering.

Parameters

lob_from

The copied LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->flush
OCI-Lob->setBuffering
OCI-Lob->getBuffering

Prev | Home | Next
oci_internal_debug | Up | OCI-Lob->close


OCI-Lob->close

(no version information, might be only in CVS)

OCI-Lob->close -- Closes LOB descriptor

Description

class OCI-Lob {

bool close ( void )

}

Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob->writeTemporary.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->writeTemporary

Prev | Home | Next
OCI-Lob->append | Up | oci_lob_copy


oci_lob_copy

(PHP 5)

oci_lob_copy -- Copies large object

Description

bool oci_lob_copy ( OCI-Lob lob_to, OCI-Lob lob_from [, int length] )

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use oci_lob_seek() to move LOB internal pointers.

Parameters

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
OCI-Lob->close | Up | OCI-Lob->eof


OCI-Lob->eof

(no version information, might be only in CVS)

OCI-Lob->eof -- Tests for end-of-file on a large object's descriptor

Description

class OCI-Lob {

bool eof ( void )

}

Tells whether the internal pointer of large object is at the end of LOB.

Return Values

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

See Also

OCI-Lob->size

Prev | Home | Next
oci_lob_copy | Up | OCI-Lob->erase


OCI-Lob->erase

(no version information, might be only in CVS)

OCI-Lob->erase -- Erases a specified portion of the internal LOB data

Description

class OCI-Lob {

int erase ( [int offset [, int length]] )

}

Erases a specified portion of the internal LOB data starting at a specified offset. If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

Parameters

offset

length

Return Values

Returns the actual number of characters/bytes erased or FALSE in case of error.

See Also

OCI-Lob->truncate

Prev | Home | Next
OCI-Lob->eof | Up | OCI-Lob->export


OCI-Lob->export

(no version information, might be only in CVS)

OCI-Lob->export -- Exports LOB's contents to a file

Description

class OCI-Lob {

bool export ( string filename [, int start [, int length]] )

}

Exports LOB contents to a file.

Parameters

filename

Path to the file.

start

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->import

Prev | Home | Next
OCI-Lob->erase | Up | OCI-Lob->flush


OCI-Lob->flush

(no version information, might be only in CVS)

OCI-Lob->flush -- Flushes/writes buffer of the LOB to the server

Description

class OCI-Lob {

bool flush ( [int flag] )

}

OCI-Lob->flush() actually writes data to the server.

Parameters

flag

By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

Return Values

Returns TRUE on success or FALSE on failure.

Returns FALSE if buffering was not enabled or an error occurred.

See Also

OCI-Lob->getBuffering
OCI-Lob->setBuffering

Prev | Home | Next
OCI-Lob->export | Up | OCI-Lob->free


OCI-Lob->import

(no version information, might be only in CVS)

OCI-Lob->import -- Imports file data to the LOB

Description

class OCI-Lob {

bool import ( string filename )

}

Writes data from the filename in to the current position of large object.

Parameters

filename

Path to the file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->export
OCI-Lob->write

Prev | Home | Next
OCI-Lob->getBuffering | Up | oci_lob_is_equal


oci_lob_is_equal

(PHP 5)

oci_lob_is_equal -- Compares two LOB/FILE locators for equality

Description

bool oci_lob_is_equal ( OCI-Lob lob1, OCI-Lob lob2 )

Compares two LOB/FILE locators.

Parameters

lob1

A LOB identifier.

lob2

A LOB identifier.

Return Values

Returns TRUE if these objects are equal, FALSE otherwise.

Prev | Home | Next
OCI-Lob->import | Up | OCI-Lob->load


OCI-Lob->load

(no version information, might be only in CVS)

OCI-Lob->load -- Returns large object's contents

Description

class OCI-Lob {

string load ( void )

}

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob->read instead.

Return Values

Returns the contents of the object, or FALSE on errors.

See Also

OCI-Lob->read

Prev | Home | Next
oci_lob_is_equal | Up | OCI-Lob->read


OCI-Lob->read

(no version information, might be only in CVS)

OCI-Lob->read -- Reads part of the large object

Description

class OCI-Lob {

string read ( int length )

}

Reads length bytes from the current position of LOB's internal pointer.

Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.

Parameters

length

The length of data to read, in bytes.

Return Values

Returns the contents as a string, or FALSE in case of error.

See Also

OCI-Lob->load
OCI-Lob->write

Prev | Home | Next
OCI-Lob->load | Up | OCI-Lob->rewind


OCI-Lob->rewind

(no version information, might be only in CVS)

OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large object

Description

class OCI-Lob {

bool rewind ( void )

}

Sets the internal pointer to the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->seek
OCI-Lob->tell

Prev | Home | Next
OCI-Lob->read | Up | OCI-Lob->save


OCI-Lob->save

(no version information, might be only in CVS)

OCI-Lob->save -- Saves data to the large object

Description

class OCI-Lob {

bool save ( string data [, int offset] )

}

Saves data to the large object.

Parameters

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->write
OCI-Lob->import

Prev | Home | Next
OCI-Lob->rewind | Up | OCI-Lob->saveFile


OCI-Lob->seek

(no version information, might be only in CVS)

OCI-Lob->seek -- Sets the internal pointer of the large object

Description

class OCI-Lob {

bool seek ( int offset [, int whence] )

}

Sets the internal pointer of the large object.

Parameters

offset

Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence.

whence

May be one of:

OCI_SEEK_SET - sets the position equal to offset
OCI_SEEK_CUR - adds offset bytes to the current position
OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object)

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->rewind
OCI-Lob->tell
OCI-Lob->eof

Prev | Home | Next
OCI-Lob->saveFile | Up | OCI-Lob->setBuffering


OCI-Lob->size

(no version information, might be only in CVS)

OCI-Lob->size -- Returns size of large object

Description

class OCI-Lob {

int size ( void )

}

Gets the size of the large object.

Return Values

Returns length of large object value or FALSE in case of error. Empty objects have zero length.

Prev | Home | Next
OCI-Lob->setBuffering | Up | OCI-Lob->tell


OCI-Lob->tell

(no version information, might be only in CVS)

OCI-Lob->tell -- Returns current position of internal pointer of large object

Description

class OCI-Lob {

int tell ( void )

}

Gets the current position of a LOB's internal pointer.

Return Values

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

See Also

OCI-Lob->rewind
OCI-Lob->size
OCI-Lob->eof

Prev | Home | Next
OCI-Lob->size | Up | OCI-Lob->truncate


OCI-Lob->truncate

(no version information, might be only in CVS)

OCI-Lob->truncate -- Truncates large object

Description

class OCI-Lob {

bool truncate ( [int length] )

}

Truncates the LOB.

Parameters

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completrely purge the LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->erase

Prev | Home | Next
OCI-Lob->tell | Up | OCI-Lob->write


OCI-Lob->write

(no version information, might be only in CVS)

OCI-Lob->write -- Writes data to the large object

Description

class OCI-Lob {

int write ( string data [, int length] )

}

Writes data from the parameter data into the current position of LOB's internal pointer.

Parameters

data

The data to write in the LOB.

length

If this parameter is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written or FALSE in case of error.

See Also

OCI-Lob->read

Prev | Home | Next
OCI-Lob->truncate | Up | OCI-Lob->writeTemporary


oci_new_collection

(PHP 5)

oci_new_collection -- Allocates new collection object

Description

OCI-Collection oci_new_collection ( resource connection, string tdo [, string schema] )

Allocates a new collection object.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

tdo

Should be a valid named type (uppercase).

schema

Should point to the scheme, where the named type was created. The name of the current user is the default value.

Return Values

Returns a new OCICollection object or FALSE on error.

Notes

Note: In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
OCI-Lob->writeToFile | Up | oci_new_connect


oci_new_connect

(PHP 5)

oci_new_connect -- Establishes a new connection to the Oracle server

Description

resource oci_new_connect ( string username, string password [, string db [, string charset [, int session_mode]]] )

Establishes a new connection to an Oracle server and logs on.

Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.

Parameters

username

The Oracle user name.

password

The password for username.

db

This optional parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora.

If the not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.

charset

Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.

session_mode

This parameter is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

Return Values

Returns a connection identifier or FALSE on error.

Examples

The following demonstrates how you can separate connections.

Example 1. oci_new_connect() example

&#60;?php
echo "&#60;html&#62;&#60;pre&#62;";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);

function create_table($conn)
{
  $stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn)
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn)
{
  $stmt = oci_parse($conn, "insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn)
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn)
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn)
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn)
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . "----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " &#60;" . oci_result($stmt, "TEST") . "&#62;\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);
select_data($c2);

rollback($c1);

select_data($c1);
select_data($c2);

insert_data($c2);
commit($c2);

select_data($c1);

delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);

select_data($c1);
select_data($c2);

drop_table($c1);
echo "&#60;/pre&#62;&#60;/html&#62;";
?&#62;

Notes

Note: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.

Note: In PHP versions before 5.0.0 you must use ocinlogon() instead. This name still can be used, it was left as alias of oci_new_connect() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_connect()
oci_pconnect()

Prev | Home | Next
oci_new_collection | Up | oci_new_cursor


oci_new_cursor

(PHP 5)

oci_new_cursor -- Allocates and returns a new cursor (statement handle)

Description

resource oci_new_cursor ( resource connection )

Allocates a new statement handle on the specified connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Return Values

Returns a new statement handle, or FALSE on error.

Examples

Example 1. Using REF CURSOR in an Oracle's stored procedure

&#60;?php
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = oci_connect("scott", "tiger");
$curs = oci_new_cursor($conn);
$stmt = oci_parse($conn, "begin info.output(:data); end;");

oci_bind_by_name($stmt, "data", $curs, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_execute($curs);

while ($data = oci_fetch_row($curs)) {
    var_dump($data);
}

oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?&#62;

Example 2. Using REF CURSOR in an Oracle's select statement

&#60;?php
echo "&#60;html&#62;&#60;body&#62;";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");

oci_execute($stmt);
echo "&#60;table border=\"1\"&#62;";
echo "&#60;tr&#62;";
echo "&#60;th&#62;DEPT NAME&#60;/th&#62;";
echo "&#60;th&#62;DEPT #&#60;/th&#62;";
echo "&#60;th&#62;# EMPLOYEES&#60;/th&#62;";
echo "&#60;/tr&#62;";

while ($data = oci_fetch_assoc($stmt)) {
    echo "&#60;tr&#62;";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    echo "&#60;td&#62;$dname&#60;/td&#62;";
    echo "&#60;td&#62;$deptno&#60;/td&#62;";
    oci_execute($data["EMPCNT"]);
    while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
        $num_emps = $subdata["NUM_EMPS"];
        echo  "&#60;td&#62;$num_emps&#60;/td&#62;";
    }
    echo "&#60;/tr&#62;";
}
echo "&#60;/table&#62;";
echo "&#60;/body&#62;&#60;/html&#62;";
oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_new_connect | Up | oci_new_descriptor


oci_new_descriptor

(PHP 5)

oci_new_descriptor -- Initializes a new empty LOB or FILE descriptor

Description

OCI-Lob oci_new_descriptor ( resource connection [, int type] )

Allocates resources to hold descriptor or LOB locator.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

type

Valid values for type are: OCI_D_FILE, OCI_D_LOB and OCI_D_ROWID.

Return Values

Returns a new LOB or FILE descriptor on success, FALSE on error.

Examples

Example 1. oci_new_descriptor() example

&#60;?php
/* This script is designed to be called from a HTML form.
 * It expects $user, $password, $table, $where, and $commitsize
 * to be passed in from the form.  The script then deletes
 * the selected rows using the ROWID and commits after each
 * set of $commitsize rows. (Use with care, there is no rollback)
 */
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
    $nrows = oci_num_rows($stmt);
    $delete = oci_parse($conn, "delete from $table where ROWID = :rid");
    oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
    oci_execute($delete);
    echo "$nrows\n";
    if (($nrows % $commitsize) == 0) {
        oci_commit($conn);
    }
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?&#62;
&#60;?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * &#60;form action="upload.php" method="post" enctype="multipart/form-data"&#62;
     * &#60;input type="file" name="lob_upload" /&#62;
     * ...
     */
  if (!isset($lob_upload) || $lob_upload == 'none'){
?&#62;
&#60;form action="upload.php" method="post" enctype="multipart/form-data"&#62;
Upload file: &#60;input type="file" name="lob_upload" /&#62;&#60;br /&#62;
&#60;input type="submit" value="Upload" /&#62; - &#60;input type="reset" value="Reset" /&#62;
&#60;/form&#62;
&#60;?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     $conn = oci_connect($user, $password);
     $lob = oci_new_descriptor($conn, OCI_D_LOB);
     $stmt = oci_parse($conn, "insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
     oci_execute($stmt, OCI_DEFAULT);
     if ($lob-&#62;savefile($lob_upload)){
        oci_commit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     oci_free_descriptor($lob);
     oci_free_statement($stmt);
     oci_close($conn);
  }
?&#62;

Example 2. oci_new_descriptor() example

&#60;?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters (PHP 4 &#62;= 4.0.6).
 * Example PL/SQL stored procedure signature is:
 *
 * PROCEDURE save_data
 *   Argument Name                  Type                    In/Out Default?
 *   ------------------------------ ----------------------- ------ --------
 *   KEY                            NUMBER(38)              IN
 *   DATA                           CLOB                    IN
 *
 */

$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob-&#62;write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob-&#62;free();
oci_free_statement($stmt);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_new_cursor | Up | oci_num_fields


oci_num_fields

(PHP 5)

oci_num_fields -- Returns the number of result columns in a statement

Description

int oci_num_fields ( resource statement )

Gets the number of columns in the given statement.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of columns as an integer, or FALSE on errors.

Examples

Example 1. oci_num_fields() example

&#60;?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "\n";
    $ncols = oci_num_fields($stmt);
    for ($i = 1; $i &#60;= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_value = oci_result($stmt, $i);
        echo $column_name . ': ' . $column_value . "\n";
    }
    echo "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_new_descriptor | Up | oci_num_rows


oci_num_rows

(PHP 5)

oci_num_rows -- Returns number of rows affected during statement execution

Description

int oci_num_rows ( resource statement )

Gets the number of rows affected during statement execution.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of rows affected as an integer, or FALSE on errors.

Examples

Example 1. oci_num_rows() example

&#60;?php
$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "create table emp2 as select * from emp");
oci_execute($stmt);
echo oci_num_rows($stmt) . " rows inserted.&#60;br /&#62;";
oci_free_statement($stmt);

$stmt = oci_parse($conn, "delete from emp2");
oci_execute($stmt, OCI_DEFAULT);
echo oci_num_rows($stmt) . " rows deleted.&#60;br /&#62;";
oci_commit($conn);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "drop table emp2");
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?&#62;

Notes

Note: This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.

Note: In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_num_fields | Up | oci_parse


oci_parse

(PHP 5)

oci_parse -- Prepares Oracle statement for execution

Description

resource oci_parse ( resource connection, string query )

Prepares the queryusing connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

query

The SQL query.

Return Values

Returns a statement handler on success, or FALSE on error.

Notes

Note: This function does not validate query. The only way to find out if query is valid SQL or PL/SQL statement - is to execute it.

Note: In PHP versions before 5.0.0 you must use ociparse() instead. This name still can be used, it was left as alias of oci_parse() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_num_rows | Up | oci_password_change


oci_password_change

(PHP 5)

oci_password_change -- Changes password of Oracle's user

Description

bool oci_password_change ( resource connection, string username, string old_password, string new_password )

resource oci_password_change ( string dbname, string username, string old_password, string new_password )

Changes password for user with username.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

username

The Oracle user name.

old_password

The old password.

new_password

The new password to be set.

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The second oci_password_change() syntax is available since version 1.1.

Note: In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_parse | Up | oci_pconnect


oci_pconnect

(PHP 5)

oci_pconnect -- Connect to an Oracle database using a persistent connection

Description

resource oci_pconnect ( string username, string password [, string db [, string charset [, int session_mode]]] )

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.

Parameters

username

The Oracle user name.

password

The password for username.

db

This optional parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora.

If the not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.

charset

Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.

session_mode

This parameter is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

Return Values

Returns a connection identifier or FALSE on error.

Notes

Note: Starting with version 1.1 of the oci8 extension, the lifetime and maximum amount of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

Note: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.

Note: In PHP versions before 5.0.0 you must use ociplogon() instead. This name still can be used, it was left as alias of oci_pconnect() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_connect()
oci_new_connect()

Prev | Home | Next
oci_password_change | Up | oci_result


oci_result

(PHP 5)

oci_result -- Returns field's value from the fetched row

Description

mixed oci_result ( resource statement, mixed field )

Returns the data from field in the current row, fetched by oci_fetch().

For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver

Parameters

statement

field

Can be either use the column number (1-based) or the column name (in uppercase).

Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Notes

Note: In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_fetch_array()
oci_fetch_assoc()
oci_fetch_object()
oci_fetch_row()
oci_fetch_all()

Prev | Home | Next
oci_pconnect | Up | oci_rollback


oci_rollback

(PHP 5)

oci_rollback -- Rolls back outstanding transaction

Description

bool oci_rollback ( resource connection )

Rolls back all outstanding statements for the Oracle connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.

Note: In PHP versions before 5.0.0 you must use ocirollback() instead. This name still can be used, it was left as alias of oci_rollback() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci_commit()

Prev | Home | Next
oci_result | Up | oci_server_version


oci_server_version

(PHP 5)

oci_server_version -- Returns server version

Description

string oci_server_version ( resource connection )

Returns a string with version information of the Oracle server, which uses the provided connection.

Parameters

connection

Return Values

Returns the version information as a string or FALSE on error.

Examples

Example 1. oci_server_version() example

&#60;?php
    $conn = oci_connect("scott", "tiger");
    echo "Server Version: " . oci_server_version($conn);
    oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ociserverversion() instead. This name still can be used, it was left as alias of oci_server_version() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_rollback | Up | oci_set_prefetch


oci_set_prefetch

(PHP 5)

oci_set_prefetch -- Sets number of rows to be prefetched

Description

bool oci_set_prefetch ( resource statement [, int rows] )

Sets the number of rows to be prefetched after successful call to oci_execute().

Parameters

statement

rows

The default value for rows is 1.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: In PHP versions before 5.0.0 you must use ocisetprefetch() instead. This name still can be used, it was left as alias of oci_set_prefetch() for downwards compatability. This, however, is deprecated and not recommended.

See Also

oci8_.default_prefetch ini option

Prev | Home | Next
oci_server_version | Up | oci_statement_type


oci_statement_type

(PHP 5)

oci_statement_type -- Returns the type of an OCI statement

Description

string oci_statement_type ( resource statement )

Returns the type of the provided OCI statement.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the query type ofstatement as one of the following values:

  1. SELECT

  2. UPDATE

  3. DELETE

  4. INSERT

  5. CREATE

  6. DROP

  7. ALTER

  8. BEGIN

  9. DECLARE

  10. CALL (since PHP 5.2.1 and OCI8 1.2.3)

  11. UNKNOWN

Returns FALSE on error.

Examples

Example 1. oci_statement_type() example

&#60;?php
    $conn = oci_connect("scott", "tiger");
    $sql  = "delete from emp where deptno = 10";

    $stmt = oci_parse($conn, $sql);
    if (oci_statement_type($stmt) == "DELETE") {
        die("You are not allowed to delete from this table&#60;br /&#62;");
    }

    oci_close($conn);
?&#62;

Notes

Note: In PHP versions before 5.0.0 you must use ocistatementtype() instead. This name still can be used, it was left as alias of oci_statement_type() for downwards compatability. This, however, is deprecated and not recommended.

Prev | Home | Next
oci_set_prefetch | Up | ocibindbyname


ocibindbyname

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocibindbyname -- Alias of oci_bind_by_name()

Description

This function is an alias of: oci_bind_by_name().

Prev | Home | Next
oci_statement_type | Up | ocicancel


ocicancel

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocicancel -- Alias of oci_cancel()

Description

This function is an alias of: oci_cancel().

Prev | Home | Next
ocibindbyname | Up | ocicloselob


ocicloselob

(no version information, might be only in CVS)

ocicloselob -- Alias of OCI-Lob->close

Description

This function is an alias of: OCI-Lob->close.

Prev | Home | Next
ocicancel | Up | ocicollappend


ocicollappend

(PHP 4 >= 4.0.6, PHP 5)

ocicollappend -- Alias of OCI-Collection->append

Description

This function is an alias of: OCI-Collection->append.

Prev | Home | Next
ocicloselob | Up | ocicollassign


ocicollassign

(PHP 4 >= 4.0.6)

ocicollassign -- Alias of OCI-Collection->assign

Description

This function is an alias of: OCI-Collection->assign.

Prev | Home | Next
ocicollappend | Up | ocicollassignelem


ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5)

ocicollassignelem -- Alias of OCI-Collection->assignElem

Description

This function is an alias of: OCI-Collection->assignElem.

Prev | Home | Next
ocicollassign | Up | ocicollgetelem


ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5)

ocicollgetelem -- Alias of OCI-Collection->getElem

Description

This function is an alias of: OCI-Collection->getElem.

Prev | Home | Next
ocicollassignelem | Up | ocicollmax


ocicollmax

(PHP 4 >= 4.0.6, PHP 5)

ocicollmax -- Alias of OCI-Collection->max

Description

This function is an alias of: OCI-Collection->max.

Prev | Home | Next
ocicollgetelem | Up | ocicollsize


ocicollsize

(PHP 4 >= 4.0.6, PHP 5)

ocicollsize -- Alias of OCI-Collection->size

Description

This function is an alias of: OCI-Collection->size.

Prev | Home | Next
ocicollmax | Up | ocicolltrim


ocicolltrim

(PHP 4 >= 4.0.6, PHP 5)

ocicolltrim -- Alias of OCI-Collection->trim

Description

This function is an alias of: OCI-Collection->trim.

Prev | Home | Next
ocicollsize | Up | ocicolumnisnull


ocicolumnisnull

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnisnull -- Alias of oci_field_is_null()

Description

This function is an alias of: oci_field_is_null().

Prev | Home | Next
ocicolltrim | Up | ocicolumnname


ocicolumnname

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnname -- Alias of oci_field_name()

Description

This function is an alias of: oci_field_name().

Prev | Home | Next
ocicolumnisnull | Up | ocicolumnprecision


ocicolumnprecision

(PHP 4, PHP 5)

ocicolumnprecision -- Alias of oci_field_precision()

Description

This function is an alias of: oci_field_precision().

Prev | Home | Next
ocicolumnname | Up | ocicolumnscale


ocicolumnscale

(PHP 4, PHP 5)

ocicolumnscale -- Alias of oci_field_scale()

Description

This function is an alias of: oci_field_scale().

Prev | Home | Next
ocicolumnprecision | Up | ocicolumnsize


ocicolumnsize

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnsize -- Alias of oci_field_size()

Description

This function is an alias of: oci_field_size().

Prev | Home | Next
ocicolumnscale | Up | ocicolumntype


ocicolumntype

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumntype -- Alias of oci_field_type()

Description

This function is an alias of: oci_field_type().

Prev | Home | Next
ocicolumnsize | Up | ocicolumntyperaw


ocicolumntyperaw

(PHP 4, PHP 5)

ocicolumntyperaw -- Alias of oci_field_type_raw()

Description

This function is an alias of: oci_field_type_raw().

Prev | Home | Next
ocicolumntype | Up | ocicommit


ocicommit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocicommit -- Alias of oci_commit()

Description

This function is an alias of: oci_commit().

Prev | Home | Next
ocicolumntyperaw | Up | ocidefinebyname


ocidefinebyname

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocidefinebyname -- Alias of oci_define_by_name()

Description

This function is an alias of: oci_define_by_name().

Prev | Home | Next
ocicommit | Up | ocierror


ocierror

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocierror -- Alias of oci_error()

Description

This function is an alias of: oci_error().

Prev | Home | Next
ocidefinebyname | Up | ociexecute


ociexecute

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociexecute -- Alias of oci_execute()

Description

This function is an alias of: oci_execute().

Prev | Home | Next
ocierror | Up | ocifetch


ocifetch

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocifetch -- Alias of oci_fetch()

Description

This function is an alias of: oci_fetch().

Prev | Home | Next
ociexecute | Up | ocifetchinto


ocifetchinto

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocifetchinto -- Fetches the next row into an array (deprecated)

Description

int ocifetchinto ( resource statement, array &result [, int mode] )

This function is deprecated. Recommended alternatives:
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() and
oci_fetch_row().

Prev | Home | Next
ocifetch | Up | ocifetchstatement


ocifetchstatement

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocifetchstatement -- Alias of oci_fetch_all()

Description

This function is an alias of: oci_fetch_all().

Prev | Home | Next
ocifetchinto | Up | ocifreecollection


ocifreecollection

(PHP 4 >= 4.1.0, PHP 5)

ocifreecollection -- Alias of OCI-Collection->free

Description

This function is an alias of: OCI-Collection->free.

Prev | Home | Next
ocifetchstatement | Up | ocifreecursor


ocifreecursor

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocifreecursor -- Alias of oci_free_statement()

Description

This function is an alias of: oci_free_statement().

Prev | Home | Next
ocifreecollection | Up | ocifreedesc


ocifreedesc

(PHP 4, PHP 5)

ocifreedesc -- Alias of OCI-Lob->free

Description

This function is an alias of: OCI-Lob->free.

Prev | Home | Next
ocifreecursor | Up | ocifreestatement


ocifreestatement

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

ocifreestatement -- Alias of oci_free_statement()

Description

This function is an alias of: oci_free_statement().

Prev | Home | Next
ocifreedesc | Up | ociinternaldebug


ociinternaldebug

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociinternaldebug -- Alias of oci_internal_debug()

Description

This function is an alias of: oci_internal_debug().

Prev | Home | Next
ocifreestatement | Up | ociloadlob


ociloadlob

(PHP 4, PHP 5)

ociloadlob -- Alias of OCI-Lob->load

Description

This function is an alias of: OCI-Lob->load.

Prev | Home | Next
ociinternaldebug | Up | ocilogoff


ocilogoff

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocilogoff -- Alias of oci_close()

Description

This function is an alias of: oci_close().

Prev | Home | Next
ociloadlob | Up | ocilogon


ocilogon

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocilogon -- Alias of oci_connect()

Description

This function is an alias of: oci_connect().

Prev | Home | Next
ocilogoff | Up | ocinewcollection


ocinewcollection

(PHP 4 >= 4.0.6, PHP 5)

ocinewcollection -- Alias of oci_new_collection()

Description

This function is an alias of: oci_new_collection().

Prev | Home | Next
ocilogon | Up | ocinewcursor


ocinewcursor

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocinewcursor -- Alias of oci_new_cursor()

Description

This function is an alias of: oci_new_cursor().

Prev | Home | Next
ocinewcollection | Up | ocinewdescriptor


ocinewdescriptor

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocinewdescriptor -- Alias of oci_new_descriptor()

Description

This function is an alias of: oci_new_descriptor().

Prev | Home | Next
ocinewcursor | Up | ocinlogon


ocinlogon

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocinlogon -- Alias of oci_new_connect()

Description

This function is an alias of: oci_new_connect().

Prev | Home | Next
ocinewdescriptor | Up | ocinumcols


ocinumcols

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocinumcols -- Alias of oci_num_fields()

Description

This function is an alias of: oci_num_fields().

Prev | Home | Next
ocinlogon | Up | ociparse


ociparse

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociparse -- Alias of oci_parse()

Description

This function is an alias of: oci_parse().

Prev | Home | Next
ocinumcols | Up | ociplogon


ociplogon

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ociplogon -- Alias of oci_pconnect()

Description

This function is an alias of: oci_pconnect().

Prev | Home | Next
ociparse | Up | ociresult


ociresult

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociresult -- Alias of oci_result()

Description

This function is an alias of: oci_result().

Prev | Home | Next
ociplogon | Up | ocirollback


ocirollback

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocirollback -- Alias of oci_rollback()

Description

This function is an alias of: oci_rollback().

Prev | Home | Next
ociresult | Up | ocirowcount


ocirowcount

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocirowcount -- Alias of oci_num_rows()

Description

This function is an alias of: oci_num_rows().

Prev | Home | Next
ocirollback | Up | ocisavelob


ocisavelob

(PHP 4, PHP 5)

ocisavelob -- Alias of OCI-Lob->save

Description

This function is an alias of: OCI-Lob->save.

Prev | Home | Next
ocirowcount | Up | ocisavelobfile


ocisavelobfile

(PHP 4, PHP 5)

ocisavelobfile -- Alias of OCI-Lob->import

Description

This function is an alias of: OCI-Lob->import.

Prev | Home | Next
ocisavelob | Up | ociserverversion


ociserverversion

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociserverversion -- Alias of oci_server_version()

Description

This function is an alias of: oci_server_version().

Prev | Home | Next
ocisavelobfile | Up | ocisetprefetch


ocisetprefetch

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ocisetprefetch -- Alias of oci_set_prefetch()

Description

This function is an alias of: oci_set_prefetch().

Prev | Home | Next
ociserverversion | Up | ocistatementtype


ocistatementtype

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

ocistatementtype -- Alias of oci_statement_type()

Description

This function is an alias of: oci_statement_type().

Prev | Home | Next
ocisetprefetch | Up | ociwritelobtofile


ociwritelobtofile

(PHP 4, PHP 5)

ociwritelobtofile -- Alias of OCI-Lob->export

Description

This function is an alias of: OCI-Lob->export.

Prev | Home | Next
ocistatementtype | Up | ociwritetemporarylob


ociwritetemporarylob

(no version information, might be only in CVS)

ociwritetemporarylob -- Alias of OCI-Lob->writeTemporary

Description

This function is an alias of: OCI-Lob->writeTemporary.

Prev | Home | Next
ociwritelobtofile | Up | ODBC Functions (Unified)


OpenAL Audio Bindings

PHP Manual
Prev Next

CIX. OpenAL Audio Bindings

Introduction

Platform independent audio bindings. Requires the OpenAL library.

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/openal.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension defines four resource types:
Open AL(Device) - Returned by openal_device_open(),
Open AL(Context) - Returned by openal_context_create(),
Open AL(Buffer) - Returned by openal_buffer_create(),
and Open AL(Source) - Returned by openal_source_create().

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.

ALC_FREQUENCY (integer)

Context Attribute

ALC_REFRESH (integer)

Context Attribute

ALC_SYNC (integer)

Context Attribute

AL_FREQUENCY (integer)

Buffer Setting

AL_BITS (integer)

Buffer Setting

AL_CHANNELS (integer)

Buffer Setting

AL_SIZE (integer)

Buffer Setting

AL_BUFFER (integer)

Source/Listener Setting (Integer)

AL_SOURCE_RELATIVE (integer)

Source/Listener Setting (Integer)

AL_SOURCE_STATE (integer)

Source/Listener Setting (Integer)

AL_PITCH (integer)

Source/Listener Setting (Float)

AL_GAIN (integer)

Source/Listener Setting (Float)

AL_MIN_GAIN (integer)

Source/Listener Setting (Float)

AL_MAX_GAIN (integer)

Source/Listener Setting (Float)

AL_MAX_DISTANCE (integer)

Source/Listener Setting (Float)

AL_ROLLOFF_FACTOR (integer)

Source/Listener Setting (Float)

AL_CONE_OUTER_GAIN (integer)

Source/Listener Setting (Float)

AL_CONE_INNER_ANGLE (integer)

Source/Listener Setting (Float)

AL_CONE_OUTER_ANGLE (integer)

Source/Listener Setting (Float)

AL_REFERENCE_DISTANCE (integer)

Source/Listener Setting (Float)

AL_POSITION (integer)

Source/Listener Setting (Float Vector)

AL_VELOCITY (integer)

Source/Listener Setting (Float Vector)

AL_DIRECTION (integer)

Source/Listener Setting (Float Vector)

AL_ORIENTATION (integer)

Source/Listener Setting (Float Vector)

AL_FORMAT_MONO8 (integer)

PCM Format

AL_FORMAT_MONO16 (integer)

PCM Format

AL_FORMAT_STEREO8 (integer)

PCM Format

AL_FORMAT_STEREO16 (integer)

PCM Format

AL_INITIAL (integer)

Source State

AL_PLAYING (integer)

Source State

AL_PAUSED (integer)

Source State

AL_STOPPED (integer)

Source State

AL_LOOPING (integer)

Source State

AL_TRUE (integer)

Boolean value recognized by OpenAL

AL_FALSE (integer)

Boolean value recognized by OpenAL

Table of Contents
openal_buffer_create -- Generate OpenAL buffer
openal_buffer_data -- Load a buffer with data
openal_buffer_destroy -- Destroys an OpenAL buffer
openal_buffer_get -- Retrieve an OpenAL buffer property
openal_buffer_loadwav -- Load a .wav file into a buffer
openal_context_create -- Create an audio processing context
openal_context_current -- Make the specified context current
openal_context_destroy -- Destroys a context
openal_context_process -- Process the specified context
openal_context_suspend -- Suspend the specified context
openal_device_close -- Close an OpenAL device
openal_device_open -- Initialize the OpenAL audio layer
openal_listener_get -- Retrieve a listener property
openal_listener_set -- Set a listener property
openal_source_create -- Generate a source resource
openal_source_destroy -- Destroy a source resource
openal_source_get -- Retrieve an OpenAL source property
openal_source_pause -- Pause the source
openal_source_play -- Start playing the source
openal_source_rewind -- Rewind the source
openal_source_set -- Set source property
openal_source_stop -- Stop playing the source
openal_stream -- Begin streaming on a source

Prev | Home | Next
Usage | Up | openal_buffer_create


openal_buffer_create

(PECL)

openal_buffer_create -- Generate OpenAL buffer

Description

resource openal_buffer_create ( void )

Return Values

Returns an Open AL(Buffer) resource on success or FALSE on failure.

See Also

openal_buffer_loadwav()
openal_buffer_data()

Prev | Home | Next
OpenAL Audio Bindings | Up | openal_buffer_data


openal_buffer_data

(PECL)

openal_buffer_data -- Load a buffer with data

Description

bool openal_buffer_data ( resource buffer, int format, string data, int freq )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

freq

Frequency of data given in Hz.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_buffer_loadwav()
openal_stream()

Prev | Home | Next
openal_buffer_create | Up | openal_buffer_destroy


openal_buffer_destroy

(PECL)

openal_buffer_destroy -- Destroys an OpenAL buffer

Description

bool openal_buffer_destroy ( resource buffer )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_buffer_create()

Prev | Home | Next
openal_buffer_data | Up | openal_buffer_get


openal_buffer_get

(PECL)

openal_buffer_get -- Retrieve an OpenAL buffer property

Description

int openal_buffer_get ( resource buffer, int property )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS and AL_SIZE.

Return Values

Returns an integer value appropriate to the property requested or FALSE on failure.

See Also

openal_buffer_create()

Prev | Home | Next
openal_buffer_destroy | Up | openal_buffer_loadwav


openal_buffer_loadwav

(PECL)

openal_buffer_loadwav -- Load a .wav file into a buffer

Description

bool openal_buffer_loadwav ( resource buffer, string wavfile )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .WAV file on local file system.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_buffer_data()
openal_stream()

Prev | Home | Next
openal_buffer_get | Up | openal_context_create


openal_context_create

(PECL)

openal_context_create -- Create an audio processing context

Description

resource openal_context_create ( resource device )

Parameters

device

An Open AL(Device) resource (previously created by openal_device_open()).

Return Values

Returns an Open AL(Context) resource on success or FALSE on failure.

See Also

openal_device_open()
openal_context_destroy()

Prev | Home | Next
openal_buffer_loadwav | Up | openal_context_current


openal_context_current

(PECL)

openal_context_current -- Make the specified context current

Description

bool openal_context_current ( resource context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_context_create()

Prev | Home | Next
openal_context_create | Up | openal_context_destroy


openal_context_destroy

(PECL)

openal_context_destroy -- Destroys a context

Description

bool openal_context_destroy ( resource context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_context_create()

Prev | Home | Next
openal_context_current | Up | openal_context_process


openal_context_process

(PECL)

openal_context_process -- Process the specified context

Description

bool openal_context_process ( resource context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_context_create()
openal_context_current()
openal_context_suspend()

Prev | Home | Next
openal_context_destroy | Up | openal_context_suspend


openal_context_suspend

(PECL)

openal_context_suspend -- Suspend the specified context

Description

bool openal_context_suspend ( resource context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_context_create()
openal_context_current()
openal_context_process()

Prev | Home | Next
openal_context_process | Up | openal_device_close


openal_device_close

(PECL)

openal_device_close -- Close an OpenAL device

Description

bool openal_device_close ( resource device )

Parameters

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_device_open()

Prev | Home | Next
openal_context_suspend | Up | openal_device_open


openal_device_open

(PECL)

openal_device_open -- Initialize the OpenAL audio layer

Description

resource openal_device_open ( [string device_desc] )

Parameters

device_desc

Open an audio device optionally specified by device_desc. If device_desc is not specified the first available audio device will be used.

Return Values

Returns an Open AL(Device) resource on success or FALSE on failure.

See Also

openal_device_close()
openal_context_create()

Prev | Home | Next
openal_device_close | Up | openal_listener_get


openal_listener_get

(PECL)

openal_listener_get -- Retrieve a listener property

Description

mixed openal_listener_get ( int property )

Parameters

property

Property to retrieve, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).

Return Values

Returns a float or array of floats (as appropriate), or FALSE on failure.

See Also

openal_listener_set()

Prev | Home | Next
openal_device_open | Up | openal_listener_set


openal_listener_set

(PECL)

openal_listener_set -- Set a listener property

Description

bool openal_listener_set ( int property, mixed setting )

Parameters

property

Property to set, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).

setting

Value to set, either float, or an array of floats as appropriate.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_listener_get()

Prev | Home | Next
openal_listener_get | Up | openal_source_create


openal_source_create

(PECL)

openal_source_create -- Generate a source resource

Description

resource openal_source_create ( void )

Return Values

Returns an Open AL(Source) resource on success or FALSE on failure.

See Also

openal_source_set()
openal_source_play()
openal_source_destroy()

Prev | Home | Next
openal_listener_set | Up | openal_source_destroy


openal_source_destroy

(PECL)

openal_source_destroy -- Destroy a source resource

Description

bool openal_source_destroy ( resource source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_create()

Prev | Home | Next
openal_source_create | Up | openal_source_get


openal_source_get

(PECL)

openal_source_get -- Retrieve an OpenAL source property

Description

mixed openal_source_get ( resource source, int property )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

Return Values

Returns the type associated with the property being retrieved or FALSE on failure.

See Also

openal_source_create()
openal_source_set()
openal_source_play()

Prev | Home | Next
openal_source_destroy | Up | openal_source_pause


openal_source_pause

(PECL)

openal_source_pause -- Pause the source

Description

bool openal_source_pause ( resource source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_stop()
openal_source_play()
openal_source_rewind()

Prev | Home | Next
openal_source_get | Up | openal_source_play


openal_source_play

(PECL)

openal_source_play -- Start playing the source

Description

bool openal_source_play ( resource source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_stop()
openal_source_pause()
openal_source_rewind()

Prev | Home | Next
openal_source_pause | Up | openal_source_rewind


openal_source_rewind

(PECL)

openal_source_rewind -- Rewind the source

Description

bool openal_source_rewind ( resource source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_stop()
openal_source_pause()
openal_source_play()

Prev | Home | Next
openal_source_play | Up | openal_source_set


openal_source_set

(PECL)

openal_source_set -- Set source property

Description

bool openal_source_set ( resource source, int property, mixed setting )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

setting

Value to assign to specified property. Refer to the description of property for a description of the value(s) expected.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_create()
openal_source_get()
openal_source_play()

Prev | Home | Next
openal_source_rewind | Up | openal_source_stop


openal_source_stop

(PECL)

openal_source_stop -- Stop playing the source

Description

bool openal_source_stop ( resource source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

openal_source_play()
openal_source_pause()
openal_source_rewind()

Prev | Home | Next
openal_source_set | Up | openal_stream


openal_stream

(PECL)

openal_stream -- Begin streaming on a source

Description

resource openal_stream ( resource source, int format, int rate )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

Return Values

Returns a stream resource on success, or FALSE on failure.

See Also

openal_source_create()
fwrite()

Prev | Home | Next
openal_source_stop | Up | OpenSSL Functions


OpenSSL Functions

PHP Manual
Prev Next

CX. OpenSSL Functions

Introduction

This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.

Requirements

In order to use the OpenSSL functions you need to install the OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4 and >= 4.3.2) require OpenSSL >= 0.9.6.

Warning

You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack.

Installation

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl folder of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.

Note to Win32 Users: PHP will search for the openssl.cnf using the following logic:

  • the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.

  • the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.

  • The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.

In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()

    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate

    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()

    2. For public keys only: an X.509 resource

    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)

    4. A string containing the content of a certificate/key, PEM encoded

    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

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.

Purpose checking flags

X509_PURPOSE_SSL_CLIENT (integer)

X509_PURPOSE_SSL_SERVER (integer)

X509_PURPOSE_NS_SSL_SERVER (integer)

X509_PURPOSE_SMIME_SIGN (integer)

X509_PURPOSE_SMIME_ENCRYPT (integer)

X509_PURPOSE_CRL_SIGN (integer)

X509_PURPOSE_ANY (integer)

Padding flags

OPENSSL_PKCS1_PADDING (integer)

OPENSSL_SSLV23_PADDING (integer)

OPENSSL_NO_PADDING (integer)

OPENSSL_PKCS1_OAEP_PADDING (integer)

Key types

OPENSSL_KEYTYPE_RSA (integer)

OPENSSL_KEYTYPE_DSA (integer)

OPENSSL_KEYTYPE_DH (integer)

PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

Table 1. PKCS7 CONSTANTS

Constant | Description
PKCS7_TEXT | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY | Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example).
PKCS7_NOATTR | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS | Don't try and verify the signatures on a message

Note: These constants were added in 4.0.6.

Signature Algorithms

OPENSSL_ALGO_SHA1 (integer)

Used as default algorithm by openssl_sign() and openssl_verify().

OPENSSL_ALGO_MD5 (integer)

OPENSSL_ALGO_MD4 (integer)

OPENSSL_ALGO_MD2 (integer)

Note: These constants were added in 5.0.0.

Ciphers

OPENSSL_CIPHER_RC2_40 (integer)

OPENSSL_CIPHER_RC2_128 (integer)

OPENSSL_CIPHER_RC2_64 (integer)

OPENSSL_CIPHER_DES (integer)

OPENSSL_CIPHER_3DES (integer)

Note: These constants were added in 4.3.0.

Version constants

OPENSSL_VERSION_TEXT (string)

OPENSSL_VERSION_NUMBER (integer)

Note: These constants were added in 5.2.0.

Table of Contents
openssl_csr_export_to_file -- Exports a CSR to a file
openssl_csr_export -- Exports a CSR as a string
openssl_csr_get_public_key -- Returns the public key of a CERT
openssl_csr_get_subject -- Returns the subject of a CERT
openssl_csr_new -- Generates a CSR
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate
openssl_error_string -- Return openSSL error message
openssl_free_key -- Free key resource
openssl_get_privatekey -- Alias of openssl_pkey_get_private()
openssl_get_publickey -- Alias of openssl_pkey_get_public()
openssl_open -- Open sealed data
openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt -- Encrypt an S/MIME message
openssl_pkcs7_sign -- Sign an S/MIME message
openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file
openssl_pkey_export -- Gets an exportable representation of a key into a string
openssl_pkey_free -- Frees a private key
openssl_pkey_get_details -- Returns an array with the key details (bits, pkey, type)
openssl_pkey_get_private -- Get a private key
openssl_pkey_get_public -- Extract public key from certificate and prepare it for use
openssl_pkey_new -- Generates a new private key
openssl_private_decrypt -- Decrypts data with private key
openssl_private_encrypt -- Encrypts data with private key
openssl_public_decrypt -- Decrypts data with public key
openssl_public_encrypt -- Encrypts data with public key
openssl_seal -- Seal (encrypt) data
openssl_sign -- Generate signature
openssl_verify -- Verify signature
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file -- Exports a certificate to file
openssl_x509_export -- Exports a certificate as a string
openssl_x509_free -- Free certificate resource
openssl_x509_parse -- Parse an X509 certificate and return the information as an array
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

Prev | Home | Next
openal_stream | Up | openssl_csr_export_to_file


openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export_to_file -- Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext] )

openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Returns TRUE on success or FALSE on failure.

See also openssl_csr_export(),
openssl_csr_new() and
openssl_csr_sign().

Prev | Home | Next
OpenSSL Functions | Up | openssl_csr_export


openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export -- Exports a CSR as a string

Description

bool openssl_csr_export ( resource csr, string &out [, bool notext] )

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Returns TRUE on success or FALSE on failure.

See also openssl_csr_export_to_file(),
openssl_csr_new() and
openssl_csr_sign().

Prev | Home | Next
openssl_csr_export_to_file | Up | openssl_csr_get_public_key


openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_new -- Generates a CSR

Description

mixed openssl_csr_new ( array dn, resource &privkey [, array configargs [, array extraattribs]] )

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify an alternative openssl configuration file by setting the value of the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.

Table 1. Configuration overrides

configargs key | type | openssl.conf equivalent | description
digest_alg | string | default_md | Selects which digest method to use
x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate
req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR
private_key_bits | integer | default_bits | Specifies how many bits should be used to generate a private key
private_key_type | integer | none | Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type.
encrypt_key | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted?

Returns TRUE on success or FALSE on failure.

Example 1. openssl_csr_new() example - creating a self-signed-certificate

&#60;?php
// Fill in data for the distinguished name to be used in the cert
// You must change the values of these keys to match your name and
// company, or more precisely, the name and company of the person/site
// that you are generating the certificate for.
// For SSL certificates, the commonName is usually the domain name of
// that will be using the certificate, but for S/MIME certificates,
// the commonName will be the name of the individual who will use the
// certificate.
$dn = array(
    "countryName" =&#62; "UK",
    "stateOrProvinceName" =&#62; "Somerset",
    "localityName" =&#62; "Glastonbury",
    "organizationName" =&#62; "The Brain Room Limited",
    "organizationalUnitName" =&#62; "PHP Documentation Team",
    "commonName" =&#62; "Wez Furlong",
    "emailAddress" =&#62; "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);

// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($sscert, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?&#62;

Prev | Home | Next
openssl_csr_get_subject | Up | openssl_csr_sign


openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate

Description

resource openssl_csr_sign ( mixed csr, mixed cacert, mixed priv_key, int days [, array configargs [, int serial]] )

openssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but it can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days. You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs. Since PHP 4.3.3 you can specify the serial number of issued certificate by serial. In earlier versions, it was always 0.

Returns an x509 certificate resource on success, FALSE on failure.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Example 1. openssl_csr_sign() example - signing a CSR (how to implement your own CA)

&#60;?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$userscert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?&#62;

Prev | Home | Next
openssl_csr_new | Up | openssl_error_string


openssl_error_string

(PHP 4 >= 4.0.6, PHP 5)

openssl_error_string -- Return openSSL error message

Description

string openssl_error_string ( void )

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

Example 1. openssl_error_string() example

&#60;?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "&#60;br /&#62;\n";
?&#62;

Prev | Home | Next
openssl_csr_sign | Up | openssl_free_key


openssl_free_key

(PHP 4 >= 4.0.4, PHP 5)

openssl_free_key -- Free key resource

Description

void openssl_free_key ( resource key_identifier )

openssl_free_key() frees the key associated with the specified key_identifier from memory.

Prev | Home | Next
openssl_error_string | Up | openssl_get_privatekey


openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_privatekey -- Alias of openssl_pkey_get_private()

Description

This function is an alias of: openssl_pkey_get_private().

Prev | Home | Next
openssl_free_key | Up | openssl_get_publickey


openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_publickey -- Alias of openssl_pkey_get_public()

Description

This function is an alias of: openssl_pkey_get_public().

Prev | Home | Next
openssl_get_privatekey | Up | openssl_open


openssl_open

(PHP 4 >= 4.0.4, PHP 5)

openssl_open -- Open sealed data

Description

bool openssl_open ( string sealed_data, string &open_data, string env_key, mixed priv_key_id )

Returns TRUE on success or FALSE on failure. If successful the opened data is returned in open_data.

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

Example 1. openssl_open() example

&#60;?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid)) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

// free the private key from memory
openssl_free_key($pkeyid);
?&#62;

See also openssl_seal().

Prev | Home | Next
openssl_get_publickey | Up | openssl_pkcs7_decrypt


openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message

Description

bool openssl_pkcs7_decrypt ( string infilename, string outfilename, mixed recipcert [, mixed recipkey] )

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey.

The decrypted message is output to the file specified by outfilename

Example 1. openssl_pkcs7_decrypt() example

&#60;?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
    echo "decrypted!";
} else {
    echo "failed to decrypt!";
}
?&#62;

Prev | Home | Next
openssl_open | Up | openssl_pkcs7_encrypt


openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_encrypt -- Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags [, int cipherid]] )

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line. Cipher can be selected with cipherid since PHP 5.

Example 1. openssl_pkcs7_encrypt() example

&#60;?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = &#60;&#60;&#60;EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" =&#62; "nighthawk@example.com", // keyed syntax
          "From: HQ &#60;hq@example.com&#62;", // indexed syntax
          "Subject" =&#62; "Eyes only"))) {
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " &#60; enc.txt");
}
?&#62;

Prev | Home | Next
openssl_pkcs7_decrypt | Up | openssl_pkcs7_sign


openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_sign -- Sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [, int flags [, string extracerts]] )

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.

headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.

flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.

extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

Example 1. openssl_pkcs7_sign() example

&#60;?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = &#60;&#60;&#60;EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("file://mycert.pem", "mypassphrase"),
    array("To" =&#62; "joes@example.com", // keyed syntax
          "From: HQ &#60;ceo@example.com&#62;", // indexed syntax
          "Subject" =&#62; "Eyes only")
    )) {
    // message signed - send it!
    exec(ini_get("sendmail_path") . " &#60; signed.txt");
}
?&#62;

Prev | Home | Next
openssl_pkcs7_encrypt | Up | openssl_pkcs7_verify


openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message

Description

mixed openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts [, string content]]]] )

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

You can specify a filename with content that will be filled with the verified data, but with the signature information stripped. This was added as of PHP 5.1.0.

Prev | Home | Next
openssl_pkcs7_sign | Up | openssl_pkey_export_to_file


openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file

Description

bool openssl_pkey_export_to_file ( mixed key, string outfilename [, string passphrase [, array configargs]] )

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename. The key can be optionally protected by a passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Returns TRUE on success or FALSE on failure.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Prev | Home | Next
openssl_pkcs7_verify | Up | openssl_pkey_export


openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export -- Gets an exportable representation of a key into a string

Description

bool openssl_pkey_export ( mixed key, string &out [, string passphrase [, array configargs]] )

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference). The key is optionally protected by passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Returns TRUE on success or FALSE on failure.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Prev | Home | Next
openssl_pkey_export_to_file | Up | openssl_pkey_free


openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_private -- Get a private key

Description

resource openssl_pkey_get_private ( mixed key [, string passphrase] )

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  2. A PEM formatted private key.

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

Prev | Home | Next
openssl_pkey_get_details | Up | openssl_pkey_get_public


openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_public -- Extract public key from certificate and prepare it for use

Description

resource openssl_pkey_get_public ( mixed certificate )

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:

  1. an X.509 certificate resource

  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  3. A PEM formatted private key.

Prev | Home | Next
openssl_pkey_get_private | Up | openssl_pkey_new


openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_new -- Generates a new private key

Description

resource openssl_pkey_new ( [array configargs] )

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Prev | Home | Next
openssl_pkey_get_public | Up | openssl_private_decrypt


openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_decrypt -- Decrypts data with private key

Description

bool openssl_private_decrypt ( string data, string &decrypted, mixed key [, int padding] )

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_public_encrypt() and stores the result into decrypted. key must be the private key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Returns TRUE on success or FALSE on failure.

You can use this function e.g. to decrypt data which were supposed only to you.

See also openssl_public_encrypt() and openssl_public_decrypt().

Prev | Home | Next
openssl_pkey_new | Up | openssl_private_encrypt


openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_encrypt -- Encrypts data with private key

Description

bool openssl_private_encrypt ( string data, string &crypted, mixed key [, int padding] )

openssl_private_encrypt() encrypts data with private key and stores the result into crypted. Encrypted data can be decrypted via openssl_public_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.

Returns TRUE on success or FALSE on failure.

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.

See also openssl_public_decrypt() and openssl_public_encrypt().

Prev | Home | Next
openssl_private_decrypt | Up | openssl_public_decrypt


openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_decrypt -- Decrypts data with public key

Description

bool openssl_public_decrypt ( string data, string &decrypted, mixed key [, int padding] )

openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted. key must be the public key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.

Returns TRUE on success or FALSE on failure.

You can use this function e.g. to check if the message was written by the owner of the private key.

See also openssl_private_encrypt() and openssl_private_decrypt().

Prev | Home | Next
openssl_private_encrypt | Up | openssl_public_encrypt


openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_encrypt -- Encrypts data with public key

Description

bool openssl_public_encrypt ( string data, string &crypted, mixed key [, int padding] )

openssl_public_encrypt() encrypts data with public key and stores the result into crypted. Encrypted data can be decrypted via openssl_private_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Returns TRUE on success or FALSE on failure.

This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

See also openssl_private_decrypt() and openssl_private_encrypt().

Prev | Home | Next
openssl_public_decrypt | Up | openssl_seal


openssl_seal

(PHP 4 >= 4.0.4, PHP 5)

openssl_seal -- Seal (encrypt) data

Description

int openssl_seal ( string data, string &sealed_data, array &env_keys, array pub_key_ids )

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Example 1. openssl_seal() example

&#60;?php
// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);
?&#62;

See also openssl_open().

Prev | Home | Next
openssl_public_encrypt | Up | openssl_sign


openssl_sign

(PHP 4 >= 4.0.4, PHP 5)

openssl_sign -- Generate signature

Description

bool openssl_sign ( string data, string &signature, mixed priv_key_id [, int signature_alg] )

Returns TRUE on success or FALSE on failure. If successful the signature is returned in signature.

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Note: Optional 4th parameter signature_alg was added in version 5.0.0. Its default value is OPENSSL_ALGO_SHA1. For more information see the list of Signature Algorithms.

Example 1. openssl_sign() example

&#60;?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?&#62;

See also openssl_verify().

Prev | Home | Next
openssl_seal | Up | openssl_verify


openssl_verify

(PHP 4 >= 4.0.4, PHP 5)

openssl_verify -- Verify signature

Description

int openssl_verify ( string data, string signature, mixed pub_key_id [, int signature_alg] )

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing.

Note: Optional 4th parameter signature_alg was added in version 5.2.0. Its default value is OPENSSL_ALGO_SHA1. For more information see the list of Signature Algorithms.

Example 1. openssl_verify() example

&#60;?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?&#62;

See also openssl_sign().

Prev | Home | Next
openssl_sign | Up | openssl_x509_check_private_key


openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate

Description

bool openssl_x509_check_private_key ( mixed cert, mixed key )

openssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

Prev | Home | Next
openssl_verify | Up | openssl_x509_checkpurpose


openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose

Description

int openssl_x509_checkpurpose ( mixed x509cert, int purpose [, array cainfo [, string untrustedfile]] )

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification. It defaults to an empty array.

untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.

Table 1. openssl_x509_checkpurpose() purposes

Constant | Description
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

Prev | Home | Next
openssl_x509_check_private_key | Up | openssl_x509_export_to_file


openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export_to_file -- Exports a certificate to file

Description

bool openssl_x509_export_to_file ( mixed x509, string outfilename [, bool notext] )

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
openssl_x509_checkpurpose | Up | openssl_x509_export


openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export -- Exports a certificate as a string

Description

bool openssl_x509_export ( mixed x509, string &output [, bool notext] )

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
openssl_x509_export_to_file | Up | openssl_x509_free


openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_free -- Free certificate resource

Description

void openssl_x509_free ( resource x509cert )

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Prev | Home | Next
openssl_x509_export | Up | openssl_x509_parse


openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_parse -- Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed x509cert [, bool shortnames] )

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

Prev | Home | Next
openssl_x509_free | Up | openssl_x509_read


openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

Description

resource openssl_x509_read ( mixed x509certdata )

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Prev | Home | Next
openssl_x509_parse | Up | Oracle Functions [deprecated]


Oracle Functions [deprecated]

PHP Manual
Prev Next

CXI. Oracle Functions [deprecated]

Introduction

Warning

This extension is deprecated. Instead, use the improved oci8 extension. Functions documented here do list recommended oci8 alternatives.

This extension adds support for Oracle database server access.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Installation

You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environment variable ORACLE_HOME.

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.

ORA_BIND_INOUT (integer)

ORA_BIND_IN (integer)

ORA_BIND_OUT (integer)

ORA_FETCHINTO_ASSOC (integer)

ORA_FETCHINTO_NULLS (integer)

Table of Contents
ora_bind -- Binds a PHP variable to an Oracle parameter
ora_close -- Closes an Oracle cursor
ora_columnname -- Gets the name of an Oracle result column
ora_columnsize -- Returns the size of an Oracle result column
ora_columntype -- Gets the type of an Oracle result column
ora_commit -- Commit an Oracle transaction
ora_commitoff -- Disable automatic commit
ora_commiton -- Enable automatic commit
ora_do -- Parse, Exec, Fetch
ora_error -- Gets an Oracle error message
ora_errorcode -- Gets an Oracle error code
ora_exec -- Execute a parsed statement on an Oracle cursor
ora_fetch_into -- Fetch a row into the specified result array
ora_fetch -- Fetch a row of data from a cursor
ora_getcolumn -- Get data from a fetched column
ora_logoff -- Close an Oracle connection
ora_logon -- Open an Oracle connection
ora_numcols -- Returns the number of columns
ora_numrows -- Returns the number of rows
ora_open -- Opens an Oracle cursor
ora_parse -- Parse an SQL statement with Oracle
ora_plogon -- Open a persistent Oracle connection
ora_rollback -- Rolls back a transaction

Prev | Home | Next
openssl_x509_read | Up | ora_bind


ora_bind

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_bind -- Binds a PHP variable to an Oracle parameter

Description

bool ora_bind ( resource cursor, string phpvar, string sqlparam, int length [, int type] )

Binds the named PHP variable with a SQL parameter.

ora_bind() must be called after ora_parse() and before ora_exec(). Input values can be given by assignment to the bound PHP variables, after calling ora_exec() the bound PHP variables contain the output values if available.

Parameters

cursor

An Oracle cursor, opened with ora_open().

phpvar

The PHP variable to be bound.

sqlparam

The SQL parameter. Must be in the form :name.

length

type

Defines the type of the parameter. It defaults to ORA_BIND_INOUT. Possible values are listed below:

Constant | Value
ORA_BIND_INOUT | 0
ORA_BIND_IN | 1
ORA_BIND_OUT | 2

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.
3.0.1 | The constants for the type were added. In previous versions, you should use the numerical values.

Examples

Example 1. ora_bind() example

&#60;?php
  ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;");
  ora_bind($curs, "result", ":x", $len, 2);
  ora_bind($curs, "input", ":in", 5, 1);
  ora_bind($curs, "output", ":out", 5, 2);
  $input = 765;
  ora_exec($curs);
  echo "Result: $result&#60;br /&#62;Out: $output&#60;br /&#62;In: $input";
?&#62;

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_bind_by_name()
oci_bind_array_by_name()

Prev | Home | Next
Oracle Functions [deprecated] | Up | ora_close


ora_close

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_close -- Closes an Oracle cursor

Description

bool ora_close ( resource cursor )

Closes a data cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_free_statement()

Prev | Home | Next
ora_bind | Up | ora_columnname


ora_columnname

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columnname -- Gets the name of an Oracle result column

Description

string ora_columnname ( resource cursor, int column )

Returns the name of the column on the cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

column

The column number. First is 0.

Return Values

Returns the name as a string. The returned name is in all uppercase letters.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_field_name()

Prev | Home | Next
ora_close | Up | ora_columnsize


ora_columnsize

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columnsize -- Returns the size of an Oracle result column

Description

int ora_columnsize ( resource cursor, int column )

Returns the size of a column on the cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

column

The column number. First is 0.

Return Values

Returns the size as an integer, or FALSE on error.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_field_size()

Prev | Home | Next
ora_columnname | Up | ora_columntype


ora_columntype

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columntype -- Gets the type of an Oracle result column

Description

string ora_columntype ( resource cursor, int column )

Returns the Oracle data type name of the column on the cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

column

The column number. First is 0.

Return Values

The returned type will be one of the following strings:

"VARCHAR2"
"VARCHAR"
"CHAR"
"NUMBER"
"LONG"
"LONG RAW"
"ROWID"
"DATE"
"CURSOR"

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_field_type()
oci_field_type_raw()

Prev | Home | Next
ora_columnsize | Up | ora_commit


ora_commit

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_commit -- Commit an Oracle transaction

Description

bool ora_commit ( resource connection )

Commits an Oracle transaction.

A transaction is defined as all the changes on a given connection since the last commit/rollback, autocommit was turned off or when the connection was established.

Parameters

connection

A connection identifier, opened with ora_logon().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_commit()

See Also

ora_commiton()
ora_commitoff()

Prev | Home | Next
ora_columntype | Up | ora_commitoff


ora_commitoff

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_commitoff -- Disable automatic commit

Description

bool ora_commitoff ( resource connection )

Turns off automatic commit after each ora_exec() on the given connection.

Parameters

connection

A connection identifier, opened with ora_logon().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

Pass the OCI_DEFAULT flag to oci_execute()

See Also

ora_commiton()
ora_commit()

Prev | Home | Next
ora_commit | Up | ora_commiton


ora_commiton

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_commiton -- Enable automatic commit

Description

bool ora_commiton ( resource conn )

Turns on automatic commit after each ora_exec() on the given connection.

Parameters

conn

A connection identifier, opened with ora_logon().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_execute()

See Also

ora_commitoff()
ora_commit()

Prev | Home | Next
ora_commitoff | Up | ora_do


ora_do

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_do -- Parse, Exec, Fetch

Description

resource ora_do ( resource connection, string query )

Parse and execute a statement, then fetch the first result row.

This function is a quick combination of ora_parse(), ora_exec() and ora_fetch().

Parameters

connection

A connection identifier, opened with ora_logon().

query

The SQL statement.

Return Values

This function returns a cursor index or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

There is no direct replacement for ora_do() in oci8. Instead, use a sequence of oci_parse(), oci_excute(), and one of the oci_fetch_*() functions.

See Also

ora_parse()
ora_exec()
ora_fetch()

Prev | Home | Next
ora_commiton | Up | ora_error


ora_error

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_error -- Gets an Oracle error message

Description

string ora_error ( [resource cursor_or_connection] )

Returns the error message of the last executed statement on the specified cursor or connection.

Parameters

cursor_or_connection

An Oracle cursor or connection identifier.

Return Values

Returns an error message of the form XXX-NNNNN where XXX is where the error comes from and NNNNN identifies the error message.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.
3.0.4 | Support for connection identifiers was added.

Examples

On Unix versions of Oracle, you can find details about an error message like this:

$> oerr ora 00001

The above example will output something similar to:

00001, 00000,
"unique constraint (%s.%s) violated" // *Cause: An update or insert
statement attempted to insert a duplicate key //         For Trusted
ORACLE configured in DBMS MAC mode, you may see //         this message
if a duplicate entry exists at a different level.  // *Action: Either
remove the unique restriction or do not insert the key

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_error()

Prev | Home | Next
ora_do | Up | ora_errorcode


ora_errorcode

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_errorcode -- Gets an Oracle error code

Description

int ora_errorcode ( [resource cursor_or_connection] )

Returns the numeric error code of the last executed statement on the specified cursor or connection.

Parameters

cursor_or_connection

An Oracle cursor or connection identifier.

Return Values

Returns the error code, as an integer.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.
3.0.4 | Support for connection identifiers was added.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_error() (the "code" field of the resulting array)

Prev | Home | Next
ora_error | Up | ora_exec


ora_exec

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_exec -- Execute a parsed statement on an Oracle cursor

Description

bool ora_exec ( resource cursor )

Executes the parsed statement cursor.

Parameters

cursor

An Oracle cursor, already parsed by ora_parse().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_execute()

See Also

ora_parse()
ora_fetch()
ora_do()

Prev | Home | Next
ora_errorcode | Up | ora_fetch_into


ora_fetch_into

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_fetch_into -- Fetch a row into the specified result array

Description

int ora_fetch_into ( resource cursor, array &result [, int flags] )

Fetches a row of data into an array.

Parameters

cursor

An Oracle cursor, opened with ora_open().

result

An array passed by reference. It will be filled with the fetched values.

flags

There are two possible flags. If ORA_FETCHINTO_NULLS is set, columns with NULL values are set in the array; and if the ORA_FETCHINTO_ASSOC flag is set, an associative array is created.

Return Values

Returns the number of columns fetched, or FALSE on error.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Examples

Example 1. ora_fetch_into()

&#60;?php
$results = array();
ora_fetch_into($cursor, $results);
echo $results[0];
echo $results[1];
$results = array();
ora_fetch_into($cursor, $results, ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
echo $results['MyColumn'];
?&#62;

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

A fetch function like oci_fetch_array()

See Also

ora_parse()
ora_exec()
ora_fetch()
ora_do()

Prev | Home | Next
ora_exec | Up | ora_fetch


ora_fetch

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_fetch -- Fetch a row of data from a cursor

Description

bool ora_fetch ( resource cursor )

Retrieves a row of data from the specified cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

Return Values

Returns TRUE (a row was fetched) or FALSE (no more rows, or an
error occurred). If an error occurred, details can be retrieved
using the ora_error() and
ora_errorcode() functions. If there was no
error, ora_errorcode() will return 0.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_fetch()

See Also

ora_parse()
ora_exec()
ora_do()

Prev | Home | Next
ora_fetch_into | Up | ora_getcolumn


ora_getcolumn

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_getcolumn -- Get data from a fetched column

Description

string ora_getcolumn ( resource cursor, int column )

Fetches the data for a column or function result.

Parameters

cursor

An Oracle cursor, opened with ora_open().

column

The column number, as an integer.

Return Values

Returns the column data. If an error occurs, FALSE is returned and ora_errorcode() will return a non-zero value. Note, however, that a test for FALSE on the results from this function may be TRUE in cases where there is not error as well (NULL result, empty string, the number 0, the string "0").

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_result()

Prev | Home | Next
ora_fetch | Up | ora_logoff


ora_logoff

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_logoff -- Close an Oracle connection

Description

bool ora_logoff ( resource connection )

Logs out the user and disconnects from the server.

Parameters

connection

A connection identifier, opened with ora_logon().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_close()

See Also

ora_logon()

Prev | Home | Next
ora_getcolumn | Up | ora_logon


ora_logon

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_logon -- Open an Oracle connection

Description

resource ora_logon ( string user, string password )

Establishes a connection between PHP and an Oracle database.

Connections can be made using SQL*Net by supplying the TNS name to user like this:

&#60;?php
$conn = Ora_Logon("user@TNSNAME", "pass");
?&#62;

If you have character data with non-ASCII characters, you should make sure that NLS_LANG is set in your environment. For server modules, you should set it in the server's environment before starting the server.

Parameters

user

The user name.

password

The password associated with user.

Return Values

Returns a connection identifier on success, or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_connect()
oci_new_connect()

Prev | Home | Next
ora_logoff | Up | ora_numcols


ora_numcols

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_numcols -- Returns the number of columns

Description

int ora_numcols ( resource cursor )

Returns the number of columns in a result. It only returns meaningful values after a parse/exec/fetch sequence.

Parameters

cursor

An Oracle cursor, opened with ora_open().

Return Values

Returns the number of columns as an integer, or FALSE on error.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_num_fields()

See Also

ora_parse()
ora_exec()
ora_fetch()
ora_do()

Prev | Home | Next
ora_logon | Up | ora_numrows


ora_numrows

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_numrows -- Returns the number of rows

Description

int ora_numrows ( resource cursor )

Returns the number of rows in a result.

Parameters

cursor

An Oracle cursor, opened with ora_open().

Return Values

Returns the number of rows as an integer, or FALSE on error.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_num_rows()

Prev | Home | Next
ora_numcols | Up | ora_open


ora_open

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_open -- Opens an Oracle cursor

Description

resource ora_open ( resource connection )

Opens an Oracle cursor associated with connection.

Parameters

connection

A connection identifier, opened with ora_logon().

Return Values

Returns a cursor index or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_new_cursor()

Prev | Home | Next
ora_numrows | Up | ora_parse


ora_parse

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_parse -- Parse an SQL statement with Oracle

Description

bool ora_parse ( resource cursor, string sql_statement [, int defer] )

Parses an SQL statement or a PL/SQL block and associates it with the given cursor.

Parameters

cursor

An Oracle cursor, opened with ora_open().

sql_statement

The SQL statement, or PL/SQL block.

defer

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_parse()

See Also

ora_exec()
ora_fetch()
ora_do()

Prev | Home | Next
ora_open | Up | ora_plogon


ora_plogon

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_plogon -- Open a persistent Oracle connection

Description

resource ora_plogon ( string user, string password )

Establishes a persistent connection between PHP and an Oracle database/

Parameters

user

The user name.

password

The password associated with user.

Return Values

Returns a persistent connection identifier, or FALSE on error.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_pconnect()

See Also

ora_logon()

Prev | Home | Next
ora_parse | Up | ora_rollback


ora_rollback

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_rollback -- Rolls back a transaction

Description

bool ora_rollback ( resource connection )

Rollbacks an Oracle transaction.

See ora_commit() for the definition of a transaction.

Parameters

connection

A connection identifier, opened with ora_logon().

Return Values

Returns TRUE on success or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

ChangeLog

Version | Description
5.1.0 | The oracle extension is deprecated in favor of oci8.

Notes

When using oci8 as a replacement for the deprecated oracle extension, consider using:

oci_rollback()

Prev | Home | Next
ora_plogon | Up | Oracle Functions (PDO_OCI)


Output Control Functions

PHP Manual
Prev Next

CXIII. Output Control Functions

Introduction

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

Note: When upgrading from PHP 4.1 (and 4.2) to 4.3 due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.

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. Output Control configuration options

Name | Default | Changeable | Changelog
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4.
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Note:
      You cannot use both mb_output_handler() with
      ob_iconv_handler() and you cannot use both
      ob_gzhandler() and
      zlib.output_compression.

Note: Only built-in functions can be used with this directive. For user defined functions, use ob_start().

implicit_flush boolean

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

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

See also ob_implicit_flush().

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

Example 1. Output Control example

&#60;?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?&#62;

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

See Also

See also header() and setcookie().

Table of Contents
flush -- Flush the output buffer
ob_clean -- Clean (erase) the output buffer
ob_end_clean -- Clean (erase) the output buffer and turn off output buffering
ob_end_flush -- Flush (send) the output buffer and turn off output buffering
ob_flush -- Flush (send) the output buffer
ob_get_clean -- Get current buffer contents and delete current output buffer
ob_get_contents -- Return the contents of the output buffer
ob_get_flush -- Flush the output buffer, return it as a string and turn off output buffering
ob_get_length -- Return the length of the output buffer
ob_get_level -- Return the nesting level of the output buffering mechanism
ob_get_status -- Get status of output buffers
ob_gzhandler -- ob_start callback function to gzip output buffer
ob_implicit_flush -- Turn implicit flush on/off
ob_list_handlers -- List all output handlers in use
ob_start -- Turn on output buffering
output_add_rewrite_var -- Add URL rewriter values
output_reset_rewrite_vars -- Reset URL rewriter values

Prev | Home | Next
PDO_OCI DSN | Up | flush


flush

(PHP 3, PHP 4, PHP 5)

flush -- Flush the output buffer

Description

void flush ( void )

Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.

flush() has no effect on the buffering scheme of your webserver or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

Prev | Home | Next
Output Control Functions | Up | ob_clean


ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_clean -- Clean (erase) the output buffer

Description

void ob_clean ( void )

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

See also ob_flush(),
ob_end_flush() and
ob_end_clean().

Prev | Home | Next
flush | Up | ob_end_clean


ob_end_clean

(PHP 4, PHP 5)

ob_end_clean -- Clean (erase) the output buffer and turn off output buffering

Description

bool ob_end_clean ( void )

This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

The following example shows an easy way to get rid of all output buffers:

Example 1. ob_end_clean() example

&#60;?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?&#62;

Note: If the function fails it generates an E_NOTICE.

The boolean return value was added in PHP 4.2.0.

See also ob_start(),
ob_get_contents(), and
ob_flush().

Prev | Home | Next
ob_clean | Up | ob_end_flush


ob_end_flush

(PHP 4, PHP 5)

ob_end_flush -- Flush (send) the output buffer and turn off output buffering

Description

bool ob_end_flush ( void )

This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

The following example shows an easy way to flush and end all output buffers:

Example 1. ob_end_flush() example

&#60;?php
  while (@ob_end_flush());
?&#62;

Note: If the function fails it generates an E_NOTICE.

The boolean return value was added in PHP 4.2.0.

See also ob_start(),
ob_get_contents(),
ob_get_flush(),
ob_flush() and
ob_end_clean().

Prev | Home | Next
ob_end_clean | Up | ob_flush


ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flush -- Flush (send) the output buffer

Description

void ob_flush ( void )

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

See also ob_get_contents(),
ob_clean(),
ob_end_flush() and
ob_end_clean().

Prev | Home | Next
ob_end_flush | Up | ob_get_clean


ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_clean -- Get current buffer contents and delete current output buffer

Description

string ob_get_clean ( void )

This will return the contents of the output buffer and end output
buffering.  If output buffering isn't active then FALSE is returned.
ob_get_clean() essentially executes both
ob_get_contents() and
ob_end_clean().

Example 1. A simple ob_get_clean() example

&#60;?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?&#62;

Our example will output:

string(11) "hello world"

See also ob_start() and ob_get_contents().

Prev | Home | Next
ob_flush | Up | ob_get_contents


ob_get_contents

(PHP 4, PHP 5)

ob_get_contents -- Return the contents of the output buffer

Description

string ob_get_contents ( void )

This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn't active.

Example 1. A simple ob_get_contents() example

&#60;?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?&#62;

Our example will output:

string(6) "Hello "
string(11) "Hello World"

See also ob_start() and ob_get_length().

Prev | Home | Next
ob_get_clean | Up | ob_get_flush


ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flush -- Flush the output buffer, return it as a string and turn off output buffering

Description

string ob_get_flush ( void )

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering. ob_get_flush() returns FALSE if no buffering is active.

Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

Example 1. ob_get_flush() example

&#60;?php
//using output_buffering=On
print_r(ob_list_handlers());

//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);

print_r(ob_list_handlers());
?&#62;

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
)

See also ob_end_clean(),
ob_end_flush() and
ob_list_handlers().

Prev | Home | Next
ob_get_contents | Up | ob_get_length


ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_length -- Return the length of the output buffer

Description

int ob_get_length ( void )

This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.

Example 1. A simple ob_get_length() example

&#60;?php

ob_start();

echo "Hello ";

$len1 = ob_get_length();

echo "World";

$len2 = ob_get_length();

ob_end_clean();

echo $len1 . ", ." . $len2;
?&#62;

Our example will output:

6, 11

See also ob_start() and ob_get_contents().

Prev | Home | Next
ob_get_flush | Up | ob_get_level


ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_level -- Return the nesting level of the output buffering mechanism

Description

int ob_get_level ( void )

This will return the level of nested output buffering handlers or zero if output buffering is not activated.

See also ob_start() and ob_get_contents().

Prev | Home | Next
ob_get_length | Up | ob_get_status


ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_status -- Get status of output buffers

Description

array ob_get_status ( [bool full_status=FALSE] )

ob_get_status() returns status information on either the top level output buffer or all active output buffer levels if full_status is set to TRUE.

If called without the full_status parameter or with full_status = FALSE a simple array with the following elements is returned:

Example 1. Simple ob_get_status() output

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)

Simple ob_get_status() results

Key: level

Value: Output nesting level

Key: type

Value: PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)

Key: status

Value: One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)

Key: name

Value: Name of active output handler or ' default output handler' if none is set

Key: del

Value: Erase-flag as set by ob_start()

If called with full_status = TRUE an array with one element for each active output buffer level is returned. The output level is used as key of the top level array and each array element itself is another array holding status information on one active output level.

Example 2. Full ob_get_status() output

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

The full output contains these additional elements:

Full ob_get_status() results

Key: chunk_size

Value: Chunk size as set by ob_start()

Key: size

Value: ...

Key: blocksize

Value: ...

See also ob_get_level() and ob_list_handlers().

Prev | Home | Next
ob_get_level | Up | ob_gzhandler


ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandler -- ob_start callback function to gzip output buffer

Description

string ob_gzhandler ( string buffer, int mode )

Note: ob_gzhandler() requires the zlib extension.

ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages. If a browser doesn't support compressed pages this function returns FALSE.

Note: mode was added in PHP 4.0.5.

Example 1. ob_gzhandler() example

&#60;?php

ob_start("ob_gzhandler");

?&#62;
&#60;html&#62;
&#60;body&#62;
&#60;p&#62;This should be a compressed page.&#60;/p&#62;
&#60;/html&#62;
&#60;body&#62;

Note: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().

See also ob_start() and ob_end_flush().

Prev | Home | Next
ob_get_status | Up | ob_implicit_flush


ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flush -- Turn implicit flush on/off

Description

void ob_implicit_flush ( [int flag] )

ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

See also flush(),
ob_start(), and
ob_end_flush().

Prev | Home | Next
ob_gzhandler | Up | ob_list_handlers


ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlers -- List all output handlers in use

Description

array ob_list_handlers ( void )

This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".

Example 1. ob_list_handlers() example

&#60;?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(create_function('$string', 'return $string;'));
print_r(ob_list_handlers());
ob_end_flush();
?&#62;

The above example will output:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => default output handler
)

See also
ob_end_clean(),
ob_end_flush(),
ob_get_flush(),
ob_start().

Prev | Home | Next
ob_implicit_flush | Up | ob_start


ob_start

(PHP 4, PHP 5)

ob_start -- Turn on output buffering

Description

bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] )

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE. If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END. If output_callback returns FALSE original input is sent to the browser.

Note: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.

Note: Before PHP 4.3.2 this function did not return FALSE in case the passed output_callback can not be executed.

Warning

Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value.

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes (as of PHP 4.3.0).

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.

Example 1. User defined callback function example

&#60;?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?&#62;
&#60;html&#62;
&#60;body&#62;
&#60;p&#62;It's like comparing apples to oranges.&#60;/p&#62;
&#60;/body&#62;
&#60;/html&#62;
&#60;?php

ob_end_flush();

?&#62;

Would produce:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

See also ob_get_contents(),
ob_end_flush(),
ob_end_clean(),
ob_implicit_flush(),
ob_gzhandler(), ob_iconv_handler()
mb_output_handler(), and
ob_tidyhandler().

Prev | Home | Next
ob_list_handlers | Up | output_add_rewrite_var


output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_var -- Add URL rewriter values

Description

bool output_add_rewrite_var ( string name, string value )

This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid. Please note that absolute URLs (http://example.com/..) aren't rewritten.

This functions behavior is controlled by the url_rewriter.tags php.ini parameter.

Note: Calling this function will implicitly start output buffering if it is not active already.

Example 1. output_add_rewrite_var() example

&#60;?php
output_add_rewrite_var('var', 'value');

// some links
echo '&#60;a href="file.php"&#62;link&#60;/a&#62;
&#60;a href="http://example.com"&#62;link2&#60;/a&#62;';

// a form
echo '&#60;form action="script.php" method="post"&#62;
&#60;input type="text" name="var2" /&#62;
&#60;/form&#62;';

print_r(ob_list_handlers());
?&#62;

The above example will output:

<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

See also
output_reset_rewrite_vars(),
ob_flush() and
ob_list_handlers().

Prev | Home | Next
ob_start | Up | output_reset_rewrite_vars


output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_vars -- Reset URL rewriter values

Description

bool output_reset_rewrite_vars ( void )

This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function or the session mechanism (if session.use_trans_sid was set on session_start()).

Example 1. output_reset_rewrite_vars() example

&#60;?php
session_start();
output_add_rewrite_var('var', 'value');

echo '&#60;a href="file.php"&#62;link&#60;/a&#62;';
ob_flush();

output_reset_rewrite_vars();
echo '&#60;a href="file.php"&#62;link&#60;/a&#62;';
?&#62;

The above example will output:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

See also
output_add_rewrite_var(),
ob_flush(),
ob_list_handlers() and
session_start().

Prev | Home | Next
output_add_rewrite_var | Up | Ovrimos SQL Functions


Object property and method call overloading

PHP Manual
Prev Next

CIV. Object property and method call overloading

Introduction

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

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.

Warning

This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.

Requirements

No external libraries are needed to build this extension.

Installation

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.

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 overload 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.

Examples

Some simple examples on using the overload() function:

Example 1. Overloading a PHP class

&#60;?php

class OO {
    var $a = 111;
    var $elem = array('b' =&#62; 9, 'c' =&#62; 42);

    // Callback method for getting a property
    function __get($prop_name, &#38;$prop_value)
    {
        if (isset($this-&#62;elem[$prop_name])) {
            $prop_value = $this-&#62;elem[$prop_name];
            return true;
        } else {
            return false;
        }
    }

    // Callback method for setting a property
    function __set($prop_name, $prop_value)
    {
        $this-&#62;elem[$prop_name] = $prop_value;
        return true;
    }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo "\$o-&#62;a: $o-&#62;a\n"; // print: $o-&#62;a: 111
echo "\$o-&#62;b: $o-&#62;b\n"; // print: $o-&#62;b: 9
echo "\$o-&#62;c: $o-&#62;c\n"; // print: $o-&#62;c: 42
echo "\$o-&#62;d: $o-&#62;d\n"; // print: $o-&#62;d:

// add a new item to the $elem array in OO
$o-&#62;x = 56;

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val-&#62;prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o-&#62;a = array($val);
var_dump($o-&#62;a[0]-&#62;prop);

?&#62;

Table of Contents
overload -- Enable property and method call overloading for a class

Prev | Home | Next
deaggregate | Up | overload


overload

(PHP 4 >= 4.2.0)

overload -- Enable property and method call overloading for a class

Description

void overload ( string class_name )

The overload() function will enable property and method call overloading for a class identified by class_name.

Parameters

class_name

The overloaded class name, as a string

Return Values

No value is returned.

Examples

See an example in the introductory section of this part.

Prev | Home | Next
Object property and method call overloading | Up | Oracle Functions


Ovrimos SQL Functions

PHP Manual
Prev Next

CXIV. Ovrimos SQL Functions

Introduction

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 4.4.5 and PHP 5.1.0.

Note: This extension is not available on Windows platforms.

Requirements

You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.

Installation

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Examples

Example 1. Connect to Ovrimos SQL Server and select from a system table

&#60;?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?&#62;
This will just connect to an Ovrimos SQL server.

Table of Contents
ovrimos_close -- Closes the connection to ovrimos
ovrimos_commit -- Commits the transaction
ovrimos_connect -- Connect to the specified database
ovrimos_cursor -- Returns the name of the cursor
ovrimos_exec -- Executes an SQL statement
ovrimos_execute -- Executes a prepared SQL statement
ovrimos_fetch_into -- Fetches a row from the result set
ovrimos_fetch_row -- Fetches a row from the result set
ovrimos_field_len -- Returns the length of the output column
ovrimos_field_name -- Returns the output column name
ovrimos_field_num -- Returns the (1-based) index of the output column
ovrimos_field_type -- Returns the type of the output column
ovrimos_free_result -- Frees the specified result_id
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypes
ovrimos_num_fields -- Returns the number of columns
ovrimos_num_rows -- Returns the number of rows affected by update operations
ovrimos_prepare -- Prepares an SQL statement
ovrimos_result_all -- Prints the whole result set as an HTML table
ovrimos_result -- Retrieves the output column
ovrimos_rollback -- Rolls back the transaction

Prev | Home | Next
output_reset_rewrite_vars | Up | ovrimos_close


ovrimos_close

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_close -- Closes the connection to ovrimos

Description

void ovrimos_close ( int connection )

Closes the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

Parameters

connection

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

No value is returned.

Prev | Home | Next
Ovrimos SQL Functions | Up | ovrimos_commit


ovrimos_commit

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_commit -- Commits the transaction

Description

bool ovrimos_commit ( int connection_id )

Commits the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ovrimos_close | Up | ovrimos_connect


ovrimos_connect

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_connect -- Connect to the specified database

Description

int ovrimos_connect ( string host, string dborport, string user, string password )

Connects to the specified database.

Parameters

host

A host name or IP address.

dborport

Either a database name, or the port number to connect to.

user

The user name.

password

Password associated with user.

Return Values

Returns a connection identifier (greater than 0) on success, or 0 on failure.

Examples

Example 1. ovrimos_connect() Example

&#60;?php
$conn = ovrimos_connect("server.example.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?&#62;

Prev | Home | Next
ovrimos_commit | Up | ovrimos_cursor


ovrimos_cursor

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_cursor -- Returns the name of the cursor

Description

string ovrimos_cursor ( int result_id )

Gets the name of the cursor. Useful when wishing to perform positioned updates or deletes.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the name as a string, or FALSE on error.

Prev | Home | Next
ovrimos_connect | Up | ovrimos_exec


ovrimos_exec

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_exec -- Executes an SQL statement

Description

int ovrimos_exec ( int connection_id, string query )

Executes an SQL statement (query or update) and returns a result identifier.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement. Evidently, it should not contain parameters. Use ovrimos_prepare() for prepared statements.

Return Values

Returns the result identifier as an integer, or FALSE on error.

Prev | Home | Next
ovrimos_cursor | Up | ovrimos_execute


ovrimos_execute

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_execute -- Executes a prepared SQL statement

Description

bool ovrimos_execute ( int result_id [, array parameters_array] )

Executes a prepared statement.

Parameters

result_id

An Ovrimos result identifier prepared with ovrimos_prepare().

parameters_array

If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ovrimos_exec | Up | ovrimos_fetch_into


ovrimos_fetch_into

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_fetch_into -- Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int result_id, array &result_array [, string how [, int rownumber]] )

Fetches a row from the given result set, into result_array.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

result_array

You must provide an array by reference. It will be filled with the fetched values.

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber.

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A fetch into example

&#60;?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into($res, &#38;$row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, &#38;$row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?&#62;

Prev | Home | Next
ovrimos_execute | Up | ovrimos_fetch_row


ovrimos_fetch_row

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_fetch_row -- Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int result_id [, int how [, int row_number]] )

Fetches a row from the result set. Column values should be retrieved with other calls.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber.

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A fetch row example

&#60;?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?&#62;
This will fetch a row and print the result.

Prev | Home | Next
ovrimos_fetch_into | Up | ovrimos_field_len


ovrimos_field_len

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_len -- Returns the length of the output column

Description

int ovrimos_field_len ( int result_id, int field_number )

Gets the length of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the length as an interger, or FALSE on error.

Prev | Home | Next
ovrimos_fetch_row | Up | ovrimos_field_name


ovrimos_field_name

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_name -- Returns the output column name

Description

string ovrimos_field_name ( int result_id, int field_number )

Returns the output column name at the index specified.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

Prev | Home | Next
ovrimos_field_len | Up | ovrimos_field_num


ovrimos_field_num

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_num -- Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int result_id, string field_name )

Returns the 1-based index of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_name

The field name.

Return Values

Returns the index, starting at 1, or FALSE on error.

Prev | Home | Next
ovrimos_field_name | Up | ovrimos_field_type


ovrimos_field_type

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_type -- Returns the type of the output column

Description

int ovrimos_field_type ( int result_id, int field_number )

Returns the type of the output column

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

A 1-based index.

Return Values

Returns the field type as an integer, or FALSE on error.

Prev | Home | Next
ovrimos_field_num | Up | ovrimos_free_result


ovrimos_free_result

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_free_result -- Frees the specified result_id

Description

bool ovrimos_free_result ( int result_id )

Frees the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns TRUE.

Prev | Home | Next
ovrimos_field_type | Up | ovrimos_longreadlen


ovrimos_longreadlen

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypes

Description

bool ovrimos_longreadlen ( int result_id, int length )

Specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary).

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

length

The number of bytes to retrieve. Default is zero.

Return Values

Returns TRUE.

Prev | Home | Next
ovrimos_free_result | Up | ovrimos_num_fields


ovrimos_num_fields

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_num_fields -- Returns the number of columns

Description

int ovrimos_num_fields ( int result_id )

Returns the number of columns in the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of columns as an integer, or FALSE on error.

Prev | Home | Next
ovrimos_longreadlen | Up | ovrimos_num_rows


ovrimos_num_rows

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_num_rows -- Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int result_id )

Gets the number of rows affected by update operations.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of rows as an integer, or FALSE on error.

Prev | Home | Next
ovrimos_num_fields | Up | ovrimos_prepare


ovrimos_prepare

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_prepare -- Prepares an SQL statement

Description

int ovrimos_prepare ( int connection_id, string query )

Prepares an SQL statement.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement.

Return Values

Returns a result identifier on success, or FALSE on error.

Examples

Example 1. ovrimos_prepare() Example

&#60;?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";

    // Prepare the statement
    $res=ovrimos_prepare($conn, "select table_id, table_name
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        // Execute the prepared statement
        if (ovrimos_execute($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?&#62;

Prev | Home | Next
ovrimos_num_rows | Up | ovrimos_result_all


ovrimos_result_all

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_result_all -- Prints the whole result set as an HTML table

Description

int ovrimos_result_all ( int result_id [, string format] )

Prints the whole result set as an HTML table.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

format

Optional HTML attributes for the generated table element.

Return Values

Returns the number of rows in the generated table.

Examples

This will execute an SQL statement and print the result in an HTML table.

Example 1. Prepare a statement, execute, and view the result

&#60;?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare($conn, "select table_id, table_name
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?&#62;

Example 2. ovrimos_result_all() with meta-information

&#60;?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Statement ok! cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Output columns=" . $colnb . "\n";
        for ($i=1; $i &#60;= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);
            echo "Column " . $i . " name=" . $name . " type=" . $type . " len=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?&#62;

Prev | Home | Next
ovrimos_prepare | Up | ovrimos_result


ovrimos_result

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_result -- Retrieves the output column

Description

string ovrimos_result ( int result_id, mixed field )

Retrieves the output column specified by field.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field

Either as a string with the field name or as an 1-based index.

Return Values

Returns the column as a string, FALSE on failure.

Prev | Home | Next
ovrimos_result_all | Up | ovrimos_rollback


ovrimos_rollback

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_rollback -- Rolls back the transaction

Description

bool ovrimos_rollback ( int connection_id )

Rolls back the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ovrimos_result | Up | Paradox File Access


Parsekit Functions

PHP Manual
Prev Next

CXVI. Parsekit Functions

Introduction

These functions allow runtime analysis of opcodes compiled from PHP scripts.

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/parsekit.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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.

PARSEKIT_QUIET (int)

Return full detail, but without unnecessary NULL entries.

PARSEKIT_SIMPLE (int)

Return shorthand opcode notation.

PARSEKIT_EXTENDED_VALUE (int)

Opnode Flag

PARSEKIT_RESULT_CONST (int)

Opnode Flag

PARSEKIT_RESULT_EA_TYPE (int)

Opnode Flag

PARSEKIT_RESULT_JMP_ADDR (int)

Opnode Flag

PARSEKIT_RESULT_OPARRAY (int)

Opnode Flag

PARSEKIT_RESULT_OPLINE (int)

Opnode Flag

PARSEKIT_RESULT_VAR (int)

Opnode Flag

PARSEKIT_USAGE_UNKNOWN (int)

Opnode Flag

PARSEKIT_ZEND_INTERNAL_CLASS (int)

Class Type

PARSEKIT_ZEND_USER_CLASS (int)

Class Type

PARSEKIT_ZEND_EVAL_CODE (int)

Function Type

PARSEKIT_ZEND_INTERNAL_FUNCTION (int)

Function Type

PARSEKIT_ZEND_OVERLOADED_FUNCTION (int)

Function Type

PARSEKIT_ZEND_OVERLOADED_FUNCTION_TEMPORARY (int) PHP >= 5.0.0

Function Type

PARSEKIT_ZEND_USER_FUNCTION (int)

Function Type

PARSEKIT_IS_CONST (int)

Node Type

PARSEKIT_IS_TMP_VAR (int)

Node Type

PARSEKIT_IS_UNUSED (int)

Node Type

PARSEKIT_IS_VAR (int)

Node Type

PARSEKIT_ZEND_ADD (int)

Opcode

PARSEKIT_ZEND_ADD_ARRAY_ELEMENT (int)

Opcode

PARSEKIT_ZEND_ADD_CHAR (int)

Opcode

PARSEKIT_ZEND_ADD_INTERFACE (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ADD_STRING (int)

Opcode

PARSEKIT_ZEND_ADD_VAR (int)

Opcode

PARSEKIT_ZEND_ASSIGN (int)

Opcode

PARSEKIT_ZEND_ASSIGN_ADD (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_AND (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_OR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_XOR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_CONCAT (int)

Opcode

PARSEKIT_ZEND_ASSIGN_DIM (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ASSIGN_DIV (int)

Opcode

PARSEKIT_ZEND_ASSIGN_MOD (int)

Opcode

PARSEKIT_ZEND_ASSIGN_MUL (int)

Opcode

PARSEKIT_ZEND_ASSIGN_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ASSIGN_REF (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SL (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SUB (int)

Opcode

PARSEKIT_ZEND_BEGIN_SILENCE (int)

Opcode

PARSEKIT_ZEND_BOOL (int)

Opcode

PARSEKIT_ZEND_BOOL_NOT (int)

Opcode

PARSEKIT_ZEND_BOOL_XOR (int)

Opcode

PARSEKIT_ZEND_BRK (int)

Opcode

PARSEKIT_ZEND_BW_AND (int)

Opcode

PARSEKIT_ZEND_BW_NOT (int)

Opcode

PARSEKIT_ZEND_BW_OR (int)

Opcode

PARSEKIT_ZEND_BW_XOR (int)

Opcode

PARSEKIT_ZEND_CASE (int)

Opcode

PARSEKIT_ZEND_CAST (int)

Opcode

PARSEKIT_ZEND_CATCH (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_CLONE (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_CONCAT (int)

Opcode

PARSEKIT_ZEND_CONT (int)

Opcode

PARSEKIT_ZEND_DECLARE_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DECLARE_FUNCTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DECLARE_INHERITED_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DIV (int)

Opcode

PARSEKIT_ZEND_DO_FCALL (int)

Opcode

PARSEKIT_ZEND_DO_FCALL_BY_NAME (int)

Opcode

PARSEKIT_ZEND_ECHO (int)

Opcode

PARSEKIT_ZEND_END_SILENCE (int)

Opcode

PARSEKIT_ZEND_EXIT (int)

Opcode

PARSEKIT_ZEND_EXT_FCALL_BEGIN (int)

Opcode

PARSEKIT_ZEND_EXT_FCALL_END (int)

Opcode

PARSEKIT_ZEND_EXT_NOP (int)

Opcode

PARSEKIT_ZEND_EXT_STMT (int)

Opcode

PARSEKIT_ZEND_FETCH_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_FETCH_CONSTANT (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_R (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_TMP_VAR (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_W (int)

Opcode

PARSEKIT_ZEND_FETCH_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_R (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_W (int)

Opcode

PARSEKIT_ZEND_FETCH_R (int)

Opcode

PARSEKIT_ZEND_FETCH_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_W (int)

Opcode

PARSEKIT_ZEND_FE_FETCH (int)

Opcode

PARSEKIT_ZEND_FE_RESET (int)

Opcode

PARSEKIT_ZEND_FREE (int)

Opcode

PARSEKIT_ZEND_HANDLE_EXCEPTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_CONST (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_FUNCTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INCLUDE_OR_EVAL (int)

Opcode

PARSEKIT_ZEND_INIT_ARRAY (int)

Opcode

PARSEKIT_ZEND_INIT_CTOR_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_FCALL_BY_NAME (int)

Opcode

PARSEKIT_ZEND_INIT_METHOD_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_STATIC_METHOD_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_STRING (int)

Opcode

PARSEKIT_ZEND_INSTANCEOF (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY (int) PHP < 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_DIM_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_PROP_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_VAR (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IS_EQUAL (int)

Opcode

PARSEKIT_ZEND_IS_IDENTICAL (int)

Opcode

PARSEKIT_ZEND_IS_NOT_EQUAL (int)

Opcode

PARSEKIT_ZEND_IS_NOT_IDENTICAL (int)

Opcode

PARSEKIT_ZEND_IS_SMALLER (int)

Opcode

PARSEKIT_ZEND_IS_SMALLER_OR_EQUAL (int)

Opcode

PARSEKIT_ZEND_JMP (int)

Opcode

PARSEKIT_ZEND_JMPNZ (int)

Opcode

PARSEKIT_ZEND_JMPNZ_EX (int)

Opcode

PARSEKIT_ZEND_JMPZ (int)

Opcode

PARSEKIT_ZEND_JMPZNZ (int)

Opcode

PARSEKIT_ZEND_JMPZ_EX (int)

Opcode

PARSEKIT_ZEND_JMP_NO_CTOR (int)

Opcode

PARSEKIT_ZEND_MOD (int)

Opcode

PARSEKIT_ZEND_MUL (int)

Opcode

PARSEKIT_ZEND_NEW (int)

Opcode

PARSEKIT_ZEND_NOP (int)

Opcode

PARSEKIT_ZEND_OP_DATA (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_POST_DEC (int)

Opcode

PARSEKIT_ZEND_POST_DEC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_POST_INC (int)

Opcode

PARSEKIT_ZEND_POST_INC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRE_DEC (int)

Opcode

PARSEKIT_ZEND_PRE_DEC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRE_INC (int)

Opcode

PARSEKIT_ZEND_PRE_INC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRINT (int)

Opcode

PARSEKIT_ZEND_QM_ASSIGN (int)

Opcode

PARSEKIT_ZEND_RAISE_ABSTRACT_ERROR (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_RECV (int)

Opcode

PARSEKIT_ZEND_RECV_INIT (int)

Opcode

PARSEKIT_ZEND_RETURN (int)

Opcode

PARSEKIT_ZEND_SEND_REF (int)

Opcode

PARSEKIT_ZEND_SEND_VAL (int)

Opcode

PARSEKIT_ZEND_SEND_VAR (int)

Opcode

PARSEKIT_ZEND_SEND_VAR_NO_REF (int)

Opcode

PARSEKIT_ZEND_SL (int)

Opcode

PARSEKIT_ZEND_SR (int)

Opcode

PARSEKIT_ZEND_SUB (int)

Opcode

PARSEKIT_ZEND_SWITCH_FREE (int)

Opcode

PARSEKIT_ZEND_THROW (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_TICKS (int)

Opcode

PARSEKIT_ZEND_UNSET_DIM_OBJ (int)

Opcode

PARSEKIT_ZEND_UNSET_VAR (int)

Opcode

PARSEKIT_ZEND_VERIFY_ABSTRACT_CLASS (int) PHP >= 5.0.0

Opcode

Table of Contents
parsekit_compile_file -- Compile a string of PHP code and return the resulting op array
parsekit_compile_string -- Compile a string of PHP code and return the resulting op array
parsekit_func_arginfo -- Return information regarding function argument(s)

Prev | Home | Next
px_update_record | Up | parsekit_compile_file


parsekit_compile_file

(PECL)

parsekit_compile_file -- Compile a string of PHP code and return the resulting op array

Description

array parsekit_compile_file ( string filename [, array &errors [, int options]] )

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

A string containing the name of the file to compile. Similar to the argument to include().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example 1. parsekit_compile_file() example

&#60;?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?&#62;

The above example will output:

array(5) {
  [0]=>
  string(37) "ZEND_ECHO UNUSED 'Hello World' UNUSED"
  [1]=>
  string(30) "ZEND_RETURN UNUSED NULL UNUSED"
  [2]=>
  string(42) "ZEND_HANDLE_EXCEPTION UNUSED UNUSED UNUSED"
  ["function_table"]=>
  NULL
  ["class_table"]=>
  NULL
}

See Also

parsekit_compile_string()

Prev | Home | Next
Parsekit Functions | Up | parsekit_compile_string


parsekit_compile_string

(PECL)

parsekit_compile_string -- Compile a string of PHP code and return the resulting op array

Description

array parsekit_compile_string ( string phpcode [, array &errors [, int options]] )

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

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example 1. parsekit_compile_string() example

&#60;?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?&#62;

The above example will output:

array(20) {
  ["type"]=>
  int(4)
  ["type_name"]=>
  string(14) "ZEND_EVAL_CODE"
  ["fn_flags"]=>
  int(0)
  ["num_args"]=>
  int(0)
  ["required_num_args"]=>
  int(0)
  ["pass_rest_by_reference"]=>
  bool(false)
  ["uses_this"]=>
  bool(false)
  ["line_start"]=>
  int(0)
  ["line_end"]=>
  int(0)
  ["return_reference"]=>
  bool(false)
  ["refcount"]=>
  int(1)
  ["last"]=>
  int(3)
  ["size"]=>
  int(3)
  ["T"]=>
  int(0)
  ["last_brk_cont"]=>
  int(0)
  ["current_brk_cont"]=>
  int(-1)
  ["backpatch_count"]=>
  int(0)
  ["done_pass_two"]=>
  bool(true)
  ["filename"]=>
  string(17) "Parsekit Compiler"
  ["opcodes"]=>
  array(3) {
    [8594800]=>
    array(5) {
      ["opcode"]=>
      int(40)
      ["opcode_name"]=>
      string(9) "ZEND_ECHO"
      ["flags"]=>
      int(768)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &string(4) "Foo
"
      }
      ["lineno"]=>
      int(2)
    }
    ["859484C"]=>
    array(6) {
      ["opcode"]=>
      int(62)
      ["opcode_name"]=>
      string(11) "ZEND_RETURN"
      ["flags"]=>
      int(16777984)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &NULL
      }
      ["extended_value"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
    [8594898]=>
    array(4) {
      ["opcode"]=>
      int(149)
      ["opcode_name"]=>
      string(21) "ZEND_HANDLE_EXCEPTION"
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
  }
}

See Also

parsekit_compile_file()

Prev | Home | Next
parsekit_compile_file | Up | parsekit_func_arginfo


parsekit_func_arginfo

(PECL)

parsekit_func_arginfo -- Return information regarding function argument(s)

Description

array parsekit_func_arginfo ( mixed function )

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

function

A string describing a function, or an array describing a class/method.

Return Values

Returns an array containing argument information.

Examples

Example 1. parsekit_func_arginfo() example

&#60;?php
function foo($bar, stdClass $baz, &#38;$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?&#62;

The above example will output:

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "bar"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "baz"
    ["class_name"]=>
    string(8) "stdClass"
    ["allow_null"]=>
    bool(false)
    ["pass_by_reference"]=>
    bool(false)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(4) "bomb"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "bling"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
}

Prev | Home | Next
parsekit_compile_string | Up | Process Control Functions


Process Control Functions

PHP Manual
Prev Next

CXVII. Process Control Functions

Introduction

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.

There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().

Note: This extension is not available on Windows platforms.

Requirements

No external libraries are needed to build this extension.

Installation

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Note: Currently, this module will not function on non-Unix platforms (Windows).

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)

WUNTRACED (integer)

SIG_IGN (integer)

SIG_DFL (integer)

SIG_ERR (integer)

SIGHUP (integer)

SIGINT (integer)

SIGQUIT (integer)

SIGILL (integer)

SIGTRAP (integer)

SIGABRT (integer)

SIGIOT (integer)

SIGBUS (integer)

SIGFPE (integer)

SIGKILL (integer)

SIGUSR1 (integer)

SIGSEGV (integer)

SIGUSR2 (integer)

SIGPIPE (integer)

SIGALRM (integer)

SIGTERM (integer)

SIGSTKFLT (integer)

SIGCLD (integer)

SIGCHLD (integer)

SIGCONT (integer)

SIGSTOP (integer)

SIGTSTP (integer)

SIGTTIN (integer)

SIGTTOU (integer)

SIGURG (integer)

SIGXCPU (integer)

SIGXFSZ (integer)

SIGVTALRM (integer)

SIGPROF (integer)

SIGWINCH (integer)

SIGPOLL (integer)

SIGIO (integer)

SIGPWR (integer)

SIGSYS (integer)

SIGBABY (integer)

Examples

This example forks off a daemon process with a signal handler.

Example 1. Process Control Example

&#60;?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     exit(); // we are the parent
} else {
     // we are the child
}

// detatch from the controlling terminal
if (!posix_setsid()) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?&#62;

See Also

A look at the section about POSIX functions may be useful.

Table of Contents
pcntl_alarm -- Set an alarm clock for delivery of a signal
pcntl_exec -- Executes specified program in current process space
pcntl_fork -- Forks the currently running process
pcntl_getpriority -- Get the priority of any process
pcntl_setpriority -- Change the priority of any process
pcntl_signal -- Installs a signal handler
pcntl_wait -- Waits on or returns the status of a forked child
pcntl_waitpid -- Waits on or returns the status of a forked child
pcntl_wexitstatus -- Returns the return code of a terminated child
pcntl_wifexited -- Checks if status code represents a normal exit
pcntl_wifsignaled -- Checks wether the status code represents a termination due to a signal
pcntl_wifstopped -- Checks wether the child process is currently stopped
pcntl_wstopsig -- Returns the signal which caused the child to stop
pcntl_wtermsig -- Returns the signal which caused the child to terminate

Prev | Home | Next
parsekit_func_arginfo | Up | pcntl_alarm


pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5)

pcntl_alarm -- Set an alarm clock for delivery of a signal

Description

int pcntl_alarm ( int seconds )

Creates a timer that will send a SIGALRM signal to the process after the given number of seconds. Any call to pcntl_alarm() will cancel any previously set alarm.

Parameters

seconds

The number of seconds to wait. If seconds is zero, no new alarm is created.

Return Values

Returns the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.

Prev | Home | Next
Process Control Functions | Up | pcntl_exec


pcntl_exec

(PHP 4 >= 4.2.0, PHP 5)

pcntl_exec -- Executes specified program in current process space

Description

void pcntl_exec ( string path [, array args [, array envs]] )

Executes the program with the given arguments.

Parameters

path

path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.

args

args is an array of argument strings passed to the program.

envs

envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.

Return Values

Returns FALSE on error and does not return on success.

Prev | Home | Next
pcntl_alarm | Up | pcntl_fork


pcntl_fork

(PHP 4 >= 4.1.0, PHP 5)

pcntl_fork -- Forks the currently running process

Description

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

Return Values

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

Examples

Example 1. pcntl_fork() example

&#60;?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?&#62;

See Also

pcntl_waitpid()
pcntl_signal()

Prev | Home | Next
pcntl_exec | Up | pcntl_getpriority


pcntl_getpriority

(PHP 5)

pcntl_getpriority -- Get the priority of any process

Description

int pcntl_getpriority ( [int pid [, int process_identifier]] )

pcntl_getpriority() gets the priority of pid. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.

Parameters

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.

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.

Prev | Home | Next
pcntl_fork | Up | pcntl_setpriority


pcntl_setpriority

(PHP 5)

pcntl_setpriority -- Change the priority of any process

Description

bool pcntl_setpriority ( int priority [, int pid [, int process_identifier]] )

pcntl_setpriority() sets the priority of pid.

Parameters

priority

priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
pcntl_getpriority | Up | pcntl_signal


pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal -- Installs a signal handler

Description

bool pcntl_signal ( int signo, callback handler [, bool restart_syscalls] )

The pcntl_signal() function installs a new signal handler for the signal indicated by signo.

Parameters

signo

The signal number.

handler

The signal handler which may be the name of a user created function, or method, or either of the two global constants SIG_IGN or SIG_DFL.

Note: Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

restart_syscalls

Specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
4.3.0 | The restart_syscalls parameter was added.
4.3.0 | The ability to use an object method as a callback became available.
4.3.0 | As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).

Examples

Example 1. pcntl_signal() example

&#60;?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n"

?&#62;

See Also

pcntl_fork()
pcntl_waitpid()

Prev | Home | Next
pcntl_setpriority | Up | pcntl_wait


pcntl_wait

(PHP 5)

pcntl_wait -- Waits on or returns the status of a forked child

Description

int pcntl_wait ( int &status [, int options] )

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.

Note: This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.

Parameters

status

pcntl_wait() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:

Table 1. Possible values for options

WNOHANG | Return immediately if no child has exited.
WUNTRACED | Return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.

See Also

pcntl_fork()
pcntl_signal()
pcntl_wifexited()
pcntl_wifstopped()
pcntl_wifsignaled()
pcntl_wexitstatus()
pcntl_wtermsig()
pcntl_wstopsig()
pcntl_waitpid()

Prev | Home | Next
pcntl_signal | Up | pcntl_waitpid


pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5)

pcntl_waitpid -- Waits on or returns the status of a forked child

Description

int pcntl_waitpid ( int pid, int &status [, int options] )

Suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

Parameters

pid

The value of pid can be one of the following:

Table 1. possible values for pid

< -1 | wait for any child process whose process group ID is equal to the absolute value of pid.
-1 | wait for any child process; this is the same behaviour that the wait function exhibits.
0 | wait for any child process whose process group ID is equal to that of the calling process.
> 0 | wait for the child whose process ID is equal to the value of pid.

Note: Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).

status

pcntl_waitpid() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

The value of options is the value of zero or more of the following two global constants OR'ed together:

Table 2. possible values for options

WNOHANG | return immediately if no child has exited.
WUNTRACED | return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

See Also

pcntl_fork()
pcntl_signal()
pcntl_wifexited()
pcntl_wifstopped()
pcntl_wifsignaled()
pcntl_wexitstatus()
pcntl_wtermsig()
pcntl_wstopsig()

Prev | Home | Next
pcntl_wait | Up | pcntl_wexitstatus


pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wexitstatus -- Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int status )

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns the return code, as an integer.

See Also

pcntl_waitpid()
pcntl_wifexited()

Prev | Home | Next
pcntl_waitpid | Up | pcntl_wifexited


pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifexited -- Checks if status code represents a normal exit

Description

bool pcntl_wifexited ( int status )

Checks wether the child status code represents a normal exit.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

See Also

pcntl_waitpid()
pcntl_wexitstatus()

Prev | Home | Next
pcntl_wexitstatus | Up | pcntl_wifsignaled


pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled -- Checks wether the status code represents a termination due to a signal

Description

bool pcntl_wifsignaled ( int status )

Checks wether the child process exited because of a signal which was not caught.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns TRUE if the child process exited because of a signal which was not caught, FALSE otherwise.

See Also

pcntl_waitpid()
pcntl_signal()

Prev | Home | Next
pcntl_wifexited | Up | pcntl_wifstopped


pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped -- Checks wether the child process is currently stopped

Description

bool pcntl_wifstopped ( int status )

Checks wether the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns TRUE if the child process which caused the return is currently stopped, FALSE otherwise.

See Also

pcntl_waitpid()

Prev | Home | Next
pcntl_wifsignaled | Up | pcntl_wstopsig


pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wstopsig -- Returns the signal which caused the child to stop

Description

int pcntl_wstopsig ( int status )

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns the signal number.

See Also

pcntl_waitpid()
pcntl_wifstopped()

Prev | Home | Next
pcntl_wifstopped | Up | pcntl_wtermsig


pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wtermsig -- Returns the signal which caused the child to terminate

Description

int pcntl_wtermsig ( int status )

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

Parameters

status

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

Return Values

Returns the signal number, as an integer.

See Also

pcntl_waitpid()
pcntl_signal()
pcntl_wifsignaled()

Prev | Home | Next
pcntl_wstopsig | Up | Regular Expression Functions (Perl-Compatible)


Regular Expression Functions (Perl-Compatible)

PHP Manual
Prev Next

CXVIII. Regular Expression Functions (Perl-Compatible)

Introduction

The syntax for patterns used in these functions closely resembles Perl. The expression should be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters. See Pattern Syntax for detailed explanation.

The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.

PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions.

Note: This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).

Warning

You should be aware of some limitations of PCRE. Read http://www.pcre.org/pcre.txt for more info.

Requirements

No external libraries are needed to build this extension.

Installation

Beginning with PHP 4.2.0 these functions are enabled by default. You can disable the pcre functions with --without-pcre-regex. Use --with-pcre-regex=DIR to specify DIR where PCRE's include and library files are located, if not using bundled library. For older versions you have to configure and compile PHP with --with-pcre-regex[=DIR] in order to use these functions.

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. PCRE Configuration Options

Name | Default | Changeable | Changelog
pcre.backtrack_limit | 100000 | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.recursion_limit | 100000 | PHP_INI_ALL | Available since PHP 5.2.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

pcre.backtrack_limit integer

PCRE's backtracking limit.

pcre.recursion_limit integer

PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).

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. PREG constants

constant | description
PREG_PATTERN_ORDER | Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all().
PREG_SET_ORDER | Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all().
PREG_OFFSET_CAPTURE | See the description of PREG_SPLIT_OFFSET_CAPTURE. This flag is available since PHP 4.3.0.
PREG_SPLIT_NO_EMPTY | This flag tells preg_split() to return only non-empty pieces.
PREG_SPLIT_DELIM_CAPTURE | This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. This flag is available since PHP 4.0.5.
PREG_SPLIT_OFFSET_CAPTURE | If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is available since PHP 4.3.0 and is only used for preg_split().
PREG_NO_ERROR | Returned by preg_last_error() if there were no errors. Available since PHP 5.2.0.
PREG_INTERNAL_ERROR | Returned by preg_last_error() if there was an internal PCRE error. Available since PHP 5.2.0.
PREG_BACKTRACK_LIMIT_ERROR | Returned by preg_last_error() if backtrack limit was exhausted. Available since PHP 5.2.0.
PREG_RECURSION_LIMIT_ERROR | Returned by preg_last_error() if recursion limit was exhausted. Available since PHP 5.2.0.
PREG_BAD_UTF8_ERROR | Returned by preg_last_error() if the last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). Available since PHP 5.2.0.

Examples

Example 1. Examples of valid patterns

  • /<\/\w+>/

  • |(\d{3})-\d+|Sm

  • /^(?i)php[34]/

  • {^\s+(\s+)?$}

Example 2. Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter

  • /\w+\s*\w+/J - unknown modifier 'J'

  • 1-\d3-\d3-\d4| - missing starting delimiter

Table of Contents
Pattern Modifiers -- Describes possible modifiers in regex patterns
Pattern Syntax -- Describes PCRE regex syntax
preg_grep -- Return array entries that match the pattern
preg_last_error -- Returns the error code of the last PCRE regex execution
preg_match_all -- Perform a global regular expression match
preg_match -- Perform a regular expression match
preg_quote -- Quote regular expression characters
preg_replace_callback -- Perform a regular expression search and replace using a callback
preg_replace -- Perform a regular expression search and replace
preg_split -- Split string by a regular expression

Prev | Home | Next
pcntl_wtermsig | Up | Pattern Modifiers


Pattern Modifiers

Pattern Modifiers -- Describes possible modifiers in regex patterns

Description

The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error.

i (PCRE_CASELESS)

If this modifier is set, letters in the pattern match both upper and lower case letters.

m (PCRE_MULTILINE)

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.

When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

x (PCRE_EXTENDED)

If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.

e

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes and NULL chars will be escaped by backslashes in substituted backreferences.

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

Note: This modifier was not available in PHP 3.

A (PCRE_ANCHORED)

If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.

D (PCRE_DOLLAR_ENDONLY)

If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.

S

When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

X (PCRE_EXTRA)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.

u (PCRE_UTF8)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32. UTF-8 validity of the pattern is checked since PHP 4.3.5.

Prev | Home | Next
Regular Expression Functions (Perl-Compatible) | Up | Pattern Syntax


Pattern Syntax

Pattern Syntax -- Describes PCRE regex syntax

Description

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.

Differences From Perl

The differences described here are with respect to Perl 5.005.

  1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.

  2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.

  3. Capturing subpatterns that occur inside negative lookahead assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical variables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.

  4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\x00" can be used in the pattern to represent a binary zero.

  5. The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine.

  6. The Perl \G assertion is not supported as it is not relevant to single pattern matches.

  7. Fairly obviously, PCRE does not support the (?{code}) construction.

  8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.

  9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.

  10. PCRE provides some extensions to the Perl regular expression facilities:

    1. Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.

    2. If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-character matches only at the very end of the string.

    3. If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.

    4. If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.

Regular Expression Details

Introduction

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.

Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\

general escape character with several uses

^

assert start of subject (or line, in multiline mode)

$

assert end of subject (or line, in multiline mode)

.

match any character except newline (by default)

[

start character class definition

]

end character class definition

|

start of alternative branch

(

start subpattern

)

end subpattern

?

extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer

*

0 or more quantifier

+

1 or more quantifier

{

start min/max quantifier

}

end min/max quantifier

Part of a pattern that is in square brackets is called a "character class". In a character class the only meta-characters are:

\

general escape character

^

negate the class, but only if the first character

-

indicates character range

]

terminates the character class

The following sections describe the use of each of the meta-characters.

Backslash

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

Note: Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a

alarm, that is, the BEL character (hex 07)

\cx

"control-x", where x is any character

\e

escape (hex 1B)

\f

formfeed (hex 0C)

\n

newline (hex 0A)

\r

carriage return (hex 0D)

\t

tab (hex 09)

\xhh

character with hex code hh

\ddd

character with octal code ddd, or backreference

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040

is another way of writing a space

\40

is the same, provided there are fewer than 40 previous capturing subpatterns

\7

is always a back reference

\11

might be a back reference, or another way of writing a tab

\011

is always a tab

\0113

is a tab followed by the character "3"

\113

is the character with octal code 113 (since there can be no more than 99 back references)

\377

is a byte consisting entirely of 1 bits

\81

is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d

any decimal digit

\D

any character that is not a decimal digit

\s

any whitespace character

\S

any character that is not a whitespace character

\w

any "word" character

\W

any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b

word boundary

\B

not a word boundary

\A

start of subject (independent of multiline mode)

\Z

end of subject or newline at end (independent of multiline mode)

\z

end of subject (independent of multiline mode)

\G

first matching position in subject

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero. It is available since PHP 4.3.3.

\Q and \E can be used to ignore regexp metacharacters in the pattern since PHP 4.3.3. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

Unicode character properties

Since PHP 4.4.0 and 5.1.0, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. They are:

\p{xx}

a character with the xx property

\P{xx}

a character without the xx property

\X

an extended Unicode sequence

The property names represented by xx above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, \p{^Lu} is the same as \P{Lu}.

If only one letter is specified with \p or \P, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect:

\p{L}
\pL

Table 1. Supported property codes

C | Other
Cc | Control
Cf | Format
Cn | Unassigned
Co | Private use
Cs | Surrogate
L | Letter
Ll | Lower case letter
Lm | Modifier letter
Lo | Other letter
Lt | Title case letter
Lu | Upper case letter
M | Mark
Mc | Spacing mark
Me | Enclosing mark
Mn | Non-spacing mark
N | Number
Nd | Decimal number
Nl | Letter number
No | Other number
P | Punctuation
Pc | Connector punctuation
Pd | Dash punctuation
Pe | Close punctuation
Pf | Final punctuation
Pi | Initial punctuation
Po | Other punctuation
Ps | Open punctuation
S | Symbol
Sc | Currency symbol
Sk | Modifier symbol
Sm | Mathematical symbol
So | Other symbol
Z | Separator
Zl | Line separator
Zp | Paragraph separator
Zs | Space separator

Extended properties such as "Greek" or "InMusicalSymbols" are not supported by PCRE.

Specifying caseless matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters.

The \X escape matches any number of Unicode characters that form an extended Unicode sequence. \X is equivalent to (?>\PM\pM*).

That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character.

Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE.

Circumflex and dollar

Outside a character class, in the default matching mode, the circumflex character is an assertion which is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex has an entirely different meaning (see below).

Circumflex need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex, that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character is an assertion which is TRUE only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether PCRE_MULTILINE is set or not.

Full stop

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

\C can be used to match single byte. It makes sense in UTF-8 mode where full stop matches the whole character which can consist of multiple bytes.

Square brackets

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string.

When caseless matching is set, any letters in a class represent both their upper case and lower case versions, so for example, a caseless [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a caseful version would.

The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range.

Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when caseless matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched caselessly, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore.

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

Vertical bar

Vertical bar characters are used to separate alternative patterns. For example, the pattern gilbert|sullivan matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern.

Internal option setting

The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_UNGREEDY, PCRE_EXTRA, and PCRE_EXTENDED can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are:

Table 2. Internal option letters

i | for PCRE_CASELESS
m | for PCRE_MULTILINE
s | for PCRE_DOTALL
x | for PCRE_EXTENDED
U | for PCRE_UNGREEDY
X | for PCRE_EXTRA

For example, (?im) sets caseless, multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. So /ab(?i)c/ matches only "abc" and "abC". This behaviour has been changed in PCRE 4.0, which is bundled since PHP 4.3.3. Before those versions, /ab(?i)c/ would perform as /abc/i (e.g. matching "ABC" and "aBc").

If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so (a(?i)b)c matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example, (a(?i)b|c) matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise.

The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start.

Subpatterns

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

1. It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.

2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

For example, if the string "the red king" is matched against the pattern the ((red|white) (king|queen)) the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3.

The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

It is possible to name the subpattern with (?P<name>pattern) since PHP 4.3.3. Array with matches will contain the match indexed by the string alongside the match indexed by a number, then.

Repetition

Repetition is specified by quantifiers, which can follow any of the following items:

  • a single character, possibly escaped

  • the . metacharacter

  • a character class

  • a back reference (see next section)

  • a parenthesized subpattern (unless it is an assertion - see below)

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example: z{2,4} matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus [aeiou]{3,} matches at least 3 successive vowels, but may match many more, while \d{8} matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

Table 3. Single-character quantifiers

* | equivalent to {0,}
+ | equivalent to {1,}
? | equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: (a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern /\*.*\*/ to the string /* first comment */ not comment /* second comment */ fails, because it matches the entire string due to the greediness of the .* item.

However, if a quantifier is followed by a question mark, then it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

Quantifiers followed by + are "possessive". They eat as many characters as possible and don't return to match the rest of the pattern. Thus .*abc matches "aabc" but .*+abc doesn't because .*+ eats the whole string. Possessive quantifiers can be used to speed up processing since PHP 4.3.3.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after /(a|(b))+/ matches "aba" the value of the second captured substring is "b".

Back references

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. See the section entitled "Backslash" above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If caseful matching is in force at the time of the back reference, then the case of letters is relevant. For example, ((?i)rah)\s+\1 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched caselessly.

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern (a|(bc))\2 always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern (a|b\1)+ matches any number of "a"s and also "aba", "ababaa" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

Assertions

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described above. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example, \w+(?=;) matches a word followed by a semicolon, but does not include the semicolon in the match, and foo(?!bar) matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always TRUE when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example, (?<!foo)bar does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus (?<=bullock|donkey) is permitted, but (?<!dogs?|cats?) causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl 5.005, which requires all branches to match the same length of string. An assertion such as (?<=ab(c|de)) is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches: (?<=abc|abde) The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns can be particularly useful for matching at the ends of strings; an example is given at the end of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession. For example, (?<=\d{3})(?<!999)foo matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is (?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions can be nested in any combination. For example, (?<=(?<!foo)bar)baz matches an occurrence of "baz" that is preceded by "bar" which in turn is not preceded by "foo", while (?<=\d{3}...(?<!999))foo is another pattern which matches "foo" preceded by three digits and any three characters that are not "999".

Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions.

Assertions count towards the maximum of 200 parenthesized subpatterns.

Once-only subpatterns

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be re-evaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line 123456bar

After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. Once-only subpatterns provide the means for specifying that once a portion of the pattern has matched, it is not to be re-evaluated in this way, so the matcher would give up immediately on failing to match "foo" the first time. The notation is another kind of special parenthesis, starting with (?> as in this example: (?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Once-only subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated subpatterns, and it can be nested.

Once-only subpatterns can be used in conjunction with look-behind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as abcd$ when applied to a long string which does not match. Because matching proceeds from left to right, PCRE will look for each "a" in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as ^.*abcd$ then the initial .* matches the entire string at first, but when this fails (because there is no following "a"), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for "a" covers the entire string, from right to left, so we are no better off. However, if the pattern is written as ^(?>.*)(?<=abcd) then there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of a once-only subpattern is the only way to avoid some failing matches taking a very long time indeed. The pattern (\D+|<\d+>)*[!?] matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed to ((?>\D+)|<\d+>)*[!?] sequences of non-digits cannot be broken, and failure happens quickly.

Conditional subpatterns

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion: ( \( )? [^()]+ (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is TRUE, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false.

If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.

Comments

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

Recursive patterns

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored): \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis.

This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported.

The values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against (ab(cd)ef) the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving \( ( ( (?>[^()]+) | (?R) )* ) \) then the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion.

Since PHP 4.3.3, (?1), (?2) and so on can be used for recursive subpatterns too. It is also possible to use named subpatterns: (?P>foo).

If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern (sens|respons)e and (?1)ibility is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer.

Performances

Certain items that may appear in patterns are more efficient than others. It is more efficient to use a character class like [aeiou] than a set of alternatives such as (a|e|i|o|u). In general, the simplest construction that provides the required behaviour is usually the most efficient. Jeffrey Friedl's book contains a lot of discussion about optimizing regular expressions for efficient performance.

When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is implicitly anchored by PCRE, since it can match only at the start of a subject string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization, because the . metacharacter does not then match a newline, and if the subject string contains newlines, the pattern may match from the character immediately following one of them instead of from the very start. For example, the pattern (.*) second matches the subject "first\nand second" (where \n stands for a newline character) with the first captured substring being "and". In order to do this, PCRE has to retry the match starting after every newline in the subject.

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

Beware of patterns that contain nested indefinite repeats. These can take a long time to run when applied to a string that does not match. Consider the pattern fragment (a+)*

This can match "aaaa" in 33 different ways, and this number increases very rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4 times, and for each of those cases other than 0, the + repeats can match different numbers of times.) When the remainder of the pattern is such that the entire match is going to fail, PCRE has in principle to try every possible variation, and this can take an extremely long time.

An optimization catches some of the more simple cases such as (a+)*b where a literal character follows. Before embarking on the standard matching procedure, PCRE checks that there is a "b" later in the subject string, and if there is not, it fails the match immediately. However, when there is no following literal this optimization cannot be used. You can see the difference by comparing the behaviour of (a+)*\d with the pattern above. The former gives a failure almost instantly when applied to a whole line of "a" characters, whereas the latter takes an appreciable time with strings longer than about 20 characters.

Prev | Home | Next
Pattern Modifiers | Up | preg_grep


preg_grep

(PHP 4, PHP 5)

preg_grep -- Return array entries that match the pattern

Description

array preg_grep ( string pattern, array input [, int flags] )

Returns the array consisting of the elements of the input array that match the given pattern.

Parameters

pattern

The pattern to search for, as a string.

input

The input array.

flags

If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Return Values

Returns an array indexed using the keys from the input array.

ChangeLog

Version | Description
4.2.0 | The flags parameter was added.
4.0.4

Prior to this version, the returned array was indexed regardless of the keys of the input array.

If you want to reproduce this old behavior, use array_values() on the returned array to reindex the values.

Examples

Example 1. preg_grep() example

&#60;?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?&#62;

Prev | Home | Next
Pattern Syntax | Up | preg_last_error


preg_match_all

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match_all -- Perform a global regular expression match

Description

int preg_match_all ( string pattern, string subject, array &matches [, int flags [, int offset]] )

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

After the first match is found, the subsequent searches are continued on from end of the last match.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

In this case, $matches[0] is the first set of matches, and $matches[0][0] has text matched by full pattern, $matches[0][1] has text matched by first subpattern and so on. Similarly, $matches[1] is the second set of matches, etc.

flags

Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

&#60;?php
preg_match_all("|&#60;[^&#62;]+&#62;(.*)&#60;/[^&#62;]+&#62;|U",
    "&#60;b&#62;example: &#60;/b&#62;&#60;div align=left&#62;this is a test&#60;/div&#62;",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?&#62;

The above example will output:

<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test

So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

&#60;?php
preg_match_all("|&#60;[^&#62;]+&#62;(.*)&#60;/[^&#62;]+&#62;|U",
    "&#60;b&#62;example: &#60;/b&#62;&#60;div align=\"left\"&#62;this is a test&#60;/div&#62;",
    $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?&#62;

The above example will output:

<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

If no order flag is given, PREG_PATTERN_ORDER is assumed.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.

Note: Using offset is not equivalent to passing substr($subject, $offset) to preg_match_all() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). See preg_match() for examples.

Return Values

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

ChangeLog

Version | Description
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added

Examples

Example 1. Getting all phone numbers out of some text.

&#60;?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?&#62;

Example 2. Find matching HTML tags (greedy)

&#60;?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "&#60;b&#62;bold text&#60;/b&#62;&#60;a href=howdy.html&#62;click me&#60;/a&#62;";

preg_match_all("/(&#60;([\w]+)[^&#62;]*&#62;)(.*)(&#60;\/\\2&#62;)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[3] . "\n";
    echo "part 3: " . $val[4] . "\n\n";
}
?&#62;

The above example will output:

matched: <b>bold text</b>
part 1: <b>
part 2: bold text
part 3: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: click me
part 3: </a>

See Also

preg_match()
preg_replace()
preg_split()

Prev | Home | Next
preg_last_error | Up | preg_match


preg_match

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match -- Perform a regular expression match

Description

int preg_match ( string pattern, string subject [, array &matches [, int flags [, int offset]]] )

Searches subject for a match to the regular expression given in pattern.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags

flags can be the following flag:

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.

Note: Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare:

&#60;?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?&#62;

The above example will output:

Array
(
)

while this example

&#60;?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?&#62;

will produce

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

Return Values

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

ChangeLog

Version | Description
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added
4.3.0 | The flags parameter was added

Examples

Example 1. Find the string of text "php"

&#60;?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?&#62;

Example 2. Find the word "web"

&#60;?php
/* The \b in the pattern indicates a word boundary, so only the distinct
 * word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?&#62;

Example 3. Getting the domain name out of a URL

&#60;?php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?&#62;

The above example will output:

domain name is: php.net

Notes

Tip: Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

See Also

preg_match_all()
preg_replace()
preg_split()

Prev | Home | Next
preg_match_all | Up | preg_quote


preg_quote

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_quote -- Quote regular expression characters

Description

string preg_quote ( string str [, string delimiter] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | :

Parameters

str

The input string.

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Return Values

Returns the quoted string.

Examples

Example 1. preg_quote() example

&#60;?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?&#62;

Example 2. Italicizing a word within some text

&#60;?php
// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
                          "&#60;i&#62;" . $word . "&#60;/i&#62;",
                          $textbody);
?&#62;

Notes

Note: This function is binary-safe.

Prev | Home | Next
preg_match | Up | preg_replace_callback


preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5)

preg_replace_callback -- Perform a regular expression search and replace using a callback

Description

mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit [, int &count]] )

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

Parameters

pattern

The pattern to search for. It can be either a string or an array with strings.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

Example 1. preg_replace_callback() and create_function()

&#60;?php
/* a unix-style command line filter to convert uppercase
 * letters at the beginning of paragraphs to lowercase */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = fgets($fp);
    $line = preg_replace_callback(
        '|&#60;p&#62;\s*\w|',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return strtolower($matches[0]);'
        ),
        $line
    );
    echo $line;
}
fclose($fp);
?&#62;

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

ChangeLog

Version | Description
5.1.0 | The count parameter was added

Examples

Example 2. preg_replace_callback() example

&#60;?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);

?&#62;

The above example will output:

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example 3. preg_replace_callback() using recursive structure to handle encapsulated BB code

&#60;?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{

    $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

    if (is_array($input)) {
        $input = '&#60;div style="margin-left: 10px"&#62;'.$input[1].'&#60;/div&#62;';
    }

    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?&#62;

See Also

preg_replace()
create_function()
information about the callback type

Prev | Home | Next
preg_quote | Up | preg_replace


preg_replace

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_replace -- Perform a regular expression search and replace

Description

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit [, int &count]] )

Searches subject for matches to pattern and replaces them with replacement.

Parameters

pattern

The pattern to search for. It can be either a string or an array with strings.

The e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

replacement

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.

replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

When using the e modifier, this function escapes some characters (namely ', ", \ and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arrise from backreference usage with either single or double quotes (e.g. 'strlen(\'$1\')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know exactly how the interpreted string will look like.

subject

The string or an array with strings to search and replace.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

ChangeLog

Version | Description
5.1.0 | Added the count parameter
4.0.4 | Added the '$n' form for the replacement parameter
4.0.1 | Added the limit parameter

Examples

Example 1. Using backreferences followed by numeric literals

&#60;?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?&#62;

The above example will output:

April1,2003

Example 2. Using indexed arrays with preg_replace()

&#60;?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?&#62;

The above example will output:

The bear black slow jumped over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

&#60;?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?&#62;

The above example will output:

The slow black bear jumped over the lazy dog.

Example 3. Replacing several values

&#60;?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                   '/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?&#62;

The above example will output:

$startDate = 5/27/1999

Example 4. Using the 'e' modifier

&#60;?php
preg_replace("/(&#60;\/?)(\w+)([^&#62;]*&#62;)/e",
             "'\\1'.strtoupper('\\2').'\\3'",
             $html_body);
?&#62;

This would capitalize all HTML tags in the input text.

Example 5. Strip whitespace

This example strips excess whitespace from a string.

&#60;?php
$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?&#62;

Example 6. Using the count parameter

&#60;?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?&#62;

The above example will output:

xp***to
3

Notes

Note: When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. This is not necessarily the same as the numerical index order. If you use indexes to identify which pattern should be replaced by which replacement, you should perform a ksort() on each array prior to calling preg_replace().

See Also

preg_match()
preg_replace_callback()
preg_split()

Prev | Home | Next
preg_replace_callback | Up | preg_split


preg_split

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_split -- Split string by a regular expression

Description

array preg_split ( string pattern, string subject [, int limit [, int flags]] )

Split the given string by a regular expression.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

limit

If specified, then only substrings up to limit are returned, and if limit is -1, it actually means "no limit", which is useful for specifying the flags.

flags

flags can be any combination of the following flags (combined with bitwise | operator):

PREG_SPLIT_NO_EMPTY

If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

PREG_SPLIT_OFFSET_CAPTURE

If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

Return Values

Returns an array containing substrings of subject split along boundaries matched by pattern.

ChangeLog

Version | Description
4.3.0 | The PREG_SPLIT_OFFSET_CAPTURE was added
4.0.5 | The PREG_SPLIT_DELIM_CAPTURE was added
4.0.0 | The flags parameter was added

Examples

Example 1. preg_split() example : Get the parts of a search string

&#60;?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?&#62;

Example 2. Splitting a string into component characters

&#60;?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?&#62;

Example 3. Splitting a string into matches and their offsets

&#60;?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?&#62;

The above example will output:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

Notes

Tip: If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

See Also

spliti()
split()
implode()
preg_match()
preg_match_all()
preg_replace()

Prev | Home | Next
preg_replace | Up | PDF Functions


PDF Functions

PHP Manual
Prev Next

CXIX. PDF Functions

Introduction

The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by PDFlib GmbH.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. For the full and detailed explanation of each function, consult the PDFlib Reference Manual which is included in all PDFlib packages distributed by PDFlib GmbH. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

For a jump start we urge you to take a look at the programming samples which are contained in all PDFlib distribution packages. These samples demonstrate basic text, vector, and graphics output as well as higher-level functions, such as the PDF import facility (PDI).

All of the functions in PDFlib and the PHP module have identical function names and parameters. Unless configured otherwise, all lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib Reference Manual included in the PDFlib distribution for a more thorough explanation of the coordinate system used.

With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. The main difference is the following:

In PHP 4, first a PDF resource has to be retrieved with a function call like

$p = PDF_new().

This PDF resource is used as the first parameter in all further function calls, such as in

PDF_begin_document($p, "", "").

In PHP 5 however, a PDFlib object is created with

$p = new PDFlib().

This object offers all PDFlib API functions as methods, e.g. as with

$p->begin_document("", "").

In addition, exceptions have been introduced in PHP 5 which are supported by PDFlib 6 and later as well.

Please see the examples below for more information.

Note: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

Requirements

PDFlib Lite is available as open source. However, the PDFlib Lite license allows free use only under certain conditions. PDFlib Lite supports a subset of PDFlib's functionality; please see the PDFlib web site for details. The full version of PDFlib is available for download at http://www.pdflib.com/products/pdflib-family/, but requires that you purchase a license for commercial use.

Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 4.0 or greater is supported by PHP 4.3 and later.

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/pdflib.

To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local.

Resource Types

This extension has no resource types defined.

Remarks about Deprecated PDFlib Functions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib Reference Manual are supported by PHP 4 with exactly the same meaning and the same parameters. However, with PDFlib Version 5.0.4 or higher all parameters have to be specified. For compatibility reasons, this binding for PDFlib still supports most of the deprecated functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions. The documentation in this section indicates old functions as "Deprecated" and gives the replacement function to be used instead.

Examples

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It is developed for PHP 4 and creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example 1. Hello World example from PDFlib distribution for PHP 4

&#60;?php
$p = PDF_new();

/*  open new PDF file; insert a file name to create the PDF on disk */
if (PDF_begin_document($p, "", "") == 0) {
    die("Error: " . PDF_get_errmsg($p));
}

PDF_set_info($p, "Creator", "hello.php");
PDF_set_info($p, "Author", "Rainer Schaaf");
PDF_set_info($p, "Title", "Hello world (PHP)!");

PDF_begin_page_ext($p, 595, 842, "");

$font = PDF_load_font($p, "Helvetica-Bold", "winansi", "");

PDF_setfont($p, $font, 24.0);
PDF_set_text_pos($p, 50, 700);
PDF_show($p, "Hello world!");
PDF_continue_text($p, "(says PHP)");
PDF_end_page_ext($p, "");

PDF_end_document($p, "");

$buf = PDF_get_buffer($p);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
print $buf;

PDF_delete($p);
?&#62;

The following example comes with the PDFlib distribution for PHP 5. It uses the new exception handling and object encapsulation features available in PHP 5. It creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example 2. Hello World example from PDFlib distribution for PHP 5

&#60;?php

try {
    $p = new PDFlib();

    /*  open new PDF file; insert a file name to create the PDF on disk */
    if ($p-&#62;begin_document("", "") == 0) {
        die("Error: " . $p-&#62;get_errmsg());
    }

    $p-&#62;set_info("Creator", "hello.php");
    $p-&#62;set_info("Author", "Rainer Schaaf");
    $p-&#62;set_info("Title", "Hello world (PHP)!");

    $p-&#62;begin_page_ext(595, 842, "");

    $font = $p-&#62;load_font("Helvetica-Bold", "winansi", "");

    $p-&#62;setfont($font, 24.0);
    $p-&#62;set_text_pos(50, 700);
    $p-&#62;show("Hello world!");
    $p-&#62;continue_text("(says PHP)");
    $p-&#62;end_page_ext("");

    $p-&#62;end_document("");

    $buf = $p-&#62;get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=hello.pdf");
    print $buf;
}
catch (PDFlibException $e) {
    die("PDFlib exception occurred in hello sample:\n" .
    "[" . $e-&#62;get_errnum() . "] " . $e-&#62;get_apiname() . ": " .
    $e-&#62;get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}
$p = 0;
?&#62;

Table of Contents
PDF_activate_item -- Activate structure element or other content item
PDF_add_annotation -- Add annotation [deprecated]
PDF_add_bookmark -- Add bookmark for current page [deprecated]
PDF_add_launchlink -- Add launch annotation for current page [deprecated]
PDF_add_locallink -- Add link annotation for current page [deprecated]
PDF_add_nameddest -- Create named destination
PDF_add_note -- Set annotation for current page [deprecated]
PDF_add_outline -- Add bookmark for current page [deprecated]
PDF_add_pdflink -- Add file link annotation for current page [deprecated]
PDF_add_thumbnail -- Add thumbnail for current page
PDF_add_weblink -- Add weblink for current page [deprecated]
PDF_arc -- Draw a counterclockwise circular arc segment
PDF_arcn -- Draw a clockwise circular arc segment
PDF_attach_file -- Add file attachment for current page [deprecated]
PDF_begin_document -- Create new PDF file
PDF_begin_font -- Start a Type 3 font definition
PDF_begin_glyph -- Start glyph definition for Type 3 font
PDF_begin_item -- Open structure element or other content item
PDF_begin_layer -- Start layer
PDF_begin_page_ext -- Start new page
PDF_begin_page -- Start new page [deprecated]
PDF_begin_pattern -- Start pattern definition
PDF_begin_template -- Start template definition
PDF_circle -- Draw a circle
PDF_clip -- Clip to current path
PDF_close_image -- Close image
PDF_close_pdi_page -- Close the page handle
PDF_close_pdi -- Close the input PDF document
PDF_close -- Close pdf resource [deprecated]
PDF_closepath_fill_stroke -- Close, fill and stroke current path
PDF_closepath_stroke -- Close and stroke path
PDF_closepath -- Close current path
PDF_concat -- Concatenate a matrix to the CTM
PDF_continue_text -- Output text in next line
PDF_create_action -- Create action for objects or events
PDF_create_annotation -- Create rectangular annotation
PDF_create_bookmark -- Create bookmark
PDF_create_field -- Create form field
PDF_create_fieldgroup -- Create form field group
PDF_create_gstate -- Create graphics state object
PDF_create_pvf -- Create PDFlib virtual file
PDF_create_textflow -- Create textflow object
PDF_curveto -- Draw Bezier curve
PDF_define_layer -- Create layer definition
PDF_delete_pvf -- Delete PDFlib virtual file
PDF_delete_textflow -- Delete textflow object
PDF_delete -- Delete PDFlib object
PDF_encoding_set_char -- Add glyph name and/or Unicode value
PDF_end_document -- Close PDF file
PDF_end_font -- Terminate Type 3 font definition
PDF_end_glyph -- Terminate glyph definition for Type 3 font
PDF_end_item -- Close structure element or other content item
PDF_end_layer -- Deactivate all active layers
PDF_end_page_ext -- Finish page
PDF_end_page -- Finish page
PDF_end_pattern -- Finish pattern
PDF_end_template -- Finish template
PDF_endpath -- End current path
PDF_fill_imageblock -- Fill image block with variable data
PDF_fill_pdfblock -- Fill PDF block with variable data
PDF_fill_stroke -- Fill and stroke path
PDF_fill_textblock -- Fill text block with variable data
PDF_fill -- Fill current path
PDF_findfont -- Prepare font for later use [deprecated]
PDF_fit_image -- Place image or template
PDF_fit_pdi_page -- Place imported PDF page
PDF_fit_textflow -- Format textflow in rectangular area
PDF_fit_textline -- Place single line of text
PDF_get_apiname -- Get name of unsuccessfull API function
PDF_get_buffer -- Get PDF output buffer
PDF_get_errmsg -- Get error text
PDF_get_errnum -- Get error number
PDF_get_font -- Get font [deprecated]
PDF_get_fontname -- Get font name [deprecated]
PDF_get_fontsize -- Font handling [deprecated]
PDF_get_image_height -- Get image height [deprecated]
PDF_get_image_width -- Get image width [deprecated]
PDF_get_majorversion -- Get major version number [deprecated]
PDF_get_minorversion -- Get minor version number [deprecated]
PDF_get_parameter -- Get string parameter
PDF_get_pdi_parameter -- Get PDI string parameter
PDF_get_pdi_value -- Get PDI numerical parameter
PDF_get_value -- Get numerical parameter
PDF_info_textflow -- Query textflow state
PDF_initgraphics -- Reset graphic state
PDF_lineto -- Draw a line
PDF_load_font -- Search and prepare font
PDF_load_iccprofile -- Search and prepare ICC profile
PDF_load_image -- Open image file
PDF_makespotcolor -- Make spot color
PDF_moveto -- Set current point
PDF_new -- Create PDFlib object
PDF_open_ccitt -- Open raw CCITT image [deprecated]
PDF_open_file -- Create PDF file [deprecated]
PDF_open_gif -- Open GIF image [deprecated]
PDF_open_image_file -- Read image from file [deprecated]
PDF_open_image -- Use image data [deprecated]
PDF_open_jpeg -- Open JPEG image [deprecated]
PDF_open_memory_image -- Open image created with PHP's image functions [not supported]
PDF_open_pdi_page -- Prepare a page
PDF_open_pdi -- Open PDF file
PDF_open_tiff -- Open TIFF image [deprecated]
PDF_place_image -- Place image on the page [deprecated]
PDF_place_pdi_page -- Place PDF page [deprecated]
PDF_process_pdi -- Process imported PDF document
PDF_rect -- Draw rectangle
PDF_restore -- Restore graphics state
PDF_resume_page -- Resume page
PDF_rotate -- Rotate coordinate system
PDF_save -- Save graphics state
PDF_scale -- Scale coordinate system
PDF_set_border_color -- Set border color of annotations [deprecated]
PDF_set_border_dash -- Set border dash style of annotations [deprecated]
PDF_set_border_style -- Set border style of annotations [deprecated]
PDF_set_char_spacing -- Set character spacing [deprecated]
PDF_set_duration -- Set duration between pages [deprecated]
PDF_set_gstate -- Activate graphics state object
PDF_set_horiz_scaling -- Set horizontal text scaling [deprecated]
PDF_set_info_author -- Fill the author document info field [deprecated]
PDF_set_info_creator -- Fill the creator document info field [deprecated]
PDF_set_info_keywords -- Fill the keywords document info field [deprecated]
PDF_set_info_subject -- Fill the subject document info field [deprecated]
PDF_set_info_title -- Fill the title document info field [deprecated]
PDF_set_info -- Fill document info field
PDF_set_layer_dependency -- Define relationships among layers
PDF_set_leading -- Set distance between text lines [deprecated]
PDF_set_parameter -- Set string parameter
PDF_set_text_matrix -- Set text matrix [deprecated]
PDF_set_text_pos -- Set text position
PDF_set_text_rendering -- Determine text rendering [deprecated]
PDF_set_text_rise -- Set text rise [deprecated]
PDF_set_value -- Set numerical parameter
PDF_set_word_spacing -- Set spacing between words [deprecated]
PDF_setcolor -- Set fill and stroke color
PDF_setdash -- Set simple dash pattern
PDF_setdashpattern -- Set dash pattern
PDF_setflat -- Set flatness
PDF_setfont -- Set font
PDF_setgray_fill -- Set fill color to gray [deprecated]
PDF_setgray_stroke -- Set stroke color to gray [deprecated]
PDF_setgray -- Set color to gray [deprecated]
PDF_setlinecap -- Set linecap parameter
PDF_setlinejoin -- Set linejoin parameter
PDF_setlinewidth -- Set line width
PDF_setmatrix -- Set current transformation matrix
PDF_setmiterlimit -- Set miter limit
PDF_setpolydash -- Set complicated dash pattern [deprecated]
PDF_setrgbcolor_fill -- Set fill rgb color values [deprecated]
PDF_setrgbcolor_stroke -- Set stroke rgb color values [deprecated]
PDF_setrgbcolor -- Set fill and stroke rgb color values [deprecated]
PDF_shading_pattern -- Define shading pattern
PDF_shading -- Define blend
PDF_shfill -- Fill area with shading
PDF_show_boxed -- Output text in a box [deprecated]
PDF_show_xy -- Output text at given position
PDF_show -- Output text at current position
PDF_skew -- Skew the coordinate system
PDF_stringwidth -- Return width of text
PDF_stroke -- Stroke path
PDF_suspend_page -- Suspend page
PDF_translate -- Set origin of coordinate system
PDF_utf16_to_utf8 -- Convert string from UTF-16 to UTF-8
PDF_utf8_to_utf16 -- Convert string from UTF-8 to UTF-16

Prev | Home | Next
preg_split | Up | PDF_activate_item


PDF_add_annotation

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_add_annotation -- Add annotation [deprecated]

Description

This function is deprecated, use PDF_create_annotation() with type=Text instead.

Prev | Home | Next
PDF_activate_item | Up | PDF_add_bookmark


PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL)

PDF_add_bookmark -- Add bookmark for current page [deprecated]

Description

This function is deprecated since PDFlib version 6, use PDF_create_bookmark() instead.

Prev | Home | Next
PDF_add_annotation | Up | PDF_add_launchlink


PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL)

PDF_add_launchlink -- Add launch annotation for current page [deprecated]

Description

bool PDF_add_launchlink ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename )

Adds a link to a web resource.

This function is deprecated since PDFlib version 6,
use PDF_create_action() with
type=Launch and
PDF_create_annotation() with
type=Link instead.

Prev | Home | Next
PDF_add_bookmark | Up | PDF_add_locallink


PDF_add_locallink

(PHP 4 >= 4.0.5, PECL)

PDF_add_locallink -- Add link annotation for current page [deprecated]

Description

bool PDF_add_locallink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, int page, string dest )

Add a link annotation to a target within the current PDF file. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=GoTo
and PDF_create_annotation() with
type=Link instead.

Prev | Home | Next
PDF_add_launchlink | Up | PDF_add_nameddest


PDF_add_note

(PHP 4 >= 4.0.5, PECL)

PDF_add_note -- Set annotation for current page [deprecated]

Description

bool PDF_add_note ( resource pdfdoc, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open )

Sets an annotation for the current page. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=Text instead.

Prev | Home | Next
PDF_add_nameddest | Up | PDF_add_outline


PDF_add_outline

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_add_outline -- Add bookmark for current page [deprecated]

Description

This function is deprecated, use PDF_create_bookmark() instead.

Prev | Home | Next
PDF_add_note | Up | PDF_add_pdflink


PDF_add_pdflink

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_add_pdflink -- Add file link annotation for current page [deprecated]

Description

bool PDF_add_pdflink ( resource pdfdoc, float bottom_left_x, float bottom_left_y, float up_right_x, float up_right_y, string filename, int page, string dest )

Add a file link annotation to a PDF target. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with
type=GoToR and
PDF_create_annotation() with
type=Link instead.

Prev | Home | Next
PDF_add_outline | Up | PDF_add_thumbnail


PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL)

PDF_add_thumbnail -- Add thumbnail for current page

Description

bool PDF_add_thumbnail ( resource pdfdoc, int image )

Adds an existing image as thumbnail for the current page. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_add_pdflink | Up | PDF_add_weblink


PDF_add_weblink

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_add_weblink -- Add weblink for current page [deprecated]

Description

bool PDF_add_weblink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, string url )

Adds a weblink annotation to a target url on the Web. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=URI
and PDF_create_annotation() with
type=Link instead.

Prev | Home | Next
PDF_add_thumbnail | Up | PDF_arc


PDF_arc

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_arc -- Draw a counterclockwise circular arc segment

Description

bool PDF_arc ( resource p, float x, float y, float r, float alpha, float beta )

Adds a counterclockwise circular arc.

Prev | Home | Next
PDF_add_weblink | Up | PDF_arcn


PDF_arcn

(PHP 4 >= 4.0.5, PECL)

PDF_arcn -- Draw a clockwise circular arc segment

Description

bool PDF_arcn ( resource p, float x, float y, float r, float alpha, float beta )

Except for the drawing direction, this function behaves exactly like PDF_arc().

Prev | Home | Next
PDF_arc | Up | PDF_attach_file


PDF_attach_file

(PHP 4 >= 4.0.5, PECL)

PDF_attach_file -- Add file attachment for current page [deprecated]

Description

bool PDF_attach_file ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon )

Adds a file attachment annotation. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=FileAttachment instead.

Prev | Home | Next
PDF_arcn | Up | PDF_begin_document


PDF_begin_page

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_begin_page -- Start new page [deprecated]

Description

bool PDF_begin_page ( resource pdfdoc, float width, float height )

Adds a new page to the document. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_page_ext() instead.

Prev | Home | Next
PDF_begin_page_ext | Up | PDF_begin_pattern


PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL)

PDF_begin_pattern -- Start pattern definition

Description

int PDF_begin_pattern ( resource pdfdoc, float width, float height, float xstep, float ystep, int painttype )

Starts a new pattern definition.

Prev | Home | Next
PDF_begin_page | Up | PDF_begin_template


PDF_begin_template

(PHP 4 >= 4.0.5, PECL)

PDF_begin_template -- Start template definition

Description

int PDF_begin_template ( resource pdfdoc, float width, float height )

Starts a new template definition.

Prev | Home | Next
PDF_begin_pattern | Up | PDF_circle


PDF_circle

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_circle -- Draw a circle

Description

bool PDF_circle ( resource pdfdoc, float x, float y, float r )

Adds a circle. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_begin_template | Up | PDF_clip


PDF_clip

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_clip -- Clip to current path

Description

bool PDF_clip ( resource p )

Uses the current path as clipping path, and terminate the path. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_circle | Up | PDF_close_image


PDF_close_image

(PHP 3 >= 3.0.7, PHP 4, PECL)

PDF_close_image -- Close image

Description

void PDF_close_image ( resource p, int image )

Closes an image retrieved with the PDF_open_image() function.

Prev | Home | Next
PDF_clip | Up | PDF_close_pdi_page


PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL)

PDF_close_pdi_page -- Close the page handle

Description

bool PDF_close_pdi_page ( resource p, int page )

Closes the page handle, and frees all page-related resources. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_close_image | Up | PDF_close_pdi


PDF_close_pdi

(PHP 4 >= 4.0.5, PECL)

PDF_close_pdi -- Close the input PDF document

Description

bool PDF_close_pdi ( resource p, int doc )

Closes all open page handles, and closes the input PDF document. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_close_pdi_page | Up | PDF_close


PDF_close

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_close -- Close pdf resource [deprecated]

Description

bool PDF_close ( resource p )

Closes the generated PDF file, and frees all document-related resources. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_end_document() instead.

Prev | Home | Next
PDF_close_pdi | Up | PDF_closepath_fill_stroke


PDF_closepath_fill_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_closepath_fill_stroke -- Close, fill and stroke current path

Description

bool PDF_closepath_fill_stroke ( resource p )

Closes the path, fills, and strokes it. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_close | Up | PDF_closepath_stroke


PDF_closepath_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_closepath_stroke -- Close and stroke path

Description

bool PDF_closepath_stroke ( resource p )

Closes the path, and strokes it. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_closepath_fill_stroke | Up | PDF_closepath


PDF_closepath

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_closepath -- Close current path

Description

bool PDF_closepath ( resource p )

Closes the current path. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_closepath_stroke | Up | PDF_concat


PDF_concat

(PHP 4 >= 4.0.5, PECL)

PDF_concat -- Concatenate a matrix to the CTM

Description

bool PDF_concat ( resource p, float a, float b, float c, float d, float e, float f )

Concatenates a matrix to the current transformation matrix (CTM). Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_closepath | Up | PDF_continue_text


PDF_continue_text

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_continue_text -- Output text in next line

Description

bool PDF_continue_text ( resource p, string text )

Prints text at the next line. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_concat | Up | PDF_create_action


PDF_curveto

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_curveto -- Draw Bezier curve

Description

bool PDF_curveto ( resource p, float x1, float y1, float x2, float y2, float x3, float y3 )

Draws a Bezier curve from the current point, using 3 more control points. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_create_textflow | Up | PDF_define_layer


PDF_delete

(PHP 4 >= 4.0.5, PECL)

PDF_delete -- Delete PDFlib object

Description

bool PDF_delete ( resource pdfdoc )

Deletes a PDFlib object, and frees all internal resources. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_delete_textflow | Up | PDF_encoding_set_char


PDF_end_page

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_end_page -- Finish page

Description

bool PDF_end_page ( resource p )

Finishes the page. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_end_page_ext | Up | PDF_end_pattern


PDF_end_pattern

(PHP 4 >= 4.0.5, PECL)

PDF_end_pattern -- Finish pattern

Description

bool PDF_end_pattern ( resource p )

Finishes the pattern definition. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_end_page | Up | PDF_end_template


PDF_end_template

(PHP 4 >= 4.0.5, PECL)

PDF_end_template -- Finish template

Description

bool PDF_end_template ( resource p )

Finishes a template definition. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_end_pattern | Up | PDF_endpath


PDF_endpath

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_endpath -- End current path

Description

bool PDF_endpath ( resource p )

Ends the current path without filling or stroking it.

Prev | Home | Next
PDF_end_template | Up | PDF_fill_imageblock


PDF_fill_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_fill_stroke -- Fill and stroke path

Description

bool PDF_fill_stroke ( resource p )

Fills and strokes the current path with the current fill and stroke color. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_fill_pdfblock | Up | PDF_fill_textblock


PDF_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_fill -- Fill current path

Description

bool PDF_fill ( resource p )

Fills the interior of the current path with the current fill color. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_fill_textblock | Up | PDF_findfont


PDF_findfont

(PHP 4 >= 4.0.5, PECL)

PDF_findfont -- Prepare font for later use [deprecated]

Description

int PDF_findfont ( resource p, string fontname, string encoding, int embed )

Search for a font and prepare it for later use with PDF_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.

This function is deprecated since PDFlib version 5, use PDF_load_font() instead.

Prev | Home | Next
PDF_fill | Up | PDF_fit_image


PDF_get_buffer

(PHP 4 >= 4.0.5, PECL)

PDF_get_buffer -- Get PDF output buffer

Description

string PDF_get_buffer ( resource p )

Fetches the buffer containing the generated PDF data.

Prev | Home | Next
PDF_get_apiname | Up | PDF_get_errmsg


PDF_get_font

(PHP 4, PECL)

PDF_get_font -- Get font [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter font instead.

Prev | Home | Next
PDF_get_errnum | Up | PDF_get_fontname


PDF_get_fontname

(PHP 4, PECL)

PDF_get_fontname -- Get font name [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_parameter() with the parameter fontname instead.

Prev | Home | Next
PDF_get_font | Up | PDF_get_fontsize


PDF_get_fontsize

(PHP 4, PECL)

PDF_get_fontsize -- Font handling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter fontsizeinstead.

Prev | Home | Next
PDF_get_fontname | Up | PDF_get_image_height


PDF_get_image_height

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_get_image_height -- Get image height [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imageheight instead.

Prev | Home | Next
PDF_get_fontsize | Up | PDF_get_image_width


PDF_get_image_width

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_get_image_width -- Get image width [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imagewidth instead.

Prev | Home | Next
PDF_get_image_height | Up | PDF_get_majorversion


PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL)

PDF_get_majorversion -- Get major version number [deprecated]

Description

int PDF_get_majorversion ( void )

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter major instead.

Prev | Home | Next
PDF_get_image_width | Up | PDF_get_minorversion


PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL)

PDF_get_minorversion -- Get minor version number [deprecated]

Description

int PDF_get_minorversion ( void )

Returns the minor version number of the PDFlib version.

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter minor instead.

Prev | Home | Next
PDF_get_majorversion | Up | PDF_get_parameter


PDF_get_parameter

(PHP 4 >= 4.0.1, PECL)

PDF_get_parameter -- Get string parameter

Description

string PDF_get_parameter ( resource p, string key, float modifier )

Gets the contents of some PDFlib parameter with string type.

Prev | Home | Next
PDF_get_minorversion | Up | PDF_get_pdi_parameter


PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL)

PDF_get_pdi_parameter -- Get PDI string parameter

Description

string PDF_get_pdi_parameter ( resource p, string key, int doc, int page, int reserved )

Gets the contents of a PDI document parameter with string type.

Prev | Home | Next
PDF_get_parameter | Up | PDF_get_pdi_value


PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL)

PDF_get_pdi_value -- Get PDI numerical parameter

Description

float PDF_get_pdi_value ( resource p, string key, int doc, int page, int reserved )

Gets the contents of a PDI document parameter with numerical type.

Prev | Home | Next
PDF_get_pdi_parameter | Up | PDF_get_value


PDF_get_value

(PHP 4 >= 4.0.1, PECL)

PDF_get_value -- Get numerical parameter

Description

float PDF_get_value ( resource p, string key, float modifier )

Gets the value of some PDFlib parameter with numerical type.

Prev | Home | Next
PDF_get_pdi_value | Up | PDF_info_textflow


PDF_initgraphics

(PHP 4 >= 4.0.5, PECL)

PDF_initgraphics -- Reset graphic state

Description

bool PDF_initgraphics ( resource p )

Reset all color and graphics state parameters to their defaults. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_info_textflow | Up | PDF_lineto


PDF_lineto

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_lineto -- Draw a line

Description

bool PDF_lineto ( resource p, float x, float y )

Draws a line from the current point to another point. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_initgraphics | Up | PDF_load_font


PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL)

PDF_makespotcolor -- Make spot color

Description

int PDF_makespotcolor ( resource p, string spotname )

Finds a built-in spot color name, or makes a named spot color from the current fill color. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_load_image | Up | PDF_moveto


PDF_moveto

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_moveto -- Set current point

Description

bool PDF_moveto ( resource p, float x, float y )

Sets the current point for graphics output. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_makespotcolor | Up | PDF_new


PDF_new

(PHP 4 >= 4.0.5, PECL)

PDF_new -- Create PDFlib object

Description

resource PDF_new ( )

Creates a new PDFlib object with default settings.

Prev | Home | Next
PDF_moveto | Up | PDF_open_ccitt


PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL)

PDF_open_ccitt -- Open raw CCITT image [deprecated]

Description

int PDF_open_ccitt ( resource pdfdoc, string filename, int width, int height, int BitReverse, int k, int Blackls1 )

Opens a raw CCITT image.

This function is deprecated since PDFlib version 5, use PDF_load_image() instead.

Prev | Home | Next
PDF_new | Up | PDF_open_file


PDF_open_file

(PHP 4 >= 4.0.5, PECL)

PDF_open_file -- Create PDF file [deprecated]

Description

bool PDF_open_file ( resource p, string filename )

Creates a new PDF file using the supplied file name. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_document() instead.

Prev | Home | Next
PDF_open_ccitt | Up | PDF_open_gif


PDF_open_gif

(PHP 3 >= 3.0.7, PHP 4, PECL)

PDF_open_gif -- Open GIF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

Prev | Home | Next
PDF_open_file | Up | PDF_open_image_file


PDF_open_image_file

(PHP 3 CVS only, PHP 4, PECL)

PDF_open_image_file -- Read image from file [deprecated]

Description

int PDF_open_image_file ( resource p, string imagetype, string filename, string stringparam, int intparam )

Opens an image file.

This function is deprecated since PDFlib version 5, use PDF_load_image() with the colorize, ignoremask, invert, mask, masked, and page options instead.

Prev | Home | Next
PDF_open_gif | Up | PDF_open_image


PDF_open_image

(PHP 4 >= 4.0.5, PECL)

PDF_open_image -- Use image data [deprecated]

Description

int PDF_open_image ( resource p, string imagetype, string source, string data, int length, int width, int height, int components, int bpc, string params )

Uses image data from a variety of data sources.

This function is deprecated since PDFlib version 5, use virtual files and PDF_load_image() instead.

Prev | Home | Next
PDF_open_image_file | Up | PDF_open_jpeg


PDF_open_jpeg

(PHP 3 >= 3.0.7, PHP 4, PECL)

PDF_open_jpeg -- Open JPEG image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

Prev | Home | Next
PDF_open_image | Up | PDF_open_memory_image


PDF_open_memory_image

(PHP 3 >= 3.0.10, PHP 4, PECL)

PDF_open_memory_image -- Open image created with PHP's image functions [not supported]

Description

int PDF_open_memory_image ( resource p, resource image )

This function is not supported by PDFlib GmbH.

Prev | Home | Next
PDF_open_jpeg | Up | PDF_open_pdi_page


PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL)

PDF_open_pdi_page -- Prepare a page

Description

int PDF_open_pdi_page ( resource p, int doc, int pagenumber, string optlist )

Prepares a page for later use with PDF_fit_pdi_page().

Prev | Home | Next
PDF_open_memory_image | Up | PDF_open_pdi


PDF_open_pdi

(PHP 4 >= 4.0.5, PECL)

PDF_open_pdi -- Open PDF file

Description

int PDF_open_pdi ( resource pdfdoc, string filename, string optlist )

Opens a disk-based or virtual PDF document and prepares it for later use.

Prev | Home | Next
PDF_open_pdi_page | Up | PDF_open_tiff


PDF_open_tiff

(PHP 4, PECL)

PDF_open_tiff -- Open TIFF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

Prev | Home | Next
PDF_open_pdi | Up | PDF_place_image


PDF_place_image

(PHP 3 >= 3.0.7, PHP 4, PECL)

PDF_place_image -- Place image on the page [deprecated]

Description

bool PDF_place_image ( resource pdfdoc, int image, float x, float y, float scale )

Places an image and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_image() instead.

Prev | Home | Next
PDF_open_tiff | Up | PDF_place_pdi_page


PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL)

PDF_place_pdi_page -- Place PDF page [deprecated]

Description

bool PDF_place_pdi_page ( resource pdfdoc, int page, float x, float y, float sx, float sy )

Places a PDF page and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_pdi_page() instead.

Prev | Home | Next
PDF_place_image | Up | PDF_process_pdi


PDF_rect

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_rect -- Draw rectangle

Description

bool PDF_rect ( resource p, float x, float y, float width, float height )

Draws a rectangle. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_process_pdi | Up | PDF_restore


PDF_restore

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_restore -- Restore graphics state

Description

bool PDF_restore ( resource p )

Restores the most recently saved graphics state. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_rect | Up | PDF_resume_page


PDF_rotate

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_rotate -- Rotate coordinate system

Description

bool PDF_rotate ( resource p, float phi )

Rotates the coordinate system. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_resume_page | Up | PDF_save


PDF_save

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_save -- Save graphics state

Description

bool PDF_save ( resource p )

Saves the current graphics state. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_rotate | Up | PDF_scale


PDF_scale

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_scale -- Scale coordinate system

Description

bool PDF_scale ( resource p, float sx, float sy )

Scales the coordinate system. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_save | Up | PDF_set_border_color


PDF_set_border_color

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_set_border_color -- Set border color of annotations [deprecated]

Description

bool PDF_set_border_color ( resource p, float red, float green, float blue )

Sets the border color for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option annotcolor in PDF_create_annotation() instead.

Prev | Home | Next
PDF_scale | Up | PDF_set_border_dash


PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL)

PDF_set_border_dash -- Set border dash style of annotations [deprecated]

Description

bool PDF_set_border_dash ( resource pdfdoc, float black, float white )

Sets the border dash style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option dasharray in PDF_create_annotation() instead.

Prev | Home | Next
PDF_set_border_color | Up | PDF_set_border_style


PDF_set_border_style

(PHP 3 >= 3.0.12, PHP 4, PECL)

PDF_set_border_style -- Set border style of annotations [deprecated]

Description

bool PDF_set_border_style ( resource pdfdoc, string style, float width )

Sets the border style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the options borderstyle and linewidth in PDF_create_annotation() instead.

Prev | Home | Next
PDF_set_border_dash | Up | PDF_set_char_spacing


PDF_set_char_spacing

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_char_spacing -- Set character spacing [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter charspacing instead.

Prev | Home | Next
PDF_set_border_style | Up | PDF_set_duration


PDF_set_duration

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_duration -- Set duration between pages [deprecated]

Description

This function is deprecated since PDFlib version 3, use the duration option in PDF_begin_page_ext() or PDF_end_page_ext() instead.

Prev | Home | Next
PDF_set_char_spacing | Up | PDF_set_gstate


PDF_set_horiz_scaling

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_horiz_scaling -- Set horizontal text scaling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter horizscaling instead.

Prev | Home | Next
PDF_set_gstate | Up | PDF_set_info_author


PDF_set_info_author

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_info_author -- Fill the author document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

Prev | Home | Next
PDF_set_horiz_scaling | Up | PDF_set_info_creator


PDF_set_info_creator

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_info_creator -- Fill the creator document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

Prev | Home | Next
PDF_set_info_author | Up | PDF_set_info_keywords


PDF_set_info_keywords

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_info_keywords -- Fill the keywords document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

Prev | Home | Next
PDF_set_info_creator | Up | PDF_set_info_subject


PDF_set_info_subject

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_info_subject -- Fill the subject document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

Prev | Home | Next
PDF_set_info_keywords | Up | PDF_set_info_title


PDF_set_info_title

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_info_title -- Fill the title document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

Prev | Home | Next
PDF_set_info_subject | Up | PDF_set_info


PDF_set_info

(PHP 4 >= 4.0.1, PECL)

PDF_set_info -- Fill document info field

Description

bool PDF_set_info ( resource p, string key, string value )

Fill document information field key with value. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_set_info_title | Up | PDF_set_layer_dependency


PDF_set_leading

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_leading -- Set distance between text lines [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the parameter leading instead.

Prev | Home | Next
PDF_set_layer_dependency | Up | PDF_set_parameter


PDF_set_parameter

(PHP 4, PECL)

PDF_set_parameter -- Set string parameter

Description

bool PDF_set_parameter ( resource p, string key, string value )

Sets some PDFlib parameter with string type. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_set_leading | Up | PDF_set_text_matrix


PDF_set_text_matrix

(PHP 3 >= 3.0.6)

PDF_set_text_matrix -- Set text matrix [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_scale(), PDF_translate(), PDF_rotate(), or PDF_skew() instead.

Prev | Home | Next
PDF_set_parameter | Up | PDF_set_text_pos


PDF_set_text_pos

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_text_pos -- Set text position

Description

bool PDF_set_text_pos ( resource p, float x, float y )

Sets the position for text output on the page. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_set_text_matrix | Up | PDF_set_text_rendering


PDF_set_text_rendering

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_text_rendering -- Determine text rendering [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrendering parameter instead.

Prev | Home | Next
PDF_set_text_pos | Up | PDF_set_text_rise


PDF_set_text_rise

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_text_rise -- Set text rise [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrise parameter instead.

Prev | Home | Next
PDF_set_text_rendering | Up | PDF_set_value


PDF_set_value

(PHP 4 >= 4.0.1, PECL)

PDF_set_value -- Set numerical parameter

Description

bool PDF_set_value ( resource p, string key, float value )

Sets the value of some PDFlib parameter with numerical type. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_set_text_rise | Up | PDF_set_word_spacing


PDF_set_word_spacing

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_set_word_spacing -- Set spacing between words [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the wordspacing parameter instead.

Prev | Home | Next
PDF_set_value | Up | PDF_setcolor


PDF_setcolor

(PHP 4 >= 4.0.5, PECL)

PDF_setcolor -- Set fill and stroke color

Description

bool PDF_setcolor ( resource p, string fstype, string colorspace, float c1, float c2, float c3, float c4 )

Sets the current color space and color. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_set_word_spacing | Up | PDF_setdash


PDF_setdash

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setdash -- Set simple dash pattern

Description

bool PDF_setdash ( resource pdfdoc, float b, float w )

Sets the current dash pattern to b black and w white units. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setcolor | Up | PDF_setdashpattern


PDF_setflat

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setflat -- Set flatness

Description

bool PDF_setflat ( resource pdfdoc, float flatness )

Sets the flatness parameter. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setdashpattern | Up | PDF_setfont


PDF_setfont

(PHP 4 >= 4.0.5, PECL)

PDF_setfont -- Set font

Description

bool PDF_setfont ( resource pdfdoc, int font, float fontsize )

Sets the current font in the specified size, using a font handle returned by PDF_load_font(). Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setflat | Up | PDF_setgray_fill


PDF_setgray_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setgray_fill -- Set fill color to gray [deprecated]

Description

bool PDF_setgray_fill ( resource p, float g )

Sets the current fill color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setfont | Up | PDF_setgray_stroke


PDF_setgray_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setgray_stroke -- Set stroke color to gray [deprecated]

Description

bool PDF_setgray_stroke ( resource p, float g )

Sets the current stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setgray_fill | Up | PDF_setgray


PDF_setgray

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setgray -- Set color to gray [deprecated]

Description

bool PDF_setgray ( resource p, float g )

Sets the current fill and stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setgray_stroke | Up | PDF_setlinecap


PDF_setlinecap

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setlinecap -- Set linecap parameter

Description

bool PDF_setlinecap ( resource p, int linecap )

Sets the linecap parameter to control the shape at the end of a path with respect to stroking.

Prev | Home | Next
PDF_setgray | Up | PDF_setlinejoin


PDF_setlinejoin

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setlinejoin -- Set linejoin parameter

Description

bool PDF_setlinejoin ( resource p, int value )

Sets the linejoin parameter to specify the shape at the corners of paths that are stroked. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setlinecap | Up | PDF_setlinewidth


PDF_setlinewidth

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setlinewidth -- Set line width

Description

bool PDF_setlinewidth ( resource p, float width )

Sets the current line width. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setlinejoin | Up | PDF_setmatrix


PDF_setmatrix

(PHP 4 >= 4.0.5, PECL)

PDF_setmatrix -- Set current transformation matrix

Description

bool PDF_setmatrix ( resource p, float a, float b, float c, float d, float e, float f )

Explicitly sets the current transformation matrix. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setlinewidth | Up | PDF_setmiterlimit


PDF_setmiterlimit

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setmiterlimit -- Set miter limit

Description

bool PDF_setmiterlimit ( resource pdfdoc, float miter )

Sets the miter limit.Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setmatrix | Up | PDF_setpolydash


PDF_setpolydash

(PHP 4 >= 4.0.5, PECL)

PDF_setpolydash -- Set complicated dash pattern [deprecated]

Description

This function is deprecated since PDFlib version 5, use PDF_setdashpattern() instead.

Prev | Home | Next
PDF_setmiterlimit | Up | PDF_setrgbcolor_fill


PDF_setrgbcolor_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setrgbcolor_fill -- Set fill rgb color values [deprecated]

Description

bool PDF_setrgbcolor_fill ( resource p, float red, float green, float blue )

Sets the current fill color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setpolydash | Up | PDF_setrgbcolor_stroke


PDF_setrgbcolor_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setrgbcolor_stroke -- Set stroke rgb color values [deprecated]

Description

bool PDF_setrgbcolor_stroke ( resource p, float red, float green, float blue )

Sets the current stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setrgbcolor_fill | Up | PDF_setrgbcolor


PDF_setrgbcolor

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_setrgbcolor -- Set fill and stroke rgb color values [deprecated]

Description

bool PDF_setrgbcolor ( resource p, float red, float green, float blue )

Sets the current fill and stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

Prev | Home | Next
PDF_setrgbcolor_stroke | Up | PDF_shading_pattern


PDF_show_boxed

(PHP 4, PECL)

PDF_show_boxed -- Output text in a box [deprecated]

Description

int PDF_show_boxed ( resource p, string text, float left, float top, float width, float height, string mode, string feature )

This function is deprecated since PDFlib version 6, use PDF_fit_textline() for single lines, or the PDF_*_textflow() functions for multi-line formatting instead.

Prev | Home | Next
PDF_shfill | Up | PDF_show_xy


PDF_show_xy

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_show_xy -- Output text at given position

Description

bool PDF_show_xy ( resource p, string text, float x, float y )

Prints text in the current font. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_show_boxed | Up | PDF_show


PDF_show

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_show -- Output text at current position

Description

bool PDF_show ( resource pdfdoc, string text )

Prints text in the current font and size at the current position. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_show_xy | Up | PDF_skew


PDF_skew

(PHP 4, PECL)

PDF_skew -- Skew the coordinate system

Description

bool PDF_skew ( resource p, float alpha, float beta )

Skews the coordinate system in x and y direction by alpha and beta degrees. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_show | Up | PDF_stringwidth


PDF_stringwidth

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_stringwidth -- Return width of text

Description

float PDF_stringwidth ( resource p, string text, int font, float fontsize )

Returns the width of text in an arbitrary font.

Prev | Home | Next
PDF_skew | Up | PDF_stroke


PDF_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_stroke -- Stroke path

Description

bool PDF_stroke ( resource p )

Strokes the path with the current color and line width, and clear it. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_stringwidth | Up | PDF_suspend_page


PDF_translate

(PHP 3 >= 3.0.6, PHP 4, PECL)

PDF_translate -- Set origin of coordinate system

Description

bool PDF_translate ( resource p, float tx, float ty )

Translates the origin of the coordinate system.

Prev | Home | Next
PDF_suspend_page | Up | PDF_utf16_to_utf8


PDO Functions

PHP Manual
Prev Next

CXX. PDO Functions

Introduction

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.

Installation

PHP 5.1 and up on Unix systems

  1. If you're running a PHP 5.1 release, PDO and PDO_SQLITE is included in the distribution; it will be automatically enabled when you run configure. It is recommended that you build PDO as a shared extension, as this will allow you to take advantage of updates that are made available via PECL. The recommended configure line for building PHP with PDO support should enable zlib support (for the pecl installer) as well. You may also need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that, but note that if you build PDO as a shared extension, you must build the PDO drivers as shared extensions. SQLite extension depends on PDO so if PDO is built as a shared extension, SQLite needs to be built the same way.

    ./configure --with-zlib --enable-pdo=shared --with-pdo-sqlite=shared --with-sqlite=shared

  2. After installing PDO as a shared module, you must edit your php.ini file so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the pdo.so line, as PDO must be initialized before the database-specific extensions can be loaded. If you built PDO and the database-specific extensions statically, you can skip this step.

    extension=pdo.so

  3. Having PDO as a shared module will allow you to run pecl upgrade pdo as new versions of PDO are published, without forcing you to rebuild the whole of PHP. Note that if you do this, you also need to upgrade your database specific PDO drivers at the same time.

PHP 5.0 and up on Unix systems

  1. PDO is available as a PECL extension from http://pecl.php.net/package/pdo. Installation can be performed via the pecl tool; this is enabled by default when you configure PHP. You should ensure that PHP was configured --with-zlib in order for pecl to be able to handle the compressed package files.

  2. Run the following command to download, build, and install the latest stable version of PDO:

    pecl install pdo

  3. The pecl command automatically installs the PDO module into your PHP extensions directory. To enable the PDO extension on Linux or Unix operating systems, you must add the following line to php.ini:

    extension=pdo.so

    For more information about building PECL packages, consult the PECL installation section of the manual.

Windows users running PHP 5.1 and up

  1. PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:

    extension=php_pdo.dll

  2. Next, choose the other database-specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:

    extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll

    These DLLs should exist in the system's extension_dir. Note that PDO_INFORMIX is only available as a PECL extension.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. PDO Configuration Options

Name | Default | Changeable | Changelog
pdo.dsn.* |  | php.ini only |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

pdo.dsn.* string

Defines DSN alias. See PDO->__construct() for thorough explanation.

PDO Drivers

The following drivers currently implement the PDO interface:

Driver name | Supported databases
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird/Interbase 6
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x
PDO_OCI | Oracle Call Interface
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL | PostgreSQL
PDO_SQLITE | SQLite 3 and SQLite 2

Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Example 1. Connecting to MySQL

&#60;?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?&#62;

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Example 2. Handling connection errors

&#60;?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   foreach ($dbh-&#62;query('SELECT * from FOO') as $row) {
      print_r($row);
   }
   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e-&#62;getMessage() . "&#60;br/&#62;";
   die();
}
?&#62;

Warning

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Example 3. Closing a connection

&#60;?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
?&#62;

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Example 4. Persistent connections

&#60;?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
  PDO::ATTR_PERSISTENT =&#62; true
));
?&#62;

Note: If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Transactions and auto-commit

Now that you're connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.

Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).

Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO->beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO->commit() or PDO->rollBack() to finish it, depending on the success of the code you run during the transaction.

When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.

Warning

The automatic rollback only happens if you initiate the transaction via PDO->beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens.

Example 5. Executing a batch in a transaction

In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO->beginTransaction() and PDO->commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.

&#60;?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT =&#62; true));
  echo "Connected\n";
  $dbh-&#62;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh-&#62;beginTransaction();
  $dbh-&#62;exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh-&#62;exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())");
  $dbh-&#62;commit();

} catch (Exception $e) {
  $dbh-&#62;rollBack();
  echo "Failed: " . $e-&#62;getMessage();
}
?&#62;

You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. In truth, this isn't 100% correct, but it is a good-enough introduction, if you've never heard of transactions before.

Prepared statements and stored procedures

Many of the more mature databases support the concept of prepared statements. What are they? You can think of them as a kind of compiled template for the SQL that you want to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize it's plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down your application if you need to repeat the same query many times with different parameters. By using a prepared statement you avoid repeating the analyze/compile/optimize cycle. In short, prepared statements use fewer resources and thus run faster.

  • The parameters to prepared statements don't need to be quoted; the driver handles it for you. If your application exclusively uses prepared statements, you can be sure that no SQL injection will occur. (However, if you're still building up other parts of the query based on untrusted input, you're still at risk).

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that you will be able to use the same data access paradigm regardless of the capabilities of the database.

Example 6. Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the named placeholders.

&#60;?php
$stmt = $dbh-&#62;prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt-&#62;bindParam(':name', $name);
$stmt-&#62;bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt-&#62;execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt-&#62;execute();
?&#62;

Example 7. Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

&#60;?php
$stmt = $dbh-&#62;prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt-&#62;bindParam(1, $name);
$stmt-&#62;bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt-&#62;execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt-&#62;execute();
?&#62;

Example 8. Fetching data using prepared statements

This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.

&#60;?php
$stmt = $dbh-&#62;prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt-&#62;execute(array($_GET['name']))) {
  while ($row = $stmt-&#62;fetch()) {
    print_r($row);
  }
}
?&#62;

If the database driver supports it, you may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that you must know how large a given parameter might be when you bind it. If the value turns out to be larger than the size you suggested, an error is raised.

Example 9. Calling a stored procedure with an output parameter

&#60;?php
$stmt = $dbh-&#62;prepare("CALL sp_returns_string(?)");
$stmt-&#62;bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// call the stored procedure
$stmt-&#62;execute();

print "procedure returned $return_value\n";
?&#62;

You may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.

Example 10. Calling a stored procedure with an input/output parameter

&#60;?php
$stmt = $dbh-&#62;prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt-&#62;bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// call the stored procedure
$stmt-&#62;execute();

print "procedure returned $value\n";
?&#62;

Example 11. Invalid use of placeholder

&#60;?php
$stmt = $dbh-&#62;prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt-&#62;execute(array($_GET['name']));

// placeholder must be used in the place of the whole value
$stmt = $dbh-&#62;prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt-&#62;execute(array("%$_GET[name]%"));
?&#62;

Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

  • PDO::ERRMODE_SILENT

    This is the default mode. PDO will simply set the error code for you to inspect using the PDO->errorCode() and PDO->errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement->errorCode() or PDOStatement->errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

  • PDO::ERRMODE_WARNING

    In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.

  • PDO::ERRMODE_EXCEPTION

    In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

    Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

    See Exceptions for more information about Exceptions in PHP.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO->errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO->errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Large Objects (LOBs)

At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the PDO::PARAM_LOB type code in your PDOStatement->bindParam() or PDOStatement->bindColumn() calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

Example 12. Displaying an image from a database

This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.

&#60;?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db-&#62;prepare("select contenttype, imagedata from images where id=?");
$stmt-&#62;execute(array($_GET['id']));
$stmt-&#62;bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt-&#62;bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt-&#62;fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?&#62;

Example 13. Inserting an image into a database

This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.

&#60;?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db-&#62;prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt-&#62;bindParam(1, $id);
$stmt-&#62;bindParam(2, $_FILES['file']['type']);
$stmt-&#62;bindParam(3, $fp, PDO::PARAM_LOB);

$stmt-&#62;beginTransaction();
$stmt-&#62;execute();
$stmt-&#62;commit();
?&#62;

Example 14. Inserting an image into a database: Oracle

Oracle requires a slightly different syntax for inserting a lob from a file. It's also essential that you perform the insert under a transaction, otherwise your newly inserted LOB will be committed with a zero-length as part of the implicit commit that happens when the query is executed:

&#60;?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db-&#62;prepare("insert into images (id, contenttype, imagedata) " .
  "VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt-&#62;bindParam(1, $id);
$stmt-&#62;bindParam(2, $_FILES['file']['type']);
$stmt-&#62;bindParam(3, $fp, PDO::PARAM_LOB);

$stmt-&#62;beginTransaction();
$stmt-&#62;execute();
$stmt-&#62;commit();
?&#62;

Predefined Classes

PDO

Represents a connection between PHP and a database server.

Constructor

  • PDO - constructs a new PDO object

Methods

  • beginTransaction - begins a transaction

  • commit - commits a transaction

  • errorCode - retrieves an error code, if any, from the database

  • errorInfo - retrieves an array of error information, if any, from the database

  • exec - issues an SQL statement and returns the number of affected rows

  • getAttribute - retrieves a database connection attribute

  • lastInsertId - retrieves the value of the last row that was inserted into a table

  • prepare - prepares an SQL statement for execution

  • query - issues an SQL statement and returns a result set

  • quote - returns a quoted version of a string for use in SQL statements

  • rollBack - roll back a transaction

  • setAttribute - sets a database connection attribute

PDOStatement

Represents a prepared statement and, after the statement is executed, an associated result set.

Methods

  • bindColumn - binds a PHP variable to an output column in a result set

  • bindParam - binds a PHP variable to a parameter in the prepared statement

  • bindValue - binds a value to a parameter in the prepared statement

  • closeCursor - closes the cursor, allowing the statement to be executed again

  • columnCount - returns the number of columns in the result set

  • errorCode - retrieves an error code, if any, from the statement

  • errorInfo - retrieves an array of error information, if any, from the statement

  • execute - executes a prepared statement

  • fetch - fetches a row from a result set

  • fetchAll - fetches an array containing all of the rows from a result set

  • fetchColumn - returns the data from a single column in a result set

  • getAttribute - retrieves a PDOStatement attribute

  • getColumnMeta - retrieves metadata for a column in the result set

  • nextRowset - retrieves the next rowset (result set)

  • rowCount - returns the number of rows that were affected by the execution of an SQL statement

  • setAttribute - sets a PDOStatement attribute

  • setFetchMode - sets the fetch mode for a PDOStatement

PDOException

Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

Example 15. The PDOException class

&#60;?php
class PDOException extends Exception
{
    public $errorInfo = null;    // corresponds to PDO::errorInfo()
                                 // or PDOStatement::errorInfo()
    protected $message;          // textual error message
                                 // use Exception::getMessage() to access it
    protected $code;             // SQLSTATE error code
                                 // use Exception::getCode() to access it
}
?&#62;

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.

Warning

PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL.

PDO::PARAM_BOOL (integer)

Represents a boolean data type.

PDO::PARAM_NULL (integer)

Represents the SQL NULL data type.

PDO::PARAM_INT (integer)

Represents the SQL INTEGER data type.

PDO::PARAM_STR (integer)

Represents the SQL CHAR, VARCHAR, or other string data type.

PDO::PARAM_LOB (integer)

Represents the SQL large object data type.

PDO::PARAM_STMT (integer)

Represents a recordset type. Not currently supported by any drivers.

PDO::PARAM_INPUT_OUTPUT (integer)

Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.

PDO::FETCH_LAZY (integer)

Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.

PDO::FETCH_ASSOC (integer)

Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.

PDO::FETCH_NAMED (integer)

Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.

PDO::FETCH_NUM (integer)

Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.

PDO::FETCH_BOTH (integer)

Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.

PDO::FETCH_OBJ (integer)

Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.

PDO::FETCH_BOUND (integer)

Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.

PDO::FETCH_COLUMN (integer)

Specifies that the fetch method shall return only a single requested column from the next row in the result set.

PDO::FETCH_CLASS (integer)

Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

PDO::FETCH_INTO (integer)

Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.

PDO::FETCH_FUNC (integer)

PDO::FETCH_GROUP (integer)

PDO::FETCH_UNIQUE (integer)

PDO::FETCH_CLASSTYPE (integer)

PDO::FETCH_SERIALIZE (integer)

Available since PHP 5.1.0.

PDO::FETCH_PROPS_LATE (integer)

Available since PHP 5.2.0

PDO::ATTR_AUTOCOMMIT (integer)

If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.

PDO::ATTR_PREFETCH (integer)

Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.

PDO::ATTR_TIMEOUT (integer)

Sets the timeout value in seconds for communications with the database.

PDO::ATTR_ERRMODE (integer)

See the Errors and error handling section for more information about this attribute.

PDO::ATTR_SERVER_VERSION (integer)

This is a read only attribute; it will return information about the version of the database server to which PDO is connected.

PDO::ATTR_CLIENT_VERSION (integer)

This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.

PDO::ATTR_SERVER_INFO (integer)

This is a read only attribute; it will return some meta information about the database server to which PDO is connected.

PDO::ATTR_CONNECTION_STATUS (integer)

PDO::ATTR_CASE (integer)

Force column names to a specific case specified by the PDO::CASE_* constants.

PDO::ATTR_CURSOR_NAME (integer)

Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.

PDO::ATTR_CURSOR (integer)

Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.

PDO::ATTR_DRIVER_NAME (string)

Returns the name of the driver.

Example 16. using PDO::ATTR_DRIVER_NAME

&#60;?php
if ($db-&#62;getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?&#62;

PDO::ATTR_ORACLE_NULLS (integer)

Convert empty strings to SQL NULL values on data fetches.

PDO::ATTR_PERSISTENT (integer)

Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.

PDO::ATTR_STATEMENT_CLASS (integer)

PDO::ATTR_FETCH_CATALOG_NAMES (integer)

Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.

PDO::ATTR_FETCH_TABLE_NAMES (integer)

Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.

PDO::ATTR_STRINGIFY_FETCHES (integer)

PDO::ATTR_MAX_COLUMN_LEN (integer)

PDO::ATTR_DEFAULT_FETCH_MODE (integer)

Available since PHP 5.2.0

PDO::ATTR_EMULATE_PREPARES (integer)

Available since PHP 5.1.3.

PDO::ERRMODE_SILENT (integer)

Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.

PDO::ERRMODE_WARNING (integer)

Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.

PDO::ERRMODE_EXCEPTION (integer)

Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.

PDO::CASE_NATURAL (integer)

Leave column names as returned by the database driver.

PDO::CASE_LOWER (integer)

Force column names to lower case.

PDO::CASE_UPPER (integer)

Force column names to upper case.

PDO::NULL_NATURAL (integer)

PDO::NULL_EMPTY_STRING (integer)

PDO::NULL_TO_STRING (integer)

PDO::FETCH_ORI_NEXT (integer)

Fetch the next row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_PRIOR (integer)

Fetch the previous row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_FIRST (integer)

Fetch the first row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_LAST (integer)

Fetch the last row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_ABS (integer)

Fetch the requested row by row number from the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_REL (integer)

Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.

PDO::CURSOR_FWDONLY (integer)

Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.

PDO::CURSOR_SCROLL (integer)

Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.

PDO::ERR_NONE (string)

Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.

PDO::PARAM_EVT_ALLOC (integer)

Allocation event

PDO::PARAM_EVT_FREE (integer)

Deallocation event

PDO::PARAM_EVT_EXEC_PRE (integer)

Event triggered prior to execution of a prepared statement.

PDO::PARAM_EVT_EXEC_POST (integer)

Event triggered subsequent to execution of a prepared statement.

PDO::PARAM_EVT_FETCH_PRE (integer)

Event triggered prior to fetching a result from a resultset.

PDO::PARAM_EVT_FETCH_POST (integer)

Event triggered subsequent to fetching a result from a resultset.

PDO::PARAM_EVT_NORMALIZE (integer)

Event triggered during bound parameter registration allowing the driver to normalize the parameter name.

Table of Contents
PDO->beginTransaction() -- Initiates a transaction
PDO->commit() -- Commits a transaction
PDO->__construct() -- Creates a PDO instance representing a connection to a database
PDO->errorCode() -- Fetch the SQLSTATE associated with the last operation on the database handle
PDO->errorInfo() -- Fetch extended error information associated with the last operation on the database handle
PDO->exec() -- Execute an SQL statement and return the number of affected rows
PDO->getAttribute() -- Retrieve a database connection attribute
PDO->getAvailableDrivers() -- Return an array of available PDO drivers
PDO->lastInsertId() -- Returns the ID of the last inserted row or sequence value
PDO->prepare() -- Prepares a statement for execution and returns a statement object
PDO->query() -- Executes an SQL statement, returning a result set as a PDOStatement object
PDO->quote() -- Quotes a string for use in a query.
PDO->rollBack() -- Rolls back a transaction
PDO->setAttribute() -- Set an attribute
PDOStatement->bindColumn() -- Bind a column to a PHP variable
PDOStatement->bindParam() -- Binds a parameter to the specified variable name
PDOStatement->bindValue() -- Binds a value to a parameter
PDOStatement->closeCursor() -- Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() -- Returns the number of columns in the result set
PDOStatement->errorCode() -- Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() -- Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() -- Executes a prepared statement
PDOStatement->fetch() -- Fetches the next row from a result set
PDOStatement->fetchAll() -- Returns an array containing all of the result set rows
PDOStatement->fetchColumn() -- Returns a single column from the next row of a result set
PDOStatement->fetchObject() -- Fetches the next row and returns it as an object.
PDOStatement->getAttribute() -- Retrieve a statement attribute
PDOStatement->getColumnMeta() -- Returns metadata for a column in a result set
PDOStatement->nextRowset() -- Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() -- Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() -- Set a statement attribute
PDOStatement->setFetchMode() -- Set the default fetch mode for this statement

Prev | Home | Next
PDF_utf8_to_utf16 | Up | PDO->beginTransaction()


PDO->beginTransaction()

(no version information, might be only in CVS)

PDO->beginTransaction() -- Initiates a transaction

Description

class PDO {

bool beginTransaction ( void )

}

Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO->commit(). Calling PDO->rollBack() will roll back all changes to the database and return the connection to autocommit mode.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

&#60;?php
/* Begin a transaction, turning off autocommit */
$dbh-&#62;beginTransaction();

/* Change the database schema and data */
$sth = $dbh-&#62;exec("DROP TABLE fruit");
$sth = $dbh-&#62;exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh-&#62;rollBack();

/* Database connection is now back in autocommit mode */
?&#62;

See Also

PDO->commit()
PDO->rollBack()

Prev | Home | Next
PDO Functions | Up | PDO->commit()


PDO->commit()

(no version information, might be only in CVS)

PDO->commit() -- Commits a transaction

Description

class PDO {

bool commit ( void )

}

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO->beginTransaction() starts a new transaction.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Commit a transaction

&#60;?php
/* Begin a transaction, turning off autocommit */
$dbh-&#62;beginTransaction();

/* Change the database schema */
$sth = $dbh-&#62;exec("DROP TABLE fruit");

/* Commit the changes */
$dbh-&#62;commit();

/* Database connection is now back in autocommit mode */
?&#62;

See Also

PDO->beginTransaction()
PDO->rollBack()

Prev | Home | Next
PDO->beginTransaction() | Up | PDO->__construct()


PDO->__construct()

(no version information, might be only in CVS)

PDO->__construct() -- Creates a PDO instance representing a connection to a database

Description

class PDO {

PDO __construct ( string dsn [, string username [, string password [, array driver_options]]] )

}

Creates a PDO instance to represent a connection to the requested database.

Parameters

dsn

The Data Source Name, or DSN, contains the information required to connect to the database.

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

Driver invocation

dsn contains the full DSN.

URI invocation

dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

uri:file:///path/to/dsnfile

Aliasing

dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.

Note: The alias must be defined in php.ini, and not .htaccess or httpd.conf

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

Return Values

Returns a PDO object on success.

Errors/Exceptions

PDO->__construct() throws a PDOException if the attempt to connect to the requested database fails.

Examples

Example 1. Create a PDO instance via driver invocation

&#60;?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e-&#62;getMessage();
}

?&#62;

Example 2. Create a PDO instance via URI invocation

The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

odbc:DSN=SAMPLE;UID=john;PWD=mypass

The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:

&#60;?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e-&#62;getMessage();
}

?&#62;

Example 3. Create a PDO instance using an alias

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"

&#60;?php
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e-&#62;getMessage();
}

?&#62;

Prev | Home | Next
PDO->commit() | Up | PDO->errorCode()


PDO->errorCode()

(no version information, might be only in CVS)

PDO->errorCode() -- Fetch the SQLSTATE associated with the last operation on the database handle

Description

class PDO {

string errorCode ( void )

}

Return Values

Returns a SQLSTATE, a five-character alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two-character class value followed by a three-character subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.

PDO->errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO->prepare() or PDO->query() and invoke an error on the statement handle, PDO->errorCode() will not reflect that error. You must call PDOStatement->errorCode() to return the error code for an operation performed on a particular statement handle.

Examples

Example 1. Retrieving a SQLSTATE code

&#60;?php
/* Provoke an error -- the BONES table does not exist */
$dbh-&#62;exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ";
print $dbh-&#62;errorCode();
?&#62;

The above example will output:

PDO::errorCode(): 42S02

See Also

PDO->errorInfo()
PDOStatement->errorCode()
PDOStatement->errorInfo()

Prev | Home | Next
PDO->__construct() | Up | PDO->errorInfo()


PDO->errorInfo()

(no version information, might be only in CVS)

PDO->errorInfo() -- Fetch extended error information associated with the last operation on the database handle

Description

class PDO {

array errorInfo ( void )

}

Return Values

PDO->errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

PDO->errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO->prepare() or PDO->query() and invoke an error on the statement handle, PDO->errorInfo() will not reflect the error from the statement handle. You must call PDOStatement->errorInfo() to return the error information for an operation performed on a particular statement handle.

Examples

Example 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

&#60;?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh-&#62;prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh-&#62;errorInfo());
}
?&#62;

The above example will output:

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

See Also

PDO->errorCode()
PDOStatement->errorCode()
PDOStatement->errorInfo()

Prev | Home | Next
PDO->errorCode() | Up | PDO->exec()


PDO->exec()

(no version information, might be only in CVS)

PDO->exec() -- Execute an SQL statement and return the number of affected rows

Description

class PDO {

int exec ( string statement )

}

PDO->exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.

PDO->exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO->query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO->prepare() and issue the statement with PDOStatement->execute().

Parameters

statement

The SQL statement to prepare and execute.

Return Values

PDO->exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO->exec() returns 0.

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.

The following example incorrectly relies on the return value of PDO->exec(), wherein a statement that affected 0 rows results in a call to die():

&#60;?php
$db-&#62;exec() or die($db-&#62;errorInfo());
?&#62;

Examples

Example 1. Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

&#60;?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* Delete all rows from the FRUIT table */
$count = $dbh-&#62;exec("DELETE FROM fruit WHERE colour = 'red'");

/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?&#62;

The above example will output:

Deleted 1 rows.

See Also

PDO->prepare()
PDO->query()
PDOStatement->execute()

Prev | Home | Next
PDO->errorInfo() | Up | PDO->getAttribute()


PDO->getAttribute()

(no version information, might be only in CVS)

PDO->getAttribute() -- Retrieve a database connection attribute

Description

class PDO {

mixed getAttribute ( int attribute )

}

This function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement->getAttribute().

Note that some database/driver combinations may not support all of the database connection attributes.

Parameters

attribute

One of the PDO::ATTR_* constants. The constants that apply to database connections are as follows:

PDO::ATTR_AUTOCOMMIT
PDO::ATTR_CASE
PDO::ATTR_CLIENT_VERSION
PDO::ATTR_CONNECTION_STATUS
PDO::ATTR_DRIVER_NAME
PDO::ATTR_ERRMODE
PDO::ATTR_ORACLE_NULLS
PDO::ATTR_PERSISTENT
PDO::ATTR_PREFETCH
PDO::ATTR_SERVER_INFO
PDO::ATTR_SERVER_VERSION
PDO::ATTR_TIMEOUT

Return Values

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

Examples

Example 1. Retrieving database connection attributes

&#60;?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
    "AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
    "ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
    "TIMEOUT"
);

foreach ($attributes as $val) {
    echo "PDO::ATTR_$val: ";
    echo $conn-&#62;getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?&#62;

See Also

PDO->setAttribute()
PDOStatement->getAttribute()
PDOStatement->setAttribute()

Prev | Home | Next
PDO->exec() | Up | PDO->getAvailableDrivers()


PDO->lastInsertId()

(no version information, might be only in CVS)

PDO->lastInsertId() -- Returns the ID of the last inserted row or sequence value

Description

class PDO {

string lastInsertId ( [string name] )

}

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

Note: This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

Parameters

name

Name of the sequence object from which the ID should be returned.

Return Values

If a sequence name was not specified for the name parameter, PDO->lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.

If a sequence name was specified for the name parameter, PDO->lastInsertId() returns a string representing the last value retrieved from the specified sequence object.

If the PDO driver does not support this capability, PDO->lastInsertId() triggers an IM001 SQLSTATE.

Prev | Home | Next
PDO->getAvailableDrivers() | Up | PDO->prepare()


PDO->prepare()

(no version information, might be only in CVS)

PDO->prepare() -- Prepares a statement for execution and returns a statement object

Description

class PDO {

PDOStatement prepare ( string statement [, array driver_options] )

}

Prepares an SQL statement to be executed by the PDOStatement->execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style.

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement->execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

Calling PDO->prepare() and PDOStatement->execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

Parameters

statement

This must be a valid SQL statement for the target database server.

driver_options

This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.

Return Values

If the database server successfully prepares the statement, PDO->prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO->prepare() returns FALSE.

Examples

Example 1. Prepare an SQL statement with named parameters

&#60;?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; :calories AND colour = :colour';
$sth = $dbh-&#62;prepare($sql, array(PDO::ATTR_CURSOR =&#62; PDO::CURSOR_FWDONLY));
$sth-&#62;execute(array(':calories' =&#62; 150, ':colour' =&#62; 'red'));
$red = $sth-&#62;fetchAll();
$sth-&#62;execute(array('calories' =&#62; 175, 'colour' =&#62; 'yellow'));
$yellow = $sth-&#62;fetchAll();
?&#62;

Example 2. Prepare an SQL statement with question mark parameters

&#60;?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; ? AND colour = ?');
$sth-&#62;execute(array(150, 'red'));
$red = $sth-&#62;fetchAll();
$sth-&#62;execute(array(175, 'yellow'));
$yellow = $sth-&#62;fetchAll();
?&#62;

See Also

PDO->exec()
PDO->query()
PDOStatement->execute()

Prev | Home | Next
PDO->lastInsertId() | Up | PDO->query()


PDO->query()

(no version information, might be only in CVS)

PDO->query() -- Executes an SQL statement, returning a result set as a PDOStatement object

Description

class PDO {

PDOStatement query ( string statement )

}class PDO {

bool query ( string statement, int PDO::FETCH_COLUMN, int colno )

}class PDO {

bool query ( string statement, int PDO::FETCH_CLASS, string classname, array ctorargs )

}class PDO {

bool query ( string statement, int PDO::FETCH_INTO, object object )

}

PDO->query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.

For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO->prepare() and issue the statement with multiple calls to PDOStatement->execute().

If you do not fetch all of the data in a result set before issuing your next call to PDO->query(), your call may fail. Call PDOStatement->closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO->query().

Note: Although this function is only documented as having a single parameter, you may pass additional arguments to this function. They will be treated as though you called PDOStatement->setFetchMode() on the resultant statement object.

Parameters

statement

The SQL statement to prepare and execute.

Return Values

PDO->query() returns a PDOStatement object.

Examples

Example 1. Demonstrate PDO::query

A nice feature of PDO->query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.

&#60;?php
function getFruit($conn) {
    $sql = 'SELECT name, colour, calories FROM fruit ORDER BY name';
    foreach ($conn-&#62;query($sql) as $row) {
        print $row['NAME'] . "\t";
        print $row['COLOUR'] . "\t";
        print $row['CALORIES'] . "\n";
    }
}
?&#62;

The above example will output:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

See Also

PDO->exec()
PDO->prepare()
PDOStatement->execute()

Prev | Home | Next
PDO->prepare() | Up | PDO->quote()


PDO->quote()

(no version information, might be only in CVS)

PDO->quote() -- Quotes a string for use in a query.

Description

class PDO {

string quote ( string string [, int parameter_type] )

}

PDO->quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO->prepare() to prepare SQL statements with bound parameters instead of using PDO->quote() to interpolate user input into a SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Parameters

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles. The default value is PDO::PARAM_STR.

Return Values

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

Examples

Example 1. Quoting a normal string

&#60;?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn-&#62;quote($string) . "\n";
?&#62;

The above example will output:

Unquoted string: Nice
Quoted string: 'Nice'

Example 2. Quoting a dangerous string

&#60;?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn-&#62;quote($string) . "\n";
?&#62;

The above example will output:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example 3. Quoting a complex string

&#60;?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn-&#62;quote($string) . "\n";
?&#62;

The above example will output:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

See Also

PDO->prepare()
PDOStatement->execute()

Prev | Home | Next
PDO->query() | Up | PDO->rollBack()


PDO->rollBack()

(no version information, might be only in CVS)

PDO->rollBack() -- Rolls back a transaction

Description

class PDO {

bool rollBack ( void )

}

Rolls back the current transaction, as initiated by PDO->beginTransaction(). It is an error to call this method if no transaction is active.

If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

&#60;?php
/* Begin a transaction, turning off autocommit */
$dbh-&#62;beginTransaction();

/* Change the database schema and data */
$sth = $dbh-&#62;exec("DROP TABLE fruit");
$sth = $dbh-&#62;exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh-&#62;rollBack();

/* Database connection is now back in autocommit mode */
?&#62;

See Also

PDO->beginTransaction()
PDO->commit()

Prev | Home | Next
PDO->quote() | Up | PDO->setAttribute()


PDO->setAttribute()

(no version information, might be only in CVS)

PDO->setAttribute() -- Set an attribute

Description

class PDO {

bool setAttribute ( int attribute, mixed value )

}

Sets an attribute on the database handle. Some of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.

  • PDO::ATTR_CASE: Force column names to a specific case.

    • PDO::CASE_LOWER: Force column names to lower case.

    • PDO::CASE_NATURAL: Leave column names as returned by the database driver.

    • PDO::CASE_UPPER: Force column names to upper case.

  • PDO::ATTR_ERRMODE: Error reporting.

    • PDO::ERRMODE_SILENT: Just set error codes.

    • PDO::ERRMODE_WARNING: Raise E_WARNING.

    • PDO::ERRMODE_EXCEPTION: Throw exceptions.

  • PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle): Conversion of NULL and empty strings.

    • PDO::NULL_NATURAL: No conversion.

    • PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.

    • PDO::NULL_TO_STRING: NULL is converted to an empty string.

  • PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when fetching. Requires bool.

  • PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

  • PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

  • PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDO->rollBack() | Up | PDOStatement->bindColumn()


PDOStatement->bindColumn()

(no version information, might be only in CVS)

PDOStatement->bindColumn() -- Bind a column to a PHP variable

Description

class PDOStatement {

bool bindColumn ( mixed column, mixed &param [, int type] )

}

PDOStatement->bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement->fetch() or PDOStatement->fetchAll() will update all the variables that are bound to columns.

Note: Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDOStatement->execute().

Parameters

column

Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.

param

Name of the PHP variable to which the column will be bound.

type

Data type of the parameter, specified by the PDO::PARAM_* constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Binding result set output to PHP variables

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.

&#60;?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh-&#62;prepare($sql);
    $stmt-&#62;execute();

    /* Bind by column number */
    $stmt-&#62;bindColumn(1, $name);
    $stmt-&#62;bindColumn(2, $colour);

    /* Bind by column name */
    $stmt-&#62;bindColumn('calories', $cals);

    while ($row = $stmt-&#62;fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e-&#62;getMessage();
  }
}
readData($dbh);
?&#62;

The above example will output:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

See Also

PDOStatement->execute()
PDOStatement->fetch()
PDOStatement->fetchAll()
PDOStatement->fetchColumn()

Prev | Home | Next
PDO->setAttribute() | Up | PDOStatement->bindParam()


PDOStatement->bindParam()

(no version information, might be only in CVS)

PDOStatement->bindParam() -- Binds a parameter to the specified variable name

Description

class PDOStatement {

bool bindParam ( mixed parameter, mixed &variable [, int data_type [, int length [, mixed driver_options]]] )

}

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement->bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement->execute() is called.

Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

Parameters

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.

length

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Execute a prepared statement with named placeholders

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; :calories AND colour = :colour');
$sth-&#62;bindParam(':calories', $calories, PDO::PARAM_INT);
$sth-&#62;bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth-&#62;execute();
?&#62;

Example 2. Execute a prepared statement with question mark placeholders

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; ? AND colour = ?');
$sth-&#62;bindParam(1, $calories, PDO::PARAM_INT);
$sth-&#62;bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth-&#62;execute();
?&#62;

Example 3. Call a stored procedure with an INOUT parameter

&#60;?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh-&#62;prepare('CALL puree_fruit(?)');
$sth-&#62;bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth-&#62;execute();
print("After pureeing fruit, the colour is: $colour");
?&#62;

See Also

PDO->prepare()
PDOStatement->execute()
PDOStatement->bindValue()

Prev | Home | Next
PDOStatement->bindColumn() | Up | PDOStatement->bindValue()


PDOStatement->columnCount()

(no version information, might be only in CVS)

PDOStatement->columnCount() -- Returns the number of columns in the result set

Description

class PDOStatement {

int columnCount ( void )

}

Use PDOStatement->columnCount() to return the number of columns in the result set represented by the PDOStatement object.

If the PDOStatement object was returned from PDO->query(), the column count is immediately available.

If the PDOStatement object was returned from PDO->prepare(), an accurate column count will not be available until you invoke PDOStatement->execute().

Return Values

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement->columnCount() returns 0.

Examples

Example 1. Counting columns

This example demonstrates how PDOStatement->columnCount() operates with and without a result set.

&#60;?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");

/* Count the number of columns in the (non-existent) result set */
$colcount = $sth-&#62;columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");

$sth-&#62;execute();

/* Count the number of columns in the result set */
$colcount = $sth-&#62;columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");

?&#62;

The above example will output:

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

See Also

PDO->prepare()
PDOStatement->execute()
PDOStatement->rowCount()

Prev | Home | Next
PDOStatement->closeCursor() | Up | PDOStatement->errorCode()


PDOStatement->errorCode()

(no version information, might be only in CVS)

PDOStatement->errorCode() -- Fetch the SQLSTATE associated with the last operation on the statement handle

Description

class PDOStatement {

string errorCode ( void )

}

Return Values

Identical to PDO->errorCode(), except that PDOStatement->errorCode() only retrieves error codes for operations performed with PDOStatement objects.

Examples

Example 1. Retrieving a SQLSTATE code

&#60;?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh-&#62;prepare('SELECT skull FROM bones');
$err-&#62;execute();

echo "\nPDOStatement::errorCode(): ";
print $err-&#62;errorCode();
?&#62;

The above example will output:

PDOStatement::errorCode(): 42S02

See Also

PDO->errorCode()
PDO->errorInfo()
PDOStatement->errorInfo()

Prev | Home | Next
PDOStatement->columnCount() | Up | PDOStatement->errorInfo()


PDOStatement->errorInfo()

(no version information, might be only in CVS)

PDOStatement->errorInfo() -- Fetch extended error information associated with the last operation on the statement handle

Description

class PDOStatement {

array errorInfo ( void )

}

Return Values

PDOStatement->errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

Examples

Example 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

&#60;?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh-&#62;prepare('SELECT skull FROM bones');
$sth-&#62;execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth-&#62;errorInfo();
print_r($arr);
?&#62;

The above example will output:

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

See Also

PDO->errorCode()
PDO->errorInfo()
PDOStatement->errorCode()

Prev | Home | Next
PDOStatement->errorCode() | Up | PDOStatement->execute()


PDOStatement->execute()

(no version information, might be only in CVS)

PDOStatement->execute() -- Executes a prepared statement

Description

class PDOStatement {

bool execute ( [array input_parameters] )

}

Execute the prepared statement. If the prepared statement included parameter markers, you must either:

  • call PDOStatement->bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

  • or pass an array of input-only parameter values

Parameters

input_parameters

An array of values with as many elements as there are bound parameters in the SQL statement being executed.

You cannot bind multiple values to a single parameter; for example, you cannot bind two values to a single named parameter in an IN() clause.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Execute a prepared statement with bound variables

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; :calories AND colour = :colour');
$sth-&#62;bindParam(':calories', $calories, PDO::PARAM_INT);
$sth-&#62;bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth-&#62;execute();
?&#62;

Example 2. Execute a prepared statement with an array of insert values (named parameters)

&#60;?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; :calories AND colour = :colour');
$sth-&#62;execute(array(':calories' =&#62; $calories, ':colour' =&#62; $colour));
?&#62;

Example 3. Execute a prepared statement with an array of insert values (placeholders)

&#60;?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; ? AND colour = ?');
$sth-&#62;execute(array($calories, $colour));
?&#62;

Example 4. Execute a prepared statement with question mark placeholders

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; ? AND colour = ?');
$sth-&#62;bindParam(1, $calories, PDO::PARAM_INT);
$sth-&#62;bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth-&#62;execute();
?&#62;

See Also

PDO->prepare()
PDOStatement->bindParam()
PDOStatement->fetch()
PDOStatement->fetchAll()
PDOStatement->fetchColumn()

Prev | Home | Next
PDOStatement->errorInfo() | Up | PDOStatement->fetch()


PDOStatement->fetch()

(no version information, might be only in CVS)

PDOStatement->fetch() -- Fetches the next row from a result set

Description

class PDOStatement {

mixed fetch ( [int fetch_style [, int cursor_orientation [, int cursor_offset]]] )

}

Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

Parameters

fetch_style

Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to PDO::FETCH_BOTH.

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement->bindParam() method

  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class

  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

cursor_orientation

For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your PDOStatement object, you must set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you prepare the SQL statement with PDO->prepare().

offset

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_ABS, this value specifies the absolute number of the row in the result set that shall be fetched.

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_REL, this value specifies the row to fetch relative to the cursor position before PDOStatement->fetch() was called.

Examples

Example 1. Fetching rows using different fetch styles

&#60;?php
$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");
$sth-&#62;execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth-&#62;fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth-&#62;fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth-&#62;fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth-&#62;fetch(PDO::FETCH_OBJ);
print $result-&#62;NAME;
print("\n");
?&#62;

The above example will output:

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [NAME] => apple
    [COLOUR] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [NAME] => banana
    [0] => banana
    [COLOUR] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
    [NAME] => orange
    [COLOUR] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

Example 2. Fetching rows with a scrollable cursor

&#60;?php
function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh-&#62;prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL));
    $stmt-&#62;execute();
    while ($row = $stmt-&#62;fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e-&#62;getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $stmt = $dbh-&#62;prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL));
    $stmt-&#62;execute();
    $row = $stmt-&#62;fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    do {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    } while ($row = $stmt-&#62;fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e-&#62;getMessage();
  }
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?&#62;

The above example will output:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

See Also

PDO->query()
PDOStatement->fetchAll()
PDOStatement->fetchColumn()
PDO->prepare()
PDOStatement->setFetchMode()

Prev | Home | Next
PDOStatement->execute() | Up | PDOStatement->fetchAll()


PDOStatement->fetchAll()

(no version information, might be only in CVS)

PDOStatement->fetchAll() -- Returns an array containing all of the result set rows

Description

class PDOStatement {

array fetchAll ( [int fetch_style [, int column_index]] )

}

Parameters

fetch_style

Controls the contents of the returned array as documented in PDOStatement->fetch(). Defaults to PDO::FETCH_BOTH.

To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN. You can specify which column you want with the column-index parameter.

To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

column_index

Returns the indicated 0-indexed column when the value of fetch_style is PDO::FETCH_COLUMN. Defaults to 0.

Return Values

PDOStatement->fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.

Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and SORT BY clauses in SQL to restrict results before retrieving and processing them with PHP.

Examples

Example 1. Fetch all remaining rows in a result set

&#60;?php
$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");
$sth-&#62;execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth-&#62;fetchAll();
print_r($result);
?&#62;

The above example will output:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

Example 2. Fetching all values of a single column from a result set

The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.

&#60;?php
$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");
$sth-&#62;execute();

/* Fetch all of the values of the first column */
$result = $sth-&#62;fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?&#62;

The above example will output:

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

Example 3. Grouping all values by a single column

The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values apple and pear are returned as arrays that contain two different colours, while watermelon is returned as an array that contains only one colour.

&#60;?php
$insert = $dbh-&#62;prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert-&#62;execute('apple', 'green');
$insert-&#62;execute('pear', 'yellow');

$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");
$sth-&#62;execute();

/* Group values by the first column */
var_dump($sth-&#62;fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?&#62;

The above example will output:

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "green"
  }
}

See Also

PDO->query()
PDOStatement->fetch()
PDOStatement->fetchColumn()
PDO->prepare()
PDOStatement->setFetchMode()

Prev | Home | Next
PDOStatement->fetch() | Up | PDOStatement->fetchColumn()


PDOStatement->getAttribute()

(no version information, might be only in CVS)

PDOStatement->getAttribute() -- Retrieve a statement attribute

Description

class PDOStatement {

mixed getAttribute ( int attribute )

}

Gets an attribute of the statement. Currently, no generic attributes exist but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Get the name of cursor for UPDATE ... WHERE CURRENT OF.

Return Values

Returns the attribute value.

See Also

PDO->getAttribute()
PDO->setAttribute()
PDOStatement->setAttribute()

Prev | Home | Next
PDOStatement->fetchObject() | Up | PDOStatement->getColumnMeta()


PDOStatement->getColumnMeta()

(no version information, might be only in CVS)

PDOStatement->getColumnMeta() -- Returns metadata for a column in a result set

Description

class PDOStatement {

mixed getColumnMeta ( int column )

}

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.

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Warning

Not all PDO drivers support PDOStatement->getColumnMeta().

Parameters

column

The 0-indexed column in the result set.

Return Values

Returns an associative array containing the following values representing the metadata for a single column:

Table 1. Column metadata

Name | Value
native_type | The PHP native type used to represent the column value.
driver:decl_type | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta().
flags | Any flags set for this column.
name | The name of this column as returned by the database.
len | The length of this column. Normally -1 for types other than floating point decimals.
precision | The numeric precision of this column. Normally 0 for types other than floating point decimals.
pdo_type | The type of this column as represented by the PDO::PARAM_* constants.

Returns FALSE if the requested column does not exist in the result set, or if no result set exists.

Examples

Example 1. Retrieving column metadata

The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.

&#60;?php
$select = $DB-&#62;query('SELECT COUNT(*) FROM fruit');
$meta = $select-&#62;getColumnMeta(0);
var_dump($meta);
?&#62;

The above example will output:

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

See Also

PDOStatement->columnCount()
PDOStatement->rowCount()

Prev | Home | Next
PDOStatement->getAttribute() | Up | PDOStatement->nextRowset()


PDOStatement->nextRowset()

(no version information, might be only in CVS)

PDOStatement->nextRowset() -- Advances to the next rowset in a multi-rowset statement handle

Description

class PDOStatement {

bool nextRowset ( void )

}

Some database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement->nextRowset() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Fetching multiple rowsets returned from a stored procedure

The following example shows how to call a stored procedure, MULTIPLE_RESULTS, that returns three rowsets. We use a do / while loop to loop over the PDOStatement->nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.

&#60;?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn-&#62;query($sql);
$i = 1;
do {
    $rowset = $stmt-&#62;fetchAll(PDO::FETCH_NUM);
    if ($rowset) {
        printResultSet($rowset, $i);
    }
    $i++;
} while ($stmt-&#62;nextRowset());

function printResultSet(&#38;$rowset, $i) {
    print "Result set $i:\n";
    foreach ($rowset as $row) {
        foreach ($row as $col) {
            print $col . "\t";
        }
        print "\n";
    }
    print "\n";
}
?&#62;

The above example will output:

Result set 1:
apple    red
banana   yellow

Result set 2:
orange   orange    150
banana   yellow    175

Result set 3:
lime     green
apple    red
banana   yellow

See Also

PDOStatement->columnCount()
PDOStatement->execute()
PDOStatement->getColumnMeta()
PDO->query()

Prev | Home | Next
PDOStatement->getColumnMeta() | Up | PDOStatement->rowCount()


PDOStatement->rowCount()

(no version information, might be only in CVS)

PDOStatement->rowCount() -- Returns the number of rows affected by the last SQL statement

Description

class PDOStatement {

int rowCount ( void )

}

PDOStatement->rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Return Values

Returns the number of rows.

Examples

Example 1. Return the number of deleted rows

PDOStatement->rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

&#60;?php
/* Delete all rows from the FRUIT table */
$del = $dbh-&#62;prepare('DELETE FROM fruit');
$del-&#62;execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del-&#62;rowCount();
print("Deleted $count rows.\n");
?&#62;

The above example will output:

Deleted 9 rows.

Example 2. Counting rows returned by a SELECT statement

For most databases, PDOStatement->rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO->query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement->fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

&#60;?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories &#62; 100";
if ($res = $conn-&#62;query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res-&#62;fetchColumn() &#62; 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories &#62; 100";
       foreach ($conn-&#62;query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?&#62;

The above example will output:

apple
banana
orange
pear

See Also

PDOStatement->columnCount()
PDOStatement->fetchColumn()
PDO->query()

Prev | Home | Next
PDOStatement->nextRowset() | Up | PDOStatement->setAttribute()


PDOStatement->setAttribute()

(no version information, might be only in CVS)

PDOStatement->setAttribute() -- Set a statement attribute

Description

class PDOStatement {

bool setAttribute ( int attribute, mixed value )

}

Sets an attribute on the statement. Currently, no generic attributes are set but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Set the name of cursor for UPDATE ... WHERE CURRENT OF.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

PDO->getAttribute()
PDO->setAttribute()
PDOStatement->getAttribute()

Prev | Home | Next
PDOStatement->rowCount() | Up | PDOStatement->setFetchMode()


PDOStatement->setFetchMode()

(no version information, might be only in CVS)

PDOStatement->setFetchMode() -- Set the default fetch mode for this statement

Description

class PDOStatement {

bool setFetchMode ( int mode )

}class PDOStatement {

bool setFetchMode ( int PDO::FETCH_COLUMN, int colno )

}class PDOStatement {

bool setFetchMode ( int PDO::FETCH_CLASS, string classname, array ctorargs )

}class PDOStatement {

bool setFetchMode ( int PDO::FETCH_INTO, object object )

}

Parameters

mode

The fetch mode must be one of the PDO::FETCH_* constants.

Return Values

Returns 1 on success or FALSE on failure.

Examples

Example 1. Setting the fetch mode

The following example demonstrates how PDOStatement->setFetchMode() changes the default fetch mode for a PDOStatement object.

&#60;?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh-&#62;query($sql);
  $result = $stmt-&#62;setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt-&#62;fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e-&#62;getMessage();
}
?&#62;

The above example will output:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90

Prev | Home | Next
PDOStatement->setAttribute() | Up | Phar archive stream and classes


Verisign Payflow Pro Functions

PHP Manual
Prev Next

CLXIX. Verisign Payflow Pro Functions

Introduction

This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products-services/payment-processing/online-payment/payflow-pro/index.html).

When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.

These functions were added in PHP 4.0.2.

Note: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

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

You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered.

Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.

Alternatively, you can extract the tarball from Verisign in one location, and reference it during build configuration with the --with-pfpro[=DIR] option:

Example 1. Explicit Configuration

tar -zxf pfpro_sunsparc.tar.gz -C /usr/local/

./configure --with-pfpro=/usr/local/verisign/payflowpro/sunsparc

Note: The last portion of the path specified in the example above, in this case sunsparc, will vary based on which architecture your Verisign SDK was built for.

Installation

These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.

Warning

If you are planing to use this extension along with the OpenSSL extension or with ModSSL, you should compile this extension as shared: --with-pfpro=shared,/usr/local.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Verisign Payflow Pro configuration options

Name | Default | Changeable | Changelog
pfpro.defaulthost/PFPRO_VERSION < 3 | "test.signio.com" | PHP_INI_ALL |
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.defaultport | "443" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxyaddress | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxyport | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxylogon | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxypassword | "" | PHP_INI_ALL | Available since PHP 4.0.2.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
pfpro_cleanup -- Shuts down the Payflow Pro library
pfpro_init -- Initialises the Payflow Pro library
pfpro_process_raw -- Process a raw transaction with Payflow Pro
pfpro_process -- Process a transaction with Payflow Pro
pfpro_version -- Returns the version of the Payflow Pro software

Prev | Home | Next
var_export | Up | pfpro_cleanup


pfpro_cleanup

(PHP 4 >= 4.0.2, PHP 5)

pfpro_cleanup -- Shuts down the Payflow Pro library

Description

bool pfpro_cleanup ( void )

Used to shutdown the Payflow Pro library cleanly.

This function should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

pfpro_init()

Prev | Home | Next
Verisign Payflow Pro Functions | Up | pfpro_init


pfpro_init

(PHP 4 >= 4.0.2, PHP 5)

pfpro_init -- Initialises the Payflow Pro library

Description

bool pfpro_init ( void )

Used to initialise the Payflow Pro library.

You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

pfpro_cleanup()

Prev | Home | Next
pfpro_cleanup | Up | pfpro_process_raw


pfpro_process_raw

(PHP 4 >= 4.0.2, PHP 5)

pfpro_process_raw -- Process a raw transaction with Payflow Pro

Description

string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]] )

pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.

Note: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.

Parameters

parameters

A string containing the raw transaction request.

address

Specifies the host to connect to. By default this is test.signio.com, that you will certainly want to change this to connect.signio.com in order to process live transactions.

port

Specifies the port to connect on. It defaults to 443, the standard SSL port number.

timeout

Specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in case of DNS or network problems.

proxy_address

If required, specifies the hostname of your SSL proxy.

proxy_port

If required, specifies the port of your SSL proxy.

proxy_logon

If required, specifies the logon identity to use on the SSL proxy.

proxy_password

If required, specifies the password to use on the SSL proxy.

Return Values

Returns a string containing the raw response.

Examples

Example 1. Payflow Pro raw example

&#60;?php

pfpro_init();

$response = pfpro_process_raw(
"USER=mylogin&#38;PWD[5]=m&#38;ndy&#38;PARTNER=VeriSign&#38;TRXTYPE=S" .
"&#38;TENDER=C&#38;AMT=1.50&#38;ACCT=4111111111111111&#38;EXPDATE=0904");

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign raw response was " . $response;

pfpro_cleanup();

?&#62;

See Also

pfpro_process()

Prev | Home | Next
pfpro_init | Up | pfpro_process


pfpro_process

(PHP 4 >= 4.0.2, PHP 5)

pfpro_process -- Process a transaction with Payflow Pro

Description

array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]] )

pfpro_process() processes a transaction with Payflow Pro.

Note: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Parameters

parameters

An associative array containing keys and values that will be encoded and passed to the processor.

address

Specifies the host to connect to. By default this is test.signio.com, that you will certainly want to change this to connect.signio.com in order to process live transactions.

port

Specifies the port to connect on. It defaults to 443, the standard SSL port number.

timeout

Specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in case of DNS or network problems.

proxy_address

If required, specifies the hostname of your SSL proxy.

proxy_port

If required, specifies the port of your SSL proxy.

proxy_logon

If required, specifies the logon identity to use on the SSL proxy.

proxy_password

If required, specifies the password to use on the SSL proxy.

Return Values

Returns an associative array of the keys and values in the response.

Examples

Example 1. Payflow Pro example

&#60;?php

pfpro_init();

$transaction = array('USER'    =&#62; 'mylogin',
                     'PWD'     =&#62; 'mypassword',
                     'PARTNER' =&#62; 'VeriSign',
                     'TRXTYPE' =&#62; 'S',
                     'TENDER'  =&#62; 'C',
                     'AMT'     =&#62; 1.50,
                     'ACCT'    =&#62; '4111111111111111',
                     'EXPDATE' =&#62; '0909'
                    );

$response = pfpro_process($transaction);

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign response code was " . $response['RESULT'];
echo ", which means: " . $response['RESPMSG'] . "\n";

echo "\nThe transaction request: ";
print_r($transaction);

echo "\nThe response: ";
print_r($response);

pfpro_cleanup();

?&#62;

Prev | Home | Next
pfpro_process_raw | Up | pfpro_version


pfpro_version

(PHP 4 >= 4.0.2, PHP 5)

pfpro_version -- Returns the version of the Payflow Pro software

Description

string pfpro_version ( void )

pfpro_version() returns the version string of the Payflow Pro library. At the time of writing, this was L211.

Return Values

Returns the version number, as a string.

Prev | Home | Next
pfpro_process | Up | vpopmail Functions


PostgreSQL Functions

PHP Manual
Prev Next

CXXV. PostgreSQL Functions

Introduction

PostgreSQL database is Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

Requirements

To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at http://www.postgresql.org/ and the PostgreSQL Documentation.

Installation

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. PostgreSQL configuration options

Name | Default | Changeable | Changelog
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

Resource Types

There are two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource 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.

PGSQL_ASSOC (integer)

Passed to pg_fetch_array(). Return an associative array of field names and values.

PGSQL_NUM (integer)

Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.

PGSQL_BOTH (integer)

Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).

PGSQL_CONNECT_FORCE_NEW (integer)

Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.

PGSQL_CONNECTION_BAD (integer)

Returned by pg_connection_status() indicating that the database connection is in an invalid state.

PGSQL_CONNECTION_OK (integer)

Returned by pg_connection_status() indicating that the database connection is in a valid state.

PGSQL_SEEK_SET (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.

PGSQL_SEEK_CUR (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the current position.

PGSQL_SEEK_END (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.

PGSQL_EMPTY_QUERY (integer)

Returned by pg_result_status(). The string sent to the server was empty.

PGSQL_COMMAND_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning no data.

PGSQL_TUPLES_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).

PGSQL_COPY_OUT (integer)

Returned by pg_result_status(). Copy Out (from server) data transfer started.

PGSQL_COPY_IN (integer)

Returned by pg_result_status(). Copy In (to server) data transfer started.

PGSQL_BAD_RESPONSE (integer)

Returned by pg_result_status(). The server's response was not understood.

PGSQL_NONFATAL_ERROR (integer)

Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.

PGSQL_FATAL_ERROR (integer)

Returned by pg_result_status(). A fatal error occurred.

PGSQL_TRANSACTION_IDLE (integer)

Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.

PGSQL_TRANSACTION_ACTIVE (integer)

Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.

PGSQL_TRANSACTION_INTRANS (integer)

Returned by pg_transaction_status(). The connection is idle, in a transaction block.

PGSQL_TRANSACTION_INERROR (integer)

Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.

PGSQL_TRANSACTION_UNKNOWN (integer)

Returned by pg_transaction_status(). The connection is bad.

PGSQL_DIAG_SEVERITY (integer)

Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.

PGSQL_DIAG_SQLSTATE (integer)

Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.

PGSQL_DIAG_MESSAGE_PRIMARY (integer)

Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.

PGSQL_DIAG_MESSAGE_DETAIL (integer)

Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.

PGSQL_DIAG_MESSAGE_HINT (integer)

Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.

PGSQL_DIAG_STATEMENT_POSITION (integer)

Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.

PGSQL_DIAG_INTERNAL_POSITION (integer)

Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.

PGSQL_DIAG_INTERNAL_QUERY (integer)

Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.

PGSQL_DIAG_CONTEXT (integer)

Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.

PGSQL_DIAG_SOURCE_FILE (integer)

Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_LINE (integer)

Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_FUNCTION (integer)

Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.

PGSQL_ERRORS_TERSE (integer)

Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.

PGSQL_ERRORS_DEFAULT (integer)

Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).

PGSQL_ERRORS_VERBOSE (integer)

Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.

PGSQL_STATUS_LONG (integer)

Passed to pg_result_status(). Indicates that numerical result code is desired.

PGSQL_STATUS_STRING (integer)

Passed to pg_result_status(). Indicates that textual result command tag is desired.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore default values in the table during conversion.

PGSQL_CONV_FORCE_NULL (integer)

Passed to pg_convert(). Use SQL NULL in place of an empty string.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.

Notes

Note: Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

Note: Most PostgreSQL functions accept connection as the first optional parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Note: PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note: PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the PostgreSQL Documentation for full details.

Examples

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example 1. PostgreSQL extension overview example

&#60;?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
    or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

// Printing results in HTML
echo "&#60;table&#62;\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    echo "\t&#60;tr&#62;\n";
    foreach ($line as $col_value) {
        echo "\t\t&#60;td&#62;$col_value&#60;/td&#62;\n";
    }
    echo "\t&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?&#62;

Table of Contents
pg_affected_rows -- Returns number of affected records (tuples)
pg_cancel_query -- Cancel an asynchronous query
pg_client_encoding -- Gets the client encoding
pg_close -- Closes a PostgreSQL connection
pg_connect -- Open a PostgreSQL connection
pg_connection_busy -- Get connection is busy or not
pg_connection_reset -- Reset connection (reconnect)
pg_connection_status -- Get connection status
pg_convert -- Convert associative array values into suitable for SQL statement
pg_copy_from -- Insert records into a table from an array
pg_copy_to -- Copy a table to an array
pg_dbname -- Get the database name
pg_delete -- Deletes records
pg_end_copy -- Sync with PostgreSQL backend
pg_escape_bytea -- Escape a string for insertion into a bytea field
pg_escape_string -- Escape a string for insertion into a text field
pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.
pg_fetch_all_columns -- Fetches all rows in a particular result column as an array
pg_fetch_all -- Fetches all rows from a result as an array
pg_fetch_array -- Fetch a row as an array
pg_fetch_assoc -- Fetch a row as an associative array
pg_fetch_object -- Fetch a row as an object
pg_fetch_result -- Returns values from a result resource
pg_fetch_row -- Get a row as an enumerated array
pg_field_is_null -- Test if a field is SQL NULL
pg_field_name -- Returns the name of a field
pg_field_num -- Returns the field number of the named field
pg_field_prtlen -- Returns the printed length
pg_field_size -- Returns the internal storage size of the named field
pg_field_table -- Returns the name or oid of the tables field
pg_field_type_oid -- Returns the type ID (OID) for the corresponding field number
pg_field_type -- Returns the type name for the corresponding field number
pg_free_result -- Free result memory
pg_get_notify -- Gets SQL NOTIFY message
pg_get_pid -- Gets the backend's process ID
pg_get_result -- Get asynchronous query result
pg_host -- Returns the host name associated with the connection
pg_insert -- Insert array into table
pg_last_error -- Get the last error message string of a connection
pg_last_notice -- Returns the last notice message from PostgreSQL server
pg_last_oid -- Returns the last row's OID
pg_lo_close -- Close a large object
pg_lo_create -- Create a large object
pg_lo_export -- Export a large object to file
pg_lo_import -- Import a large object from file
pg_lo_open -- Open a large object
pg_lo_read_all -- Reads an entire large object and send straight to browser
pg_lo_read -- Read a large object
pg_lo_seek -- Seeks position within a large object
pg_lo_tell -- Returns current seek position a of large object
pg_lo_unlink -- Delete a large object
pg_lo_write -- Write to a large object
pg_meta_data -- Get meta data for table
pg_num_fields -- Returns the number of fields in a result
pg_num_rows -- Returns the number of rows in a result
pg_options -- Get the options associated with the connection
pg_parameter_status -- Looks up a current parameter setting of the server.
pg_pconnect -- Open a persistent PostgreSQL connection
pg_ping -- Ping database connection
pg_port -- Return the port number associated with the connection
pg_prepare -- Submits a request to create a prepared statement with the given parameters, and waits for completion.
pg_put_line -- Send a NULL-terminated string to PostgreSQL backend
pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
pg_query -- Execute a query
pg_result_error_field -- Returns an individual field of an error report.
pg_result_error -- Get error message associated with result
pg_result_seek -- Set internal row offset in result resource
pg_result_status -- Get status of query result
pg_select -- Select records
pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.
pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).
pg_send_query -- Sends asynchronous query
pg_set_client_encoding -- Set the client encoding
pg_set_error_verbosity -- Determines the verbosity of messages returned by pg_last_error() and pg_result_error().
pg_trace -- Enable tracing a PostgreSQL connection
pg_transaction_status -- Returns the current in-transaction status of the server.
pg_tty -- Return the TTY name associated with the connection
pg_unescape_bytea -- Unescape binary for bytea type
pg_untrace -- Disable tracing of a PostgreSQL connection
pg_update -- Update table
pg_version -- Returns an array with client, protocol and server version (when available)

Prev | Home | Next
sql_regcase | Up | pg_affected_rows


pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_affected_rows -- Returns number of affected records (tuples)

Description

int pg_affected_rows ( resource result )

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Note: This function used to be called pg_cmdtuples().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows affected by the query. If no tuple is affected, it will return 0.

Examples

Example 1. pg_affected_rows() example

&#60;?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples = pg_affected_rows($result);

echo $cmdtuples . " tuples are affected.\n";
?&#62;

The above example will output:

1 tuples are affected.

See Also

pg_query()
pg_query_params()
pg_execute()
pg_num_rows()

Prev | Home | Next
PostgreSQL Functions | Up | pg_cancel_query


pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5)

pg_cancel_query -- Cancel an asynchronous query

Description

bool pg_cancel_query ( resource connection )

pg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_cancel_query() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  // Cancel the currently running query.  Will be the second query if it is
  // still running.
  pg_cancel_query($dbconn);
?&#62;

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

See Also

pg_send_query()
pg_connection_busy()

Prev | Home | Next
pg_affected_rows | Up | pg_client_encoding


pg_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)

pg_client_encoding -- Gets the client encoding

Description

string pg_client_encoding ( [resource connection] )

PostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.

Note: This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns SQL_ASCII. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.

The function used to be called pg_clientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

The client encoding, or FALSE on error.

Examples

Example 1. pg_client_encoding() example

&#60;?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);

echo "Client encoding is: ", $encoding, "\n";
?&#62;

The above example will output:

Client encoding is: ISO-8859-1

See Also

pg_set_client_encoding()

Prev | Home | Next
pg_cancel_query | Up | pg_close


pg_close

(PHP 3, PHP 4, PHP 5)

pg_close -- Closes a PostgreSQL connection

Description

bool pg_close ( [resource connection] )

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

Note: Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.

If there is open large object resource on the connection, do not close the connection before closing all large object resources.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_close() example

&#60;?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?&#62;

The above example will output:

Connected successfully

See Also

pg_connect()

Prev | Home | Next
pg_client_encoding | Up | pg_connect


pg_connect

(PHP 3, PHP 4, PHP 5)

pg_connect -- Open a PostgreSQL connection

Description

resource pg_connect ( string connection_string [, int connect_type] )

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string.

If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example 1. Using pg_connect()

&#60;?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?&#62;

See Also

pg_pconnect()
pg_close()
pg_host()
pg_port()
pg_tty()
pg_options()
pg_dbname()

Prev | Home | Next
pg_close | Up | pg_connection_busy


pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_busy -- Get connection is busy or not

Description

bool pg_connection_busy ( resource connection )

pg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE if the connection is busy, FALSE otherwise.

Examples

Example 1. pg_connection_busy() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $bs = pg_connection_busy($dbconn);
  if ($bs) {
      echo 'connection is busy';
  } else {
     echo 'connection is not busy';
  }
?&#62;

See Also

pg_connection_status()
pg_get_result()

Prev | Home | Next
pg_connect | Up | pg_connection_reset


pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_reset -- Reset connection (reconnect)

Description

bool pg_connection_reset ( resource connection )

pg_connection_reset() resets the connection. It is useful for error recovery.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_connection_reset() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $dbconn2 = pg_connection_reset($dbconn);
  if ($dbconn2) {
      echo "reset successful\n";
  } else {
      echo "reset failed\n";
  }
?&#62;

See Also

pg_connect()
pg_pconnect()
pg_connection_status()

Prev | Home | Next
pg_connection_busy | Up | pg_connection_status


pg_connection_status

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_status -- Get connection status

Description

int pg_connection_status ( resource connection )

pg_connection_status() returns the status of the specified connection.

Parameters

connection

PostgreSQL database connection resource.

Return Values

PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

Examples

Example 1. pg_connection_status() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_connection_status($dbconn);
  if ($stat === PGSQL_CONNECTION_OK) {
      echo 'Connection status ok';
  } else {
      echo 'Connection status bad';
  }
?&#62;

See Also

pg_connection_busy()

Prev | Home | Next
pg_connection_reset | Up | pg_convert


pg_convert

(PHP 4 >= 4.3.0, PHP 5)

pg_convert -- Convert associative array values into suitable for SQL statement

Description

array pg_convert ( resource connection, string table_name, array assoc_array [, int options] )

pg_convert() checks and converts the values in assoc_array into suitable values for use in a SQL statement. Precondition for pg_convert() is the existence of a table table_name which has at least as many columns as assoc_array has elements. The fieldnames in table_name must match the indices in assoc_array and the corresponding datatypes must be compatible. Returns an array with the converted values on success, FALSE otherwise.

Note: If there are boolean fields in table_name don't use the constant TRUE in assoc_array. It will be converted to the string 'TRUE' which is no valid entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes instead.

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

connection

PostgreSQL database connection resource.

table_name

Name of the table against which to convert types.

assoc_array

Data to be converted.

options

Any number of PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL or PGSQL_CONV_IGNORE_NOT_NULL, combined.

Return Values

An array of converted values, or FALSE on error.

Examples

Example 1. pg_convert() example

&#60;?php
  $dbconn = pg_connect('dbname=foo');

  $tmp = array(
      'author' =&#62; 'Joe Thackery',
      'year' =&#62; 2005,
      'title' =&#62; 'My Life, by Joe Thackery'
  );

  $vals = pg_convert($dbconn, 'authors', $tmp);
?&#62;

See Also

pg_meta_data()

Prev | Home | Next
pg_connection_status | Up | pg_copy_from


pg_copy_from

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_from -- Insert records into a table from an array

Description

bool pg_copy_from ( resource connection, string table_name, array rows [, string delimiter [, string null_as]] )

pg_copy_from() inserts records into a table from rows. It issues a COPY FROM SQL command internally to insert records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to copy the rows.

rows

An array of data to be copied into table_name. Each value in rows becomes a row in table_name. Each value in rows should be a delimited string of the values to insert into each field. Values should be linefeed terminated.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_copy_from() example

&#60;?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?&#62;

See Also

pg_copy_to()

Prev | Home | Next
pg_convert | Up | pg_copy_to


pg_copy_to

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_to -- Copy a table to an array

Description

array pg_copy_to ( resource connection, string table_name [, string delimiter [, string null_as]] )

pg_copy_to() copies a table to an array. It issues COPY TO SQL command internally to retrieve records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to copy the data into rows.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Return Values

An array with one element for each line of COPY data. It returns FALSE on failure.

Examples

Example 1. pg_copy_to() example

&#60;?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?&#62;

See Also

pg_copy_from()

Prev | Home | Next
pg_copy_from | Up | pg_dbname


pg_dbname

(PHP 3, PHP 4, PHP 5)

pg_dbname -- Get the database name

Description

string pg_dbname ( [resource connection] )

pg_dbname() returns the name of the database that the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the database the connection is to, or FALSE on error.

Examples

Example 1. pg_dbname() example

&#60;?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?&#62;

Prev | Home | Next
pg_copy_to | Up | pg_delete


pg_delete

(PHP 4 >= 4.3.0, PHP 5)

pg_delete -- Deletes records

Description

mixed pg_delete ( resource connection, string table_name, array assoc_array [, int options] )

pg_delete() deletes records from a table specified by the keys and values in assoc_array. If options is specified, pg_convert() is applied to assoc_array with the specified options.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to delete rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be deleted.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example 1. pg_delete() example

&#60;?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_delete($db, 'post_log', $_POST);
  if ($res) {
      echo "POST data is deleted: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?&#62;

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

pg_convert()

Prev | Home | Next
pg_dbname | Up | pg_end_copy


pg_end_copy

(PHP 4 >= 4.0.3, PHP 5)

pg_end_copy -- Sync with PostgreSQL backend

Description

bool pg_end_copy ( [resource connection] )

pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_end_copy() example

&#60;?php
  $conn = pg_pconnect("dbname=foo");
  pg_query($conn, "create table bar (a int4, b char(16), d float8)");
  pg_query($conn, "copy bar from stdin");
  pg_put_line($conn, "3\thello world\t4.5\n");
  pg_put_line($conn, "4\tgoodbye world\t7.11\n");
  pg_put_line($conn, "\\.\n");
  pg_end_copy($conn);
?&#62;

See Also

pg_put_line()

Prev | Home | Next
pg_delete | Up | pg_escape_bytea


pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_bytea -- Escape a string for insertion into a bytea field

Description

string pg_escape_bytea ( string data )

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

Note: When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

data

A string containing text or binary data to be inserted into a bytea column.

Return Values

A string containing the escaped data.

Examples

Example 1. pg_escape_bytea() example

&#60;?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a binary file
  $data = file_get_contents('image1.jpg');

  // Escape the binary data
  $escaped = pg_escape_bytea($data);

  // Insert it into the database
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?&#62;

See Also

pg_unescape_bytea()
pg_escape_string()

Prev | Home | Next
pg_end_copy | Up | pg_escape_string


pg_escape_string

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_string -- Escape a string for insertion into a text field

Description

string pg_escape_string ( string data )

pg_escape_string() escapes a string for insertion into the database. It returns an escaped string in the PostgreSQL format. Use of this function is recommended instead of addslashes(). If the type of the column is bytea, pg_escape_bytea() must be used instead.

Note: This function requires PostgreSQL 7.2 or later.

Parameters

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Examples

Example 1. pg_escape_string() example

&#60;?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a text file (containing apostrophes and backslashes)
  $data = file_get_contents('letter.txt');

  // Escape the text data
  $escaped = pg_escape_string($data);

  // Insert it into the database
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?&#62;

See Also

pg_escape_bytea()

Prev | Home | Next
pg_escape_bytea | Up | pg_execute


pg_execute

(PHP 5 >= 5.1.0RC1)

pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.

Description

resource pg_execute ( resource connection, string stmtname, array params )

resource pg_execute ( string stmtname, array params )

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Warning

Elements are converted to strings by calling this function.

Return Values

A query result resource on success, or FALSE on failure.

Examples

Example 1. Using pg_execute()

&#60;?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?&#62;

See Also

pg_prepare()
pg_send_prepare()
pg_query_params()

Prev | Home | Next
pg_escape_string | Up | pg_fetch_all_columns


pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_all -- Fetches all rows from a result as an array

Description

array pg_fetch_all ( resource result )

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Note: This function sets NULL fields to PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

An array with all rows in the result. Each row is an array of field values indexed by field name.

FALSE is returned if there are no rows in the result, or on any other error.

Examples

Example 1. PostgreSQL fetch all

&#60;?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

$arr = pg_fetch_all($result);

var_dump($arr);

?&#62;

See Also

pg_fetch_row()
pg_fetch_array()
pg_fetch_object()
pg_fetch_result()

Prev | Home | Next
pg_fetch_all_columns | Up | pg_fetch_array


pg_fetch_array

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_array -- Fetch a row as an array

Description

array pg_fetch_array ( resource result [, int row [, int result_type]] )

pg_fetch_array() returns an array that corresponds to the fetched row (record).

pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indicies by default.

Note: This function sets NULL fields to PHP NULL value.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Note: row became optional in PHP 4.1.0.

Note: result_type was added in PHP 4.0.0.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_fetch_array() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example 1. pg_fetch_array() example

&#60;?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " &#60;- Row 1 Author\n";
echo $arr[1] . " &#60;- Row 1 E-mail\n";

// As of PHP 4.1.0, the row parameter is optional; NULL can be passed instead,
// to pass a result_type.  Successive calls to pg_fetch_array will return the
// next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " &#60;- Row 2 Author\n";
echo $arr["email"] . " &#60;- Row 2 E-mail\n";

$arr = pg_fetch_array($result);
echo $arr["author"] . " &#60;- Row 3 Author\n";
echo $arr[1] . " &#60;- Row 3 E-mail\n";

?&#62;

See Also

pg_fetch_row()
pg_fetch_object()
pg_fetch_result()

Prev | Home | Next
pg_fetch_all | Up | pg_fetch_assoc


pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_assoc -- Fetch a row as an associative array

Description

array pg_fetch_assoc ( resource result [, int row] )

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with PGSQL_ASSOC as the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

Note: This function sets NULL fields to PHP NULL value.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Note: row became optional in PHP 4.1.0.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

Return Values

An array indexed associatively (by field name). Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example 1. pg_fetch_assoc() example

&#60;?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?&#62;

See Also

pg_fetch_row()
pg_fetch_array()
pg_fetch_object()
pg_fetch_result()

Prev | Home | Next
pg_fetch_array | Up | pg_fetch_object


pg_fetch_object

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_object -- Fetch a row as an object

Description

object pg_fetch_object ( resource result [, int row [, int result_type]] )

object pg_fetch_object ( resource result [, int row [, string class_name [, array params]]] )

pg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.

Note: This function sets NULL fields to PHP NULL value.

Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).

Note: row became optional in PHP 4.1.0.

Note: result_type default changed from PGSQL_BOTH to PGSQL_ASSOC from PHP 4.3.0, since the numeric index was illegal.

Note: class_name and params were added in PHP 5.0. The old form with result_type still exists for backwards compatibility.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

result_type

Ignored and deprecated. Defaults to PGSQL_ASSOC.

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

An object with one attribute for each field name in the result. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example 1. pg_fetch_object() example

&#60;?php

$database = "store";

$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
  echo "Failed connecting to postgres database $database\n";
  exit;
}

$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");

while ($data = pg_fetch_object($qu)) {
  echo $data-&#62;author . " (";
  echo $data-&#62;year . "): ";
  echo $data-&#62;title . "&#60;br /&#62;";
}

pg_free_result($qu);
pg_close($db_conn);

?&#62;

See Also

pg_query()
pg_fetch_array()
pg_fetch_assoc()
pg_fetch_row()
pg_fetch_result()

Prev | Home | Next
pg_fetch_assoc | Up | pg_fetch_result


pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5)

pg_fetch_result -- Returns values from a result resource

Description

string pg_fetch_result ( resource result, int row, mixed field )

string pg_fetch_result ( resource result, mixed field )

pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

field

A string representing the name of the field (column) to fetch, otherwise and int representing the field number to fetch. Fields are numbered from 0 upwards.

Return Values

Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, or on any other error.

Examples

Example 1. pg_fetch_result() example

&#60;?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";
?&#62;

The above example will output:

First field in the second row is: 2

See Also

pg_query()
pg_fetch_array()

Prev | Home | Next
pg_fetch_object | Up | pg_fetch_row


pg_fetch_row

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_row -- Get a row as an enumerated array

Description

array pg_fetch_row ( resource result [, int row] )

pg_fetch_row() fetches one row of data from the result associated with the specified result resource.

Note: This function sets NULL fields to PHP NULL value.

Note: From PHP 4.1.0, row became optional.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

Return Values

An array, indexed from 0 upwards, with each value represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example 1. pg_fetch_row() example

&#60;?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "&#60;br /&#62;\n";
}

?&#62;

See Also

pg_query()
pg_fetch_array()
pg_fetch_object()
pg_fetch_result()

Prev | Home | Next
pg_fetch_result | Up | pg_field_is_null


pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5)

pg_field_is_null -- Test if a field is SQL NULL

Description

int pg_field_is_null ( resource result, int row, mixed field )

int pg_field_is_null ( resource result, mixed field )

pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL NULL or not.

Note: This function used to be called pg_fieldisnull().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched.

field

Field number (starting from 0) as an integer or the field name as a string.

Return Values

Returns 1 if the field in the given row is SQL NULL, 0 if not. FALSE is returned if the row is out of range, or upon any other error.

Examples

Example 1. pg_field_is_null() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  if ($res) {
      if (pg_field_is_null($res, 0, "year") == 1) {
          echo "The value of the field year is null.\n";
      }
      if (pg_field_is_null($res, 0, "year") == 0) {
          echo "The value of the field year is not null.\n";
    }
 }
?&#62;

Prev | Home | Next
pg_fetch_row | Up | pg_field_name


pg_field_name

(PHP 4 >= 4.2.0, PHP 5)

pg_field_name -- Returns the name of a field

Description

string pg_field_name ( resource result, int field_number )

pg_field_name() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.

Note: This function used to be called pg_fieldname().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The field name, or FALSE on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j &#60; $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?&#62;

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

pg_field_num()

Prev | Home | Next
pg_field_is_null | Up | pg_field_num


pg_field_num

(PHP 4 >= 4.2.0, PHP 5)

pg_field_num -- Returns the field number of the named field

Description

int pg_field_num ( resource result, string field_name )

pg_field_num() will return the number of the field number that corresponds to the field_name in the given PostgreSQL result resource.

Note: This function used to be called pg_fieldnum().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_name

The name of the field.

Return Values

The field number (numbered from 0), or -1 on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");

  echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?&#62;

The above example will output:

Column 'title' is field number: 2

See Also

pg_field_name()

Prev | Home | Next
pg_field_name | Up | pg_field_prtlen


pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5)

pg_field_prtlen -- Returns the printed length

Description

int pg_field_prtlen ( resource result, int row_number, mixed field_name_or_number )

int pg_field_prtlen ( resource result, mixed field_name_or_number )

pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL result. Row numbering starts at 0. This function will return -1 on an error.

field_name_or_number can be passed either as an integer or as a string. If it is passed as an integer, PHP recognises it as the field number, otherwise as field name.

See the example given at the pg_field_name() page.

Note: This function used to be called pg_fieldprtlen().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.

Return Values

The field printed length, or FALSE on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j &#60; $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?&#62;

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

pg_field_size()

Prev | Home | Next
pg_field_num | Up | pg_field_size


pg_field_size

(PHP 4 >= 4.2.0, PHP 5)

pg_field_size -- Returns the internal storage size of the named field

Description

int pg_field_size ( resource result, int field_number )

pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL result.

Note: This function used to be called pg_fieldsize().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The internal field storage size (in bytes). -1 indicates a variable length field. FALSE is returned on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j &#60; $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?&#62;

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

pg_field_prtlen()
pg_field_type()

Prev | Home | Next
pg_field_prtlen | Up | pg_field_table


pg_field_type_oid

(PHP 5 >= 5.1.0RC1)

pg_field_type_oid -- Returns the type ID (OID) for the corresponding field number

Description

int pg_field_type_oid ( resource result, int field_number )

pg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.

You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

Note: If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The OID of the field's base type. FALSE is returned on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type OID: ", pg_field_type_oid($res, 0);
?&#62;

The above example will output:

Title field type OID: 1043

See Also

pg_field_type()
pg_field_prtlen()
pg_field_name()

Prev | Home | Next
pg_field_table | Up | pg_field_type


pg_field_type

(PHP 4 >= 4.2.0, PHP 5)

pg_field_type -- Returns the type name for the corresponding field number

Description

string pg_field_type ( resource result, int field_number )

pg_field_type() returns a string containing the base type name of the given field_number in the given PostgreSQL result resource.

Note: If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.

Note: This function used to be called pg_fieldtype().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

A string containing the base name of the field's type, or FALSE on error.

Examples

Example 1. Getting information about fields

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type: ", pg_field_type($res, 0);
?&#62;

The above example will output:

Title field type: varchar

See Also

pg_field_prtlen()
pg_field_name()
pg_field_type_oid()

Prev | Home | Next
pg_field_type_oid | Up | pg_free_result


pg_free_result

(PHP 4 >= 4.2.0, PHP 5)

pg_free_result -- Free result memory

Description

bool pg_free_result ( resource result )

pg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

Note: This function used to be called pg_freeresult().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_free_result() example

&#60;?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";

pg_free_result($res);
?&#62;

The above example will output:

First field in the second row is: 2

See Also

pg_query()
pg_query_params()
pg_execute()

Prev | Home | Next
pg_field_type | Up | pg_get_notify


pg_get_notify

(PHP 4 >= 4.3.0, PHP 5)

pg_get_notify -- Gets SQL NOTIFY message

Description

array pg_get_notify ( resource connection [, int result_type] )

pg_get_notify() gets notifications generated by a NOTIFY SQL command. To receive notifications, the LISTEN SQL command must be issued.

Parameters

connection

PostgreSQL database connection resource.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_get_notify() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array containing the NOTIFY message name and backend PID. Otherwise if no NOTIFY is waiting, then FALSE is returned.

Examples

Example 1. PostgreSQL NOTIFY message

&#60;?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
  echo "No messages\n";
} else {
  print_r($notify);
}
?&#62;

See Also

pg_get_pid()

Prev | Home | Next
pg_free_result | Up | pg_get_pid


pg_get_pid

(PHP 4 >= 4.3.0, PHP 5)

pg_get_pid -- Gets the backend's process ID

Description

int pg_get_pid ( resource connection )

pg_get_pid() gets the backend's (database server process) PID. The PID is useful to determine whether or not a NOTIFY message received via pg_get_notify() is sent from another process or not.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The backend database process ID.

Examples

Example 1. PostgreSQL backend PID

&#60;?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?&#62;

See Also

pg_get_notify()

Prev | Home | Next
pg_get_notify | Up | pg_get_result


pg_get_result

(PHP 4 >= 4.2.0, PHP 5)

pg_get_result -- Get asynchronous query result

Description

resource pg_get_result ( [resource connection] )

pg_get_result() gets the result resource from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().

pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The result resource, or FALSE if no more results are available.

Examples

Example 1. pg_get_result() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?&#62;

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

See Also

pg_send_query()

Prev | Home | Next
pg_get_pid | Up | pg_host


pg_host

(PHP 3, PHP 4, PHP 5)

pg_host -- Returns the host name associated with the connection

Description

string pg_host ( [resource connection] )

pg_host() returns the host name of the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the host the connection is to, or FALSE on error.

Examples

Example 1. pg_host() example

&#60;?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to: " . pg_host($pgsql_conn) . "&#60;br/&#62;\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?&#62;

See Also

pg_connect()
pg_pconnect()

Prev | Home | Next
pg_get_result | Up | pg_insert


pg_insert

(PHP 4 >= 4.3.0, PHP 5)

pg_insert -- Insert array into table

Description

mixed pg_insert ( resource connection, string table_name, array assoc_array [, int options] )

pg_insert() inserts the values of assoc_array into the table specified by table_name. If options is specified, pg_convert() is applied to assoc_array with the specified options.

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

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be inserted.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example 1. pg_insert() example

&#60;?php
  $dbconn = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_insert($dbconn, 'post_log', $_POST);
  if ($res) {
      echo "POST data is successfully logged\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?&#62;

See Also

pg_convert()

Prev | Home | Next
pg_host | Up | pg_last_error


pg_last_error

(PHP 4 >= 4.2.0, PHP 5)

pg_last_error -- Get the last error message string of a connection

Description

string pg_last_error ( [resource connection] )

pg_last_error() returns the last error message for a given connection.

Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.

Use pg_result_error(), pg_result_error_field(),
pg_result_status() and
pg_connection_status() for better error handling.

Note: This function used to be called pg_errormessage().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the last error message on the given connection, or FALSE on error.

Examples

Example 1. pg_last_error() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Query that fails
  $res = pg_query($dbconn, "select * from doesnotexist");

  echo pg_last_error($dbconn);
?&#62;

See Also

pg_result_error()
pg_result_error_field()

Prev | Home | Next
pg_insert | Up | pg_last_notice


pg_last_notice

(PHP 4 >= 4.0.6, PHP 5)

pg_last_notice -- Returns the last notice message from PostgreSQL server

Description

string pg_last_notice ( resource connection )

pg_last_notice() returns the last notice message from the PostgreSQL server on the specified connection. The PostgreSQL server sends notice messages in several cases, for instance when creating a SERIAL column in a table.

With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.

Warning

This function is EXPERIMENTAL and it is not fully implemented yet. pg_last_notice() was added in PHP 4.0.6. However, PHP 4.0.6 has problem with notice message handling. Use of the PostgreSQL module with PHP 4.0.6 is not recommended even if you are not using pg_last_notice().

This function is fully implemented in PHP 4.3.0. PHP earlier than PHP 4.3.0 ignores database connection parameter.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini from PHP 4.3.0.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini from PHP 4.3.0. Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.

Parameters

connection

PostgreSQL database connection resource.

Return Values

A string containing the last notice on the given connection, or FALSE on error.

Examples

Example 1. pg_last_error() example

&#60;?php
  $pgsql_conn = pg_connect("dbname=mark host=localhost");

  $res = pg_query("CREATE TABLE test (id SERIAL)");

  $notice = pg_last_notice($pgsql_conn);

  echo $notice;
?&#62;

The above example will output:

CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

See Also

pg_query()
pg_last_error()

Prev | Home | Next
pg_last_error | Up | pg_last_oid


pg_last_oid

(PHP 4 >= 4.2.0, PHP 5)

pg_last_oid -- Returns the last row's OID

Description

string pg_last_oid ( resource result )

pg_last_oid() is used to retrieve the OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.

To get the value of a SERIAL field in an inserted row, it is necessary to use the PostgreSQL CURRVAL function, naming the sequence whose last value is required. If the name of the sequence is unknown, the pg_get_serial_sequence PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function LASTVAL that returns the value of the most recently used sequence in the session. This avoids the need for naming the sequence, table or column altogether.

Note: This function used to be called pg_getlastoid().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

A string containing the OID assigned to the most recently inserted row in the specified connection, or FALSE on error or no available OID.

Examples

Example 1. pg_last_oid() example

&#60;?php
  $pgsql_conn = pg_connect("dbname=mark host=localhost");

  $res1 = pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

  $res2 = pg_query("INSERT INTO test VALUES (1)");

  $oid = pg_last_oid($res2);
?&#62;

See Also

pg_query()
pg_result_status()

Prev | Home | Next
pg_last_notice | Up | pg_lo_close


pg_lo_close

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_close -- Close a large object

Description

bool pg_lo_close ( resource large_object )

pg_lo_close() closes a large object. large_object is a resource for the large object from pg_lo_open().

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loclose().

Parameters

result

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_lo_close() example

&#60;?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_open()
pg_lo_create()
pg_lo_import()

Prev | Home | Next
pg_last_oid | Up | pg_lo_create


pg_lo_create

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_create -- Create a large object

Description

int pg_lo_create ( [resource connection] )

pg_lo_create() creates a large object and returns the OID of the large object. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).

To use the large object interface, it is necessary to enclose it within a transaction block.

Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().

Note: This function used to be called pg_locreate().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A large object OID or FALSE on error.

Examples

Example 1. pg_lo_create() example

&#60;?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?&#62;

Prev | Home | Next
pg_lo_close | Up | pg_lo_export


pg_lo_export

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_export -- Export a large object to file

Description

bool pg_lo_export ( resource connection, int oid, string pathname )

bool pg_lo_export ( int oid, string pathname )

pg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loexport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

pathname

The full path and file name of the file in which to write the large object on the client filesystem.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_lo_export() example

&#60;?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   $handle = pg_lo_open($database, $oid, "w");
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_lo_export($database, $oid, '/tmp/lob.dat');
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_import()

Prev | Home | Next
pg_lo_create | Up | pg_lo_import


pg_lo_import

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_import -- Import a large object from file

Description

int pg_lo_import ( resource connection, string pathname )

int pg_lo_import ( string pathname )

In versions before PHP 4.2.0 the syntax of this function was different, see the following definition:

int pg_lo_import ( string pathname [, resource connection] )

pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.

To use the large object interface, it is necessary to enclose it within a transaction block.

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 used to be called pg_loimport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

pathname

The full path and file name of the file on the client filesystem from which to read the large object data.

Return Values

The OID of the newly created large object, or FALSE on failure.

Examples

Example 1. pg_lo_import() example

&#60;?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_import($database, '/tmp/lob.dat');
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_export()
pg_lo_open()

Prev | Home | Next
pg_lo_export | Up | pg_lo_open


pg_lo_open

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_open -- Open a large object

Description

resource pg_lo_open ( resource connection, int oid, string mode )

pg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.

Warning

Do not close the database connection before closing the large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loopen().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

mode

Can be either "r" for read-only, "w" for write only or "rw" for read and write.

Return Values

A large object resource or FALSE on error.

Examples

Example 1. pg_lo_open() example

&#60;?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_close()
pg_lo_create()

Prev | Home | Next
pg_lo_import | Up | pg_lo_read_all


pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read_all -- Reads an entire large object and send straight to browser

Description

int pg_lo_read_all ( resource large_object )

pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loreadall().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Number of bytes read or FALSE on error.

Examples

Example 1. pg_lo_read_all() example

&#60;?php
   header('Content-type: image/jpeg');
   $image_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $image_oid, "r");
   pg_lo_read_all($handle);
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_read()

Prev | Home | Next
pg_lo_open | Up | pg_lo_read


pg_lo_read

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read -- Read a large object

Description

string pg_lo_read ( resource large_object [, int len] )

pg_lo_read() reads at most len bytes from a large object and returns it as a string.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loread().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

len

An optional maximum number of bytes to return. Defaults to 8192.

Return Values

A string containing len bytes from the large object, or FALSE on error.

Examples

Example 1. pg_lo_read() example

&#60;?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   $data = pg_lo_read($handle, 50000);
   pg_query($database, "commit");
   echo $data;
?&#62;

See Also

pg_lo_read_all()

Prev | Home | Next
pg_lo_read_all | Up | pg_lo_seek


pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_seek -- Seeks position within a large object

Description

bool pg_lo_seek ( resource large_object, int offset [, int whence] )

pg_lo_seek() seeks a position within a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

offset

The number of bytes to seek.

whence

One of the constants PGSQL_SEEK_SET (seek from object start), PGSQL_SEEK_CUR (seek from current position) or PGSQL_SEEK_END (seek from object end) .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_lo_seek() example

&#60;?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // Read the next 10000 bytes
   $data = pg_lo_read($handle, 10000);
   pg_query($database, "commit");
   echo $data;
?&#62;

See Also

pg_lo_tell()

Prev | Home | Next
pg_lo_read | Up | pg_lo_tell


pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_tell -- Returns current seek position a of large object

Description

int pg_lo_tell ( resource large_object )

pg_lo_tell() returns the current position (offset from the beginning) of a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.

Examples

Example 1. pg_lo_tell() example

&#60;?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // See how far we've skipped
   $offset = pg_lo_tell($handle);
   echo "Seek position is: $offset";
   pg_query($database, "commit");
?&#62;

The above example will output:

Seek position is: 50000

See Also

pg_lo_seek()

Prev | Home | Next
pg_lo_seek | Up | pg_lo_unlink


pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_unlink -- Delete a large object

Description

bool pg_lo_unlink ( resource connection, int oid )

pg_lo_unlink() deletes a large object with the oid. Returns TRUE on success or FALSE on failure.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_lounlink().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_lo_unlink() example

&#60;?php
   // OID of the large object to delete
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   pg_lo_unlink($database, $doc_oid);
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_create()
pg_lo_import()

Prev | Home | Next
pg_lo_tell | Up | pg_lo_write


pg_lo_write

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_write -- Write to a large object

Description

int pg_lo_write ( resource large_object, string data [, int len] )

pg_lo_write() writes data into a large object at the current seek position.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_lowrite().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

data

The data to be written to the large object. If len is specified and is less than the length of data, only len bytes will be written.

len

An optional maximum number of bytes to write. Must be greater than zero and no greater than the length of data. Defaults to the length of data.

Return Values

The number of bytes written to the large object, or FALSE on error.

Examples

Example 1. pg_lo_write() example

&#60;?php
   $doc_oid = 189762345;
   $data = "This will overwrite the start of the large object.";
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "w");
   $data = pg_lo_write($handle, $data);
   pg_query($database, "commit");
?&#62;

See Also

pg_lo_create()
pg_lo_open()

Prev | Home | Next
pg_lo_unlink | Up | pg_meta_data


pg_meta_data

(PHP 4 >= 4.3.0, PHP 5)

pg_meta_data -- Get meta data for table

Description

array pg_meta_data ( resource connection, string table_name )

pg_meta_data() returns table definition for table_name as an array.

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

connection

PostgreSQL database connection resource.

table_name

The name of the table.

Return Values

An array of the table definition, or FALSE on error.

Examples

Example 1. Getting table metadata

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $meta = pg_meta_data($dbconn, 'authors');
  if (is_array($meta)) {
      echo '&#60;pre&#62;';
      var_dump($meta);
      echo '&#60;/pre&#62;';
  }
?&#62;

The above example will output:

array(3) {
["author"]=>
array(5) {
  ["num"]=>
  int(1)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["year"]=>
array(5) {
  ["num"]=>
  int(2)
  ["type"]=>
  string(4) "int2"
  ["len"]=>
  int(2)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["title"]=>
array(5) {
  ["num"]=>
  int(3)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
}

See Also

pg_convert()

Prev | Home | Next
pg_lo_write | Up | pg_num_fields


pg_num_fields

(PHP 4 >= 4.2.0, PHP 5)

pg_num_fields -- Returns the number of fields in a result

Description

int pg_num_fields ( resource result )

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.

Note: This function used to be called pg_numfields().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of fields (columns) in the result. On error, -1 is returned.

Examples

Example 1. pg_num_fields() example

&#60;?php
$result = pg_query($conn, "SELECT 1, 2");

$num = pg_num_fields($result);

echo $num . " field(s) returned.\n";
?&#62;

The above example will output:

2 field(s) returned.

See Also

pg_num_rows()
pg_affected_rows()

Prev | Home | Next
pg_meta_data | Up | pg_num_rows


pg_num_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_num_rows -- Returns the number of rows in a result

Description

int pg_num_rows ( resource result )

pg_num_rows() will return the number of rows in a PostgreSQL result resource.

Note: This function used to be called pg_numrows().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows in the result. On error, -1 is returned.

Examples

Example 1. pg_num_rows() example

&#60;?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?&#62;

The above example will output:

1 row(s) returned.

See Also

pg_num_fields()
pg_affected_rows()

Prev | Home | Next
pg_num_fields | Up | pg_options


pg_options

(PHP 3, PHP 4, PHP 5)

pg_options -- Get the options associated with the connection

Description

string pg_options ( [resource connection] )

pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the connection options, or FALSE on error.

Examples

Example 1. pg_options() example

&#60;?php
   $pgsql_conn = pg_connect("dbname=mark host=localhost");
   echo pg_options($pgsql_conn);
?&#62;

See Also

pg_connect()

Prev | Home | Next
pg_num_rows | Up | pg_parameter_status


pg_parameter_status

(PHP 5)

pg_parameter_status -- Looks up a current parameter setting of the server.

Description

string pg_parameter_status ( resource connection, string param_name )

string pg_parameter_status ( string param_name )

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Caution

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Return Values

A string containing the value of the parameter, FALSE on failure or invalid param_name.

Examples

Example 1. pg_parameter_status() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?&#62;

The above example will output:

Server encoding: SQL_ASCII

Prev | Home | Next
pg_options | Up | pg_pconnect


pg_pconnect

(PHP 3, PHP 4, PHP 5)

pg_pconnect -- Open a persistent PostgreSQL connection

Description

resource pg_pconnect ( string connection_string [, int connect_type] )

pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.

If a second call is made to pg_pconnect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection can be defined with the pgsql.max_persistent php.ini directive (defaults to -1 for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.

pg_close() will not close persistent links generated by pg_pconnect().

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example 1. Using pg_pconnect()

&#60;?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?&#62;

See Also

pg_connect()
Persistent Database Connections

Prev | Home | Next
pg_parameter_status | Up | pg_ping


pg_ping

(PHP 4 >= 4.3.0, PHP 5)

pg_ping -- Ping database connection

Description

bool pg_ping ( [resource connection] )

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_ping() example

&#60;?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

if (!pg_ping($conn))
  die("Connection is broken\n");
?&#62;

See Also

pg_connection_status()
pg_connection_reset()

Prev | Home | Next
pg_pconnect | Up | pg_port


pg_port

(PHP 3, PHP 4, PHP 5)

pg_port -- Return the port number associated with the connection

Description

int pg_port ( [resource connection] )

pg_port() returns the port number that the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

An int containing the port number of the database server the connection is to, or FALSE on error.

Examples

Example 1. pg_port() example

&#60;?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to port: " . pg_port($pgsql_conn) . "&#60;br/&#62;\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?&#62;

Prev | Home | Next
pg_ping | Up | pg_prepare


pg_prepare

(PHP 5 >= 5.1.0RC1)

pg_prepare -- Submits a request to create a prepared statement with the given parameters, and waits for completion.

Description

resource pg_prepare ( resource connection, string stmtname, string query )

resource pg_prepare ( string stmtname, string query )

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

A query result resource on success, or FALSE on failure.

Examples

Example 1. Using pg_prepare()

&#60;?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?&#62;

See Also

pg_execute()
pg_send_execute()

Prev | Home | Next
pg_port | Up | pg_put_line


pg_put_line

(PHP 4 >= 4.0.3, PHP 5)

pg_put_line -- Send a NULL-terminated string to PostgreSQL backend

Description

bool pg_put_line ( string data )

bool pg_put_line ( resource connection, string data )

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's COPY FROM command.

COPY is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction.

An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.

Note: The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().

Warning

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A line of text to be sent directly to the PostgreSQL backend. A NULL terminator is added automatically.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_put_line() example

&#60;?php
  $conn = pg_pconnect("dbname=foo");
  pg_query($conn, "create table bar (a int4, b char(16), d float8)");
  pg_query($conn, "copy bar from stdin");
  pg_put_line($conn, "3\thello world\t4.5\n");
  pg_put_line($conn, "4\tgoodbye world\t7.11\n");
  pg_put_line($conn, "\\.\n");
  pg_end_copy($conn);
?&#62;

See Also

pg_end_copy()

Prev | Home | Next
pg_prepare | Up | pg_query_params


pg_query_params

(PHP 5 >= 5.1.0RC1)

pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

Description

resource pg_query_params ( resource connection, string query, array params )

resource pg_query_params ( string query, array params )

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

A query result resource on success, or FALSE on failure.

Examples

Example 1. Using pg_query_params()

&#60;?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?&#62;

See Also

pg_query()

Prev | Home | Next
pg_put_line | Up | pg_query


pg_query

(PHP 4 >= 4.2.0, PHP 5)

pg_query -- Execute a query

Description

resource pg_query ( string query )

resource pg_query ( resource connection, string query )

pg_query() executes the query on the specified database connection.

If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

Note: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.

Note: This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

Return Values

A query result resource on success, or FALSE on failure.

Examples

Example 1. pg_query() example

&#60;?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "&#60;br /&#62;\n";
}

?&#62;

Example 2. Using pg_query() with multiple statements

&#60;?php

$conn = pg_pconnect("dbname=publisher");

// these statements will be executed as one transaction

$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";

pg_query($conn, $query);

?&#62;

See Also

pg_connect()
pg_pconnect()
pg_fetch_array()
pg_fetch_object()
pg_num_rows()
pg_affected_rows()

Prev | Home | Next
pg_query_params | Up | pg_result_error_field


pg_result_error_field

(PHP 5 >= 5.1.0RC1)

pg_result_error_field -- Returns an individual field of an error report.

Description

string pg_result_error_field ( resource result, int fieldcode )

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.

Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

Parameters

result

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

Return Values

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Examples

Example 1. pg_result_error_field() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?&#62;

See Also

pg_result_error()

Prev | Home | Next
pg_query | Up | pg_result_error


pg_result_error

(PHP 4 >= 4.2.0, PHP 5)

pg_result_error -- Get error message associated with result

Description

string pg_result_error ( resource result )

pg_result_error() returns any error message associated with the result resource. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns a string if there is an error associated with the result parameter, FALSE otherwise.

Examples

Example 1. pg_result_error() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?&#62;

See Also

pg_result_error_field()
pg_query()
pg_send_query()
pg_get_result()
pg_last_error()
pg_last_notice()

Prev | Home | Next
pg_result_error_field | Up | pg_result_seek


pg_result_seek

(PHP 4 >= 4.3.0, PHP 5)

pg_result_seek -- Set internal row offset in result resource

Description

bool pg_result_seek ( resource result, int offset )

pg_result_seek() sets the internal row offset in a result resource.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

offset

Row to move the internal offset to in the result resource. Rows are numbered starting from zero.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_result_seek() example

&#60;?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a query
$result = pg_query($conn, "SELECT author, email FROM authors");

// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result, 2);

// Fetch the 3rd row
$row = pg_fetch_row($result);

?&#62;

See Also

pg_fetch_row()
pg_fetch_assoc()
pg_fetch_array()
pg_fetch_object()
pg_fetch_result()

Prev | Home | Next
pg_result_error | Up | pg_result_status


pg_result_status

(PHP 4 >= 4.2.0, PHP 5)

pg_result_status -- Get status of query result

Description

mixed pg_result_status ( resource result [, int type] )

pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

type

Either PGSQL_STATUS_LONG to return the numeric status of the result, or PGSQL_STATUS_STRING to return the command tag of the result. If not specified, PGSQL_STATUS_LONG is the default.

Return Values

Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is specified. Otherwise, a string containing the PostgreSQL command tag is returned.

Examples

Example 1. pg_result_status() example

&#60;?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");

// Get the result status
$status = pg_result_status($result);

// Determine status
if ($status == PGSQL_COPY_IN)
   echo "Copy began.";
else
   echo "Copy failed.";

?&#62;

The above example will output:

Copy began.

See Also

pg_connection_status()

Prev | Home | Next
pg_result_seek | Up | pg_select


pg_select

(PHP 4 >= 4.3.0, PHP 5)

pg_select -- Select records

Description

mixed pg_select ( resource connection, string table_name, array assoc_array [, int options] )

pg_select() selects records specified by assoc_array which has field=>value. For a successful query, it returns an array containing all records and fields that match the condition specified by assoc_array.

If options is specified, pg_convert() is applied to assoc_array with the specified 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

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be retrieved.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example 1. pg_select() example

&#60;?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $rec = pg_select($db, 'post_log', $_POST);
  if ($rec) {
      echo "Records selected\n";
      var_dump($rec);
  } else {
      echo "User must have sent wrong inputs\n";
  }
?&#62;

See Also

pg_convert()

Prev | Home | Next
pg_result_status | Up | pg_send_execute


pg_send_execute

(PHP 5 >= 5.1.0RC1)

pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

Description

bool pg_send_execute ( resource connection, string stmtname, array params )

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example 1. Using pg_send_execute()

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?&#62;

See Also

pg_prepare()
pg_send_prepare()
pg_execute()

Prev | Home | Next
pg_select | Up | pg_send_prepare


pg_send_prepare

(PHP 5 >= 5.1.0RC1)

pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.

Description

bool pg_send_prepare ( resource connection, string stmtname, string query )

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example 1. Using pg_send_prepare()

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?&#62;

See Also

pg_connect()
pg_pconnect()
pg_execute()
pg_send_execute()
pg_send_query_params()

Prev | Home | Next
pg_send_execute | Up | pg_send_query_params


pg_send_query_params

(PHP 5 >= 5.1.0RC1)

pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).

Description

bool pg_send_query_params ( resource connection, string query, array params )

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

Parameters

connection

PostgreSQL database connection resource.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example 1. Using pg_send_query_params()

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Using parameters.  Note that it is not necessary to quote or escape
  // the parameter.
  pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));

  // Compare against basic pg_send_query usage
  $str = pg_escape_string('Perth');
  pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?&#62;

See Also

pg_send_query()

Prev | Home | Next
pg_send_prepare | Up | pg_send_query


pg_send_query

(PHP 4 >= 4.2.0, PHP 5)

pg_send_query -- Sends asynchronous query

Description

bool pg_send_query ( resource connection, string query )

pg_send_query() sends a query or queries asynchronously to the connection. Unlike pg_query(), it can send multiple queries at once to PostgreSQL and get the results one by one using pg_get_result().

Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().

Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.

Parameters

connection

PostgreSQL database connection resource.

query

The SQL statement or statements to be executed.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example 1. pg_send_query() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?&#62;

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

See Also

pg_query()
pg_cancel_query()
pg_get_result()
pg_connection_busy()

Prev | Home | Next
pg_send_query_params | Up | pg_set_client_encoding


pg_set_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)

pg_set_client_encoding -- Set the client encoding

Description

int pg_set_client_encoding ( string encoding )

int pg_set_client_encoding ( resource connection, string encoding )

pg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.

PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.

Note: The function used to be called pg_setclientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

encoding

The required client encoding. One of SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5 or WIN1250.

The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.

Return Values

Returns 0 on success or -1 on error.

Examples

Example 1. pg_set_client_encoding() example

&#60;?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, UNICODE);

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "&#60;br /&#62;\n";
}

?&#62;

See Also

pg_client_encoding()

Prev | Home | Next
pg_send_query | Up | pg_set_error_verbosity


pg_set_error_verbosity

(PHP 5 >= 5.1.0RC1)

pg_set_error_verbosity -- Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

Description

int pg_set_error_verbosity ( resource connection, int verbosity )

int pg_set_error_verbosity ( int verbosity )

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Return Values

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Examples

Example 1. pg_set_error_verbosity() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?&#62;

See Also

pg_last_error()
pg_result_error()

Prev | Home | Next
pg_set_client_encoding | Up | pg_trace


pg_trace

(PHP 4 >= 4.0.1, PHP 5)

pg_trace -- Enable tracing a PostgreSQL connection

Description

bool pg_trace ( string pathname [, string mode [, resource connection]] )

pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.

For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the PostgreSQL Documentation.

Parameters

pathname

The full path and file name of the file in which to write the trace log. Same as in fopen().

pathname

An optional file access mode, same as for fopen(). Defaults to "w".

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. pg_trace() example

&#60;?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now /tmp/trace.log will contain backend communication
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?&#62;

See Also

fopen()
pg_untrace()

Prev | Home | Next
pg_set_error_verbosity | Up | pg_transaction_status


pg_tty

(PHP 3, PHP 4, PHP 5)

pg_tty -- Return the TTY name associated with the connection

Description

string pg_tty ( [resource connection] )

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL connection resource.

Note: pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the debug TTY of the connection, or FALSE on error.

Examples

Example 1. pg_tty() example

&#60;?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Server debug TTY is: " . pg_tty($pgsql_conn) . "&#60;br/&#62;\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?&#62;

Prev | Home | Next
pg_transaction_status | Up | pg_unescape_bytea


pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5)

pg_unescape_bytea -- Unescape binary for bytea type

Description

string pg_unescape_bytea ( string data )

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

Note: When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

data

A string containing PostgreSQL bytea data to be converted into a PHP binary string.

Return Values

A string containing the unescaped data.

Examples

Example 1. pg_unescape_bytea() example

&#60;?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Get the bytea data
  $res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo pg_unescape_bytea($raw);
?&#62;

See Also

pg_escape_bytea()
pg_escape_string()

Prev | Home | Next
pg_tty | Up | pg_untrace


pg_untrace

(PHP 4 >= 4.0.1, PHP 5)

pg_untrace -- Disable tracing of a PostgreSQL connection

Description

bool pg_untrace ( [resource connection] )

Stop tracing started by pg_trace().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Always returns TRUE.

Examples

Example 1. pg_untrace() example

&#60;?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now tracing of backend communication is disabled
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?&#62;

See Also

pg_trace()

Prev | Home | Next
pg_unescape_bytea | Up | pg_update


pg_update

(PHP 4 >= 4.3.0, PHP 5)

pg_update -- Update table

Description

mixed pg_update ( resource connection, string table_name, array data, array condition [, int options] )

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

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

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name, and whose values are what matched rows are to be updated to.

condition

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be updated.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example 1. pg_update() example

&#60;?php
  $db = pg_connect('dbname=foo');
  $data = array('field1'=&#62;'AA', 'field2'=&#62;'BB');

  // This is safe, since $_POST is converted automatically
  $res = pg_update($db, 'post_log', $_POST, $data);
  if ($res) {
      echo "Data is updated: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?&#62;

See Also

pg_convert()

Prev | Home | Next
pg_untrace | Up | pg_version


pg_version

(PHP 5)

pg_version -- Returns an array with client, protocol and server version (when available)

Description

array pg_version ( [resource connection] )

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns an array with client, protocol and server_version keys and values (if available). Returns FALSE on error or invalid connection.

Examples

Example 1. pg_version() example

&#60;?php
  $dbconn = pg_connect("host=localhost port=5432 dbname=mary")
     or die("Could not connect");

  $v = pg_version($dbconn);

  echo $v['client'];
?&#62;

The above example will output:

7.4

See Also

pg_parameter_status()

Prev | Home | Next
pg_update | Up | PostgreSQL Functions (PDO_PGSQL)


POSIX Functions

PHP Manual
Prev Next

CXXIII. POSIX Functions

Introduction

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means. POSIX.1 for example defined the open(), read(), write() and close() functions, too, which traditionally have been part of PHP 3 for a long time. Some more system specific functions have not been available before, though, and this module tries to remedy this by providing easy access to these functions.

Warning

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

Note: This extension is not available on Windows platforms.

Installation

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix.

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.

POSIX_F_OK (integer)

Check whether the file exists.

POSIX_R_OK (integer)

Check whether the file exists and has read permissions.

POSIX_W_OK (integer)

Check whether the file exists and has write permissions.

POSIX_X_OK (integer)

Check whether the file exists and has execute permissions.

POSIX_S_IFBLK (integer)

Block special file

POSIX_S_IFCHR (integer)

Character special file

POSIX_S_IFIFO (integer)

FIFO (named pipe) special file

POSIX_S_IFREG (integer)

Normal file

POSIX_S_IFSOCK (integer)

Socket

Note: These constants are available since PHP 5.1.0. Please also note that some of them may not be available in your system.

See Also

The section about Process Control Functions maybe of interest for you.

Table of Contents
posix_access -- Determine accessibility of a file
posix_ctermid -- Get path name of controlling terminal
posix_get_last_error -- Retrieve the error number set by the last posix function that failed
posix_getcwd -- Pathname of current directory
posix_getegid -- Return the effective group ID of the current process
posix_geteuid -- Return the effective user ID of the current process
posix_getgid -- Return the real group ID of the current process
posix_getgrgid -- Return info about a group by group id
posix_getgrnam -- Return info about a group by name
posix_getgroups -- Return the group set of the current process
posix_getlogin -- Return login name
posix_getpgid -- Get process group id for job control
posix_getpgrp -- Return the current process group identifier
posix_getpid -- Return the current process identifier
posix_getppid -- Return the parent process identifier
posix_getpwnam -- Return info about a user by username
posix_getpwuid -- Return info about a user by user id
posix_getrlimit -- Return info about system resource limits
posix_getsid -- Get the current sid of the process
posix_getuid -- Return the real user ID of the current process
posix_isatty -- Determine if a file descriptor is an interactive terminal
posix_kill -- Send a signal to a process
posix_mkfifo -- Create a fifo special file (a named pipe)
posix_mknod -- Create a special or ordinary file (POSIX.1)
posix_setegid -- Set the effective GID of the current process
posix_seteuid -- Set the effective UID of the current process
posix_setgid -- Set the GID of the current process
posix_setpgid -- Set process group id for job control
posix_setsid -- Make the current process a session leader
posix_setuid -- Set the UID of the current process
posix_strerror -- Retrieve the system error message associated with the given errno
posix_times -- Get process times
posix_ttyname -- Determine terminal device name
posix_uname -- Get system name

Prev | Home | Next
zend_version | Up | posix_access


posix_access

(PHP 5 >= 5.1.0RC1)

posix_access -- Determine accessibility of a file

Description

bool posix_access ( string file [, int mode] )

posix_access() checks the user's permission of a file.

Parameters

file

The name of the file to be tested.

mode

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK. Defaults to POSIX_F_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

&#60;?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
    echo 'The file is readable and writable!';

} else {
    $error = posix_get_last_error();

    echo "Error $error: " . posix_strerror($error);
}

?&#62;

Notes

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

posix_get_last_error()
posix_strerror()

Prev | Home | Next
POSIX Functions | Up | posix_ctermid


posix_ctermid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_ctermid -- Get path name of controlling terminal

Description

string posix_ctermid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
posix_access | Up | posix_get_last_error


posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5)

posix_get_last_error -- Retrieve the error number set by the last posix function that failed

Description

int posix_get_last_error ( void )

Retrieve the error number set by the last posix function that failed. If you're wanting the system error message associated with the errno, use posix_strerror().

Return Values

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

See Also

posix_strerror()

Prev | Home | Next
posix_ctermid | Up | posix_getcwd


posix_getcwd

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getcwd -- Pathname of current directory

Description

string posix_getcwd ( void )

Gets the absolute pathname of the script's current working directory.

Return Values

Returns the absolute pathname, or FALSE on error.

Prev | Home | Next
posix_get_last_error | Up | posix_getegid


posix_getegid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getegid -- Return the effective group ID of the current process

Description

int posix_getegid ( void )

Return the numeric effective group ID of the current process.

Return Values

Returns the group ID.

See Also

posix_getgrgid() for information on how to convert this into a useable group name

Prev | Home | Next
posix_getcwd | Up | posix_geteuid


posix_geteuid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_geteuid -- Return the effective user ID of the current process

Description

int posix_geteuid ( void )

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

Return Values

Returns the identifier, as an integer.

Prev | Home | Next
posix_getegid | Up | posix_getgid


posix_getgid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getgid -- Return the real group ID of the current process

Description

int posix_getgid ( void )

Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

Return Values

Returns the identifier, as an integer.

Prev | Home | Next
posix_geteuid | Up | posix_getgrgid


posix_getgrgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getgrgid -- Return info about a group by group id

Description

array posix_getgrgid ( int gid )

Gets information about a group provided its id.

Parameters

gid

The group id.

Return Values

Returns an array of information about a group and FALSE on failure. If gid isn't a number then NULL is returned and an E_WARNING level error is generated.

ChangeLog

Version | Description
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Examples

Example 1. Example use of posix_getgrgid()

&#60;?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);

?&#62;

The above example will output something similar to:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

posix_getegid()
filegroup()
stat()
safe_mode_gid

Prev | Home | Next
posix_getgid | Up | posix_getgrnam


posix_getgrnam

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getgrnam -- Return info about a group by name

Description

array posix_getgrnam ( string name )

Warning

This function is currently not documented; only the argument list is available.

Parameters

name

Prev | Home | Next
posix_getgrgid | Up | posix_getgroups


posix_getgroups

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getgroups -- Return the group set of the current process

Description

array posix_getgroups ( void )

Gets the group set of the current process.

Return Values

Returns an array of integers containing the numeric group ids of the group set of the current process.

See Also

posix_getgrgid()

Prev | Home | Next
posix_getgrnam | Up | posix_getlogin


posix_getlogin

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getlogin -- Return login name

Description

string posix_getlogin ( void )

Returns the login name of the user owning the current process.

Return Values

Returns the login name of the user, as a string.

See Also

posix_getpwnam()

Prev | Home | Next
posix_getgroups | Up | posix_getpgid


posix_getpgid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpgid -- Get process group id for job control

Description

int posix_getpgid ( int pid )

Returns the process group identifier of the process pid.

Parameters

pid

The process id.

Return Values

Returns the identifier, as an integer.

Notes

Note: This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

Prev | Home | Next
posix_getlogin | Up | posix_getpgrp


posix_getpgrp

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpgrp -- Return the current process group identifier

Description

int posix_getpgrp ( void )

Return the process group identifier of the current process.

Return Values

Returns the identifier, as an integer.

See Also

POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.

Prev | Home | Next
posix_getpgid | Up | posix_getpid


posix_getpid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpid -- Return the current process identifier

Description

int posix_getpid ( void )

Return the process identifier of the current process.

Return Values

Returns the identifier, as an integer.

Prev | Home | Next
posix_getpgrp | Up | posix_getppid


posix_getppid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getppid -- Return the parent process identifier

Description

int posix_getppid ( void )

Return the process identifier of the parent process of the current process.

Return Values

Returns the identifier, as an integer.

Prev | Home | Next
posix_getpid | Up | posix_getpwnam


posix_getpwnam

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getpwnam -- Return info about a user by username

Description

array posix_getpwnam ( string username )

Returns an information about the given user.

Parameters

username

An alphanumeric username.

Return Values

The array elements returned are:

Table 1. The user information array

Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Prev | Home | Next
posix_getppid | Up | posix_getpwuid


posix_getpwuid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getpwuid -- Return info about a user by user id

Description

array posix_getpwuid ( int uid )

Gets information about the user referenced by the given user ID.

Parameters

uid

The user identifier.

Return Values

Returns an associative array with the following elements:

Table 1. The user information array

Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Prev | Home | Next
posix_getpwnam | Up | posix_getrlimit


posix_getrlimit

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getrlimit -- Return info about system resource limits

Description

array posix_getrlimit ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
posix_getpwuid | Up | posix_getsid


posix_getsid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getsid -- Get the current sid of the process

Description

int posix_getsid ( int pid )

Return the sid of the process pid.

Parameters

pid

The process identifier. If set to 0, the current process is assumed.

Return Values

Returns the identifier, as an integer.

Notes

Note: This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

Prev | Home | Next
posix_getrlimit | Up | posix_getuid


posix_getuid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getuid -- Return the real user ID of the current process

Description

int posix_getuid ( void )

Return the numeric real user ID of the current process.

Return Values

Returns the identifier, as an integer.

See Also

posix_getpwuid() for information on how to convert this into a useable username

Prev | Home | Next
posix_getsid | Up | posix_isatty


posix_isatty

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_isatty -- Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int fd )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
posix_getuid | Up | posix_kill


posix_kill

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_kill -- Send a signal to a process

Description

bool posix_kill ( int pid, int sig )

Send the signal sig to the process with the process identifier pid.

Parameters

pid

The process identifier.

sig

One of the PCNTL signals constants.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

The kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

Prev | Home | Next
posix_isatty | Up | posix_mkfifo


posix_mkfifo

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_mkfifo -- Create a fifo special file (a named pipe)

Description

bool posix_mkfifo ( string pathname, int mode )

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

Parameters

pathname

Path to the FIFO file.

mode

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Prev | Home | Next
posix_kill | Up | posix_mknod


posix_setegid

(PHP 4 >= 4.0.2, PHP 5)

posix_setegid -- Set the effective GID of the current process

Description

bool posix_setegid ( int gid )

Set the effective group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
posix_mknod | Up | posix_seteuid


posix_seteuid

(PHP 4 >= 4.0.2, PHP 5)

posix_seteuid -- Set the effective UID of the current process

Description

bool posix_seteuid ( int uid )

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

posix_setgid()

Prev | Home | Next
posix_setegid | Up | posix_setgid


posix_setgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setgid -- Set the GID of the current process

Description

bool posix_setgid ( int gid )

Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
posix_seteuid | Up | posix_setpgid


posix_setpgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setpgid -- Set process group id for job control

Description

bool posix_setpgid ( int pid, int pgid )

Let the process pid join the process group pgid.

Parameters

pid

The process id.

pgid

The process group id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control.

Prev | Home | Next
posix_setgid | Up | posix_setsid


posix_setsid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setsid -- Make the current process a session leader

Description

int posix_setsid ( void )

Make the current process a session leader.

Return Values

Returns the session id, or -1 on errors.

See Also

The POSIX.1 and the setsid(2) manual page on your POSIX system for more information on process groups and job control. Returns the session id.

Prev | Home | Next
posix_setpgid | Up | posix_setuid


posix_setuid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setuid -- Set the UID of the current process

Description

bool posix_setuid ( int uid )

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

posix_setgid()

Prev | Home | Next
posix_setsid | Up | posix_strerror


posix_strerror

(PHP 4 >= 4.2.0, PHP 5)

posix_strerror -- Retrieve the system error message associated with the given errno

Description

string posix_strerror ( int errno )

Returns the POSIX system error message associated with the given errno.

Parameters

errno

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

Return Values

Returns the error message, as a string.

See Also

posix_get_last_error()

Prev | Home | Next
posix_setuid | Up | posix_times


posix_times

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_times -- Get process times

Description

array posix_times ( void )

Gets information about the current CPU usage.

Return Values

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are:

  • ticks - the number of clock ticks that have elapsed since reboot.

  • utime - user time used by the current process.

  • stime - system time used by the current process.

  • cutime - user time used by current process and children.

  • cstime - system time used by current process and children.

Notes

Warning

This function isn't reliable to use, it may return negative values for high times.

Prev | Home | Next
posix_strerror | Up | posix_ttyname


posix_ttyname

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_ttyname -- Determine terminal device name

Description

string posix_ttyname ( int fd )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
posix_times | Up | posix_uname


posix_uname

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_uname -- Get system name

Description

array posix_uname ( void )

Gets information about the system.

Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.

Return Values

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)

  • nodename - system name (e.g. valiant)

  • release - operating system release (e.g. 2.2.10)

  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)

  • machine - system architecture (e.g. i586)

  • domainname - DNS domainname (e.g. example.com)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Prev | Home | Next
posix_ttyname | Up | Regular Expression Functions (POSIX Extended)


Printer Functions

PHP Manual
Prev Next

CXXVII. Printer Functions

Introduction

These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4.0.4.

Installation

This PECL extension is not bundled with PHP.

Windows users must enable php_printer.dll inside of php.ini in order to use these functions. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Printer configuration options

Name | Default | Changeable | Changelog
printer.default_printer | "" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Table of Contents
printer_abort -- Deletes the printer's spool file
printer_close -- Close an open printer connection
printer_create_brush -- Create a new brush
printer_create_dc -- Create a new device context
printer_create_font -- Create a new font
printer_create_pen -- Create a new pen
printer_delete_brush -- Delete a brush
printer_delete_dc -- Delete a device context
printer_delete_font -- Delete a font
printer_delete_pen -- Delete a pen
printer_draw_bmp -- Draw a bmp
printer_draw_chord -- Draw a chord
printer_draw_elipse -- Draw an ellipse
printer_draw_line -- Draw a line
printer_draw_pie -- Draw a pie
printer_draw_rectangle -- Draw a rectangle
printer_draw_roundrect -- Draw a rectangle with rounded corners
printer_draw_text -- Draw text
printer_end_doc -- Close document
printer_end_page -- Close active page
printer_get_option -- Retrieve printer configuration data
printer_list -- Return an array of printers attached to the server
printer_logical_fontheight -- Get logical font height
printer_open -- Open connection to a printer
printer_select_brush -- Select a brush
printer_select_font -- Select a font
printer_select_pen -- Select a pen
printer_set_option -- Configure the printer connection
printer_start_doc -- Start a new document
printer_start_page -- Start a new page
printer_write -- Write data to the printer

Prev | Home | Next
PDO::pgsqlLOBUnlink | Up | printer_abort


printer_abort

(PECL)

printer_abort -- Deletes the printer's spool file

Description

void printer_abort ( resource handle )

This function deletes the printers spool file.

handle must be a valid handle to a printer.

Example 1. printer_abort() example

&#60;?php
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
Printer Functions | Up | printer_close


printer_close

(PECL)

printer_close -- Close an open printer connection

Description

void printer_close ( resource handle )

This function closes the printer connection. printer_close() also closes the active device context.

handle must be a valid handle to a printer.

Example 1. printer_close() example

&#60;?php
$handle = printer_open();
printer_close($handle);
?&#62;

Prev | Home | Next
printer_abort | Up | printer_create_brush


printer_create_brush

(PECL)

printer_create_brush -- Create a new brush

Description

resource printer_create_brush ( int style, string color )

The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush(). color must be a color in RGB hex format, i.e. "000000" for black, style must be one of the following constants:

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.

  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).

  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).

  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).

  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).

  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).

  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).

  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

Prev | Home | Next
printer_close | Up | printer_create_dc


printer_create_dc

(PECL)

printer_create_dc -- Create a new device context

Description

void printer_create_dc ( resource handle )

The function creates a new device context. A device context is used to customize the graphic objects of the document. handle must be a valid handle to a printer.

Example 1. printer_create_dc() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */

printer_delete_dc($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_create_brush | Up | printer_create_font


printer_create_font

(PECL)

printer_create_font -- Create a new font

Description

resource printer_create_font ( string face, int height, int width, int font_weight, bool italic, bool underline, bool strikeout, int orientation )

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font(). face must be a string specifying the font face. height specifies the font height, and width the font width. The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).

  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).

  • PRINTER_FW_LIGHT: sets the font weight to light (300).

  • PRINTER_FW_NORMAL: sets the font weight to normal (400).

  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).

  • PRINTER_FW_BOLD: sets the font weight to bold (700).

  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).

  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout can be TRUE or FALSE, and sets whether the font should be stroked out.

orientation specifies a rotation. For an example see printer_select_font().

Prev | Home | Next
printer_create_dc | Up | printer_create_pen


printer_create_pen

(PECL)

printer_create_pen -- Create a new pen

Description

resource printer_create_pen ( int style, int width, string color )

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black, width specifies the width of the pen whereas style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.

  • PRINTER_PEN_DASH: creates a dashed pen.

  • PRINTER_PEN_DOT: creates a dotted pen.

  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.

  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.

  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

Prev | Home | Next
printer_create_font | Up | printer_delete_brush


printer_delete_brush

(PECL)

printer_delete_brush -- Delete a brush

Description

void printer_delete_brush ( resource handle )

The function deletes the selected brush. For an example see printer_select_brush(). Returns NULL on success or FALSE on failure. handle must be a valid handle to a brush.

Prev | Home | Next
printer_create_pen | Up | printer_delete_dc


printer_delete_dc

(PECL)

printer_delete_dc -- Delete a device context

Description

bool printer_delete_dc ( resource handle )

The function deletes the device context. Returns TRUE on success or FALSE on failure. For an example see printer_create_dc(). handle must be a valid handle to a printer.

Prev | Home | Next
printer_delete_brush | Up | printer_delete_font


printer_delete_font

(PECL)

printer_delete_font -- Delete a font

Description

void printer_delete_font ( resource handle )

The function deletes the selected font. For an example see printer_select_font(). Returns NULL on success or FALSE on failure. handle must be a valid handle to a font.

Prev | Home | Next
printer_delete_dc | Up | printer_delete_pen


printer_delete_pen

(PECL)

printer_delete_pen -- Delete a pen

Description

void printer_delete_pen ( resource handle )

The function deletes the selected pen. For an example see printer_select_pen(). Returns NULL on success or FALSE on failure. handle must be a valid handle to a pen.

Prev | Home | Next
printer_delete_font | Up | printer_draw_bmp


printer_draw_bmp

(PECL)

printer_draw_bmp -- Draw a bmp

Description

bool printer_draw_bmp ( resource handle, string filename, int x, int y [, int width, int height] )

The function simply draws an bmp the bitmap filename at position x, y. handle must be a valid handle to a printer.

Returns TRUE on success or FALSE on failure.

Example 1. printer_draw_bmp() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_delete_pen | Up | printer_draw_chord


printer_draw_chord

(PECL)

printer_draw_chord -- Draw a chord

Description

void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int rad_x1, int rad_y1 )

The function simply draws an chord. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad_x is x coordinate of the radial defining the beginning of the chord.

rad_y is y coordinate of the radial defining the beginning of the chord.

rad_x1 is x coordinate of the radial defining the end of the chord.

rad_y1 is y coordinate of the radial defining the end of the chord.

Example 1. printer_draw_chord() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_bmp | Up | printer_draw_elipse


printer_draw_elipse

(PECL)

printer_draw_elipse -- Draw an ellipse

Description

void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y )

The function simply draws an ellipse. handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the ellipse.

ul_y is the upper left y coordinate of the ellipse.

lr_x is the lower right x coordinate of the ellipse.

lr_y is the lower right y coordinate of the ellipse.

Example 1. printer_draw_elipse() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_chord | Up | printer_draw_line


printer_draw_line

(PECL)

printer_draw_line -- Draw a line

Description

void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y )

The function simply draws a line from position from_x, from_y to position to_x, to_y using the selected pen. printer_handle must be a valid handle to a printer.

Example 1. printer_draw_line() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_elipse | Up | printer_draw_pie


printer_draw_pie

(PECL)

printer_draw_pie -- Draw a pie

Description

void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int rad2_x, int rad2_y )

The function simply draws an pie. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad1_x is x coordinate of the first radial's ending.

rad1_y is y coordinate of the first radial's ending.

rad2_x is x coordinate of the second radial's ending.

rad2_y is y coordinate of the second radial's ending.

Example 1. printer_draw_pie() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_line | Up | printer_draw_rectangle


printer_draw_rectangle

(PECL)

printer_draw_rectangle -- Draw a rectangle

Description

void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y )

The function simply draws a rectangle.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

Example 1. printer_draw_rectangle() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_pie | Up | printer_draw_roundrect


printer_draw_roundrect

(PECL)

printer_draw_roundrect -- Draw a rectangle with rounded corners

Description

void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height )

The function simply draws a rectangle with rounded corners.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

width is the width of the ellipse.

height is the height of the ellipse.

Example 1. printer_draw_roundrect() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_rectangle | Up | printer_draw_text


printer_draw_text

(PECL)

printer_draw_text -- Draw text

Description

void printer_draw_text ( resource printer_handle, string text, int x, int y )

The function simply draws text at position x, y using the selected font. printer_handle must be a valid handle to a printer.

Example 1. printer_draw_text() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 72, 48, 400, false, false, false, 0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_draw_roundrect | Up | printer_end_doc


printer_end_doc

(PECL)

printer_end_doc -- Close document

Description

bool printer_end_doc ( resource handle )

Closes a new document in the printer spooler. The document is now ready for printing. For an example see printer_start_doc(). handle must be a valid handle to a printer.

Prev | Home | Next
printer_draw_text | Up | printer_end_page


printer_end_page

(PECL)

printer_end_page -- Close active page

Description

bool printer_end_page ( resource handle )

The function closes the active page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

Prev | Home | Next
printer_end_doc | Up | printer_get_option


printer_get_option

(PECL)

printer_get_option -- Retrieve printer configuration data

Description

mixed printer_get_option ( resource handle, string option )

The function retrieves the configuration setting of option. handle must be a valid handle to a printer. Take a look at printer_set_option() for the settings that can be retrieved, additionally the following settings can be retrieved:

  • PRINTER_DEVICENAME returns the devicename of the printer.

  • PRINTER_DRIVERVERSION returns the printer driver version.

Example 1. printer_get_option() example

&#60;?php
$handle = printer_open();
echo printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_end_page | Up | printer_list


printer_list

(PECL)

printer_list -- Return an array of printers attached to the server

Description

array printer_list ( int enumtype [, string name [, int level]] )

The function enumerates available printers and their capabilities. level sets the level of information request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:

  • PRINTER_ENUM_LOCAL: enumerates the locally installed printers.

  • PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.

  • PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.

  • PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.

  • PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.

  • PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.

  • PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.

Example 1. printer_list() example

&#60;?php
/* detect locally shared printer */
var_dump(printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED));
?&#62;

Prev | Home | Next
printer_get_option | Up | printer_logical_fontheight


printer_logical_fontheight

(PECL)

printer_logical_fontheight -- Get logical font height

Description

int printer_logical_fontheight ( resource handle, int height )

The function calculates the logical font height of height. handle must be a valid handle to a printer.

Example 1. printer_logical_fontheight() example

&#60;?php
$handle = printer_open();
echo printer_logical_fontheight($handle, 72);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_list | Up | printer_open


printer_open

(PECL)

printer_open -- Open connection to a printer

Description

resource printer_open ( [string devicename] )

This function tries to open a connection to the printer devicename, and returns a handle on success or FALSE on failure.

If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, PHP tries to detect it).

printer_open() also starts a device context.

Example 1. printer_open() example

&#60;?php
$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();
?&#62;

Prev | Home | Next
printer_logical_fontheight | Up | printer_select_brush


printer_select_brush

(PECL)

printer_select_brush -- Select a brush

Description

void printer_select_brush ( resource printer_handle, resource brush_handle )

The function selects a brush as the active drawing object of the actual device context. A brush is used to fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw the border. If you haven't selected a brush before drawing shapes, the shape won't be filled. printer_handle must be a valid handle to a printer. brush_handle must be a valid handle to a brush.

Example 1. printer_select_brush() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 501, 500, 1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_open | Up | printer_select_font


printer_select_font

(PECL)

printer_select_font -- Select a font

Description

void printer_select_font ( resource printer_handle, resource font_handle )

The function selects a font to draw text. printer_handle must be a valid handle to a printer. font_handle must be a valid handle to a font.

Example 1. printer_select_font() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_select_brush | Up | printer_select_pen


printer_select_pen

(PECL)

printer_select_pen -- Select a pen

Description

void printer_select_pen ( resource printer_handle, resource pen_handle )

The function selects a pen as the active drawing object of the actual device context. A pen is used to draw lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to draw the borders, while the brush is used to fill the shape. If you haven't selected a pen before drawing shapes, the shape won't be outlined. printer_handle must be a valid handle to a printer. pen_handle must be a valid handle to a pen.

Example 1. printer_select_pen() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_select_font | Up | printer_set_option


printer_set_option

(PECL)

printer_set_option -- Configure the printer connection

Description

bool printer_set_option ( resource handle, int option, mixed value )

The function sets the following options for the current connection. handle must be a valid handle to a printer. For option can be one of the following constants:

  • PRINTER_COPIES: sets how many copies should be printed, value must be an integer.

  • PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.

  • PRINTER_TITLE: specifies the name of the document, value must be a string.

  • PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE

  • PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.

  • PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.

  • PRINTER_PAPER_FORMAT: specifies a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.

    • PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.

    • PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).

    • PRINTER_FORMAT_LEGAL: specifies standard legal format (8 1/2- by 14-inches).

    • PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).

    • PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).

    • PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).

    • PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).

    • PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).

    • PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).

  • PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.

  • PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.

  • PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of its original size. value must be an integer.

  • PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:

    • PRINTER_TA_BASELINE: text will be aligned at the base line.

    • PRINTER_TA_BOTTOM: text will be aligned at the bottom.

    • PRINTER_TA_TOP: text will be aligned at the top.

    • PRINTER_TA_CENTER: text will be aligned at the center.

    • PRINTER_TA_LEFT: text will be aligned at the left.

    • PRINTER_TA_RIGHT: text will be aligned at the right.

Example 1. printer_set_option() example

&#60;?php
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_select_pen | Up | printer_start_doc


printer_start_doc

(PECL)

printer_start_doc -- Start a new document

Description

bool printer_start_doc ( resource handle [, string document] )

The function creates a new document in the printer spooler. A document can contain multiple pages, it's used to schedule the print job in the spooler. handle must be a valid handle to a printer. The optional parameter document can be used to set an alternative document name.

Example 1. printer_start_doc() example

&#60;?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?&#62;

Prev | Home | Next
printer_set_option | Up | printer_start_page


printer_start_page

(PECL)

printer_start_page -- Start a new page

Description

bool printer_start_page ( resource handle )

The function creates a new page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

Prev | Home | Next
printer_start_doc | Up | printer_write


printer_write

(PECL)

printer_write -- Write data to the printer

Description

bool printer_write ( resource handle, string content )

Writes content directly to the printer. Returns TRUE on success or FALSE on failure.

handle must be a valid handle to a printer.

Example 1. printer_write() example

&#60;?php
$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);
?&#62;

Prev | Home | Next
printer_start_page | Up | Program Execution Functions


Pspell Functions

PHP Manual
Prev Next

CXXX. Pspell Functions

Introduction

These functions allow you to check the spelling of a word and offer suggestions.

Requirements

To compile PHP with pspell support, you need the aspell library, available from http://aspell.sourceforge.net/.

Installation

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note to Win32 Users: win32 support is available only in PHP 4.3.3 and later versions. Also, you must have aspell 0.50 or newer installed. In order to enable this module under Windows, you must copy aspell-15.dll from the bin folder of your aspell installation to a folder where PHP will be able to find it. C:\PHP or the SYSTEM32 folder of your windows machine (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32) are good choices.

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.

PSPELL_FAST (integer)

PSPELL_NORMAL (integer)

PSPELL_BAD_SPELLERS (integer)

PSPELL_RUN_TOGETHER (integer)

Table of Contents
pspell_add_to_personal -- Add the word to a personal wordlist
pspell_add_to_session -- Add the word to the wordlist in the current session
pspell_check -- Check a word
pspell_clear_session -- Clear the current session
pspell_config_create -- Create a config used to open a dictionary
pspell_config_data_dir -- location of language data files
pspell_config_dict_dir -- Location of the main word list
pspell_config_ignore -- Ignore words less than N characters long
pspell_config_mode -- Change the mode number of suggestions returned
pspell_config_personal -- Set a file that contains personal wordlist
pspell_config_repl -- Set a file that contains replacement pairs
pspell_config_runtogether -- Consider run-together words as valid compounds
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist
pspell_new_config -- Load a new dictionary with settings based on a given config
pspell_new_personal -- Load a new dictionary with personal wordlist
pspell_new -- Load a new dictionary
pspell_save_wordlist -- Save the personal wordlist to a file
pspell_store_replacement -- Store a replacement pair for a word
pspell_suggest -- Suggest spellings of a word

Prev | Home | Next
ps_translate | Up | pspell_add_to_personal


pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_personal -- Add the word to a personal wordlist

Description

bool pspell_add_to_personal ( int dictionary_link, string word )

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Example 1. pspell_add_to_personal()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?&#62;

Prev | Home | Next
Pspell Functions | Up | pspell_add_to_session


pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_session -- Add the word to the wordlist in the current session

Description

bool pspell_add_to_session ( int dictionary_link, string word )

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

Prev | Home | Next
pspell_add_to_personal | Up | pspell_check


pspell_check

(PHP 4 >= 4.0.2, PHP 5)

pspell_check -- Check a word

Description

bool pspell_check ( int dictionary_link, string word )

pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

Example 1. pspell_check()

&#60;?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?&#62;

Prev | Home | Next
pspell_add_to_session | Up | pspell_clear_session


pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_clear_session -- Clear the current session

Description

bool pspell_clear_session ( int dictionary_link )

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

Example 1. pspell_add_to_personal()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?&#62;

Prev | Home | Next
pspell_check | Up | pspell_config_create


pspell_config_create

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_create -- Create a config used to open a dictionary

Description

int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]] )

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Example 1. pspell_config_create()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal($pspell_config, "en");
?&#62;

Prev | Home | Next
pspell_clear_session | Up | pspell_config_data_dir


pspell_config_data_dir

(PHP 5)

pspell_config_data_dir -- location of language data files

Description

bool pspell_config_data_dir ( int conf, string directory )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
pspell_config_create | Up | pspell_config_dict_dir


pspell_config_dict_dir

(PHP 5)

pspell_config_dict_dir -- Location of the main word list

Description

bool pspell_config_dict_dir ( int conf, string directory )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
pspell_config_data_dir | Up | pspell_config_ignore


pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_ignore -- Ignore words less than N characters long

Description

bool pspell_config_ignore ( int dictionary_link, int n )

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker. Words less than n characters will be skipped.

Example 1. pspell_config_ignore()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error
?&#62;

Prev | Home | Next
pspell_config_dict_dir | Up | pspell_config_mode


pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_mode -- Change the mode number of suggestions returned

Description

bool pspell_config_mode ( int dictionary_link, int mode )

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Example 1. pspell_config_mode()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?&#62;

Prev | Home | Next
pspell_config_ignore | Up | pspell_config_personal


pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_personal -- Set a file that contains personal wordlist

Description

bool pspell_config_personal ( int dictionary_link, string file )

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Example 1. pspell_config_personal()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?&#62;

Prev | Home | Next
pspell_config_mode | Up | pspell_config_repl


pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_repl -- Set a file that contains replacement pairs

Description

bool pspell_config_repl ( int dictionary_link, string file )

pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Example 1. pspell_config_repl()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?&#62;

Prev | Home | Next
pspell_config_personal | Up | pspell_config_runtogether


pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_runtogether -- Consider run-together words as valid compounds

Description

bool pspell_config_runtogether ( int dictionary_link, bool flag )

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Example 1. pspell_config_runtogether()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?&#62;

Prev | Home | Next
pspell_config_repl | Up | pspell_config_save_repl


pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist

Description

bool pspell_config_save_repl ( int dictionary_link, bool flag )

pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Prev | Home | Next
pspell_config_runtogether | Up | pspell_new_config


pspell_new_config

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_config -- Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int config )

pspell_new_config() opens up a new dictionary with settings specified in a config, created with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

The config parameter is the one returned by pspell_config_create() when the config was created.

Example 1. pspell_new_config()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
?&#62;

Prev | Home | Next
pspell_config_save_repl | Up | pspell_new_personal


pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_personal -- Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]] )

pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Example 1. pspell_new_personal()

&#60;?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?&#62;

Prev | Home | Next
pspell_new_config | Up | pspell_new


pspell_new

(PHP 4 >= 4.0.2, PHP 5)

pspell_new -- Load a new dictionary

Description

int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]] )

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Example 1. pspell_new()

&#60;?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?&#62;

Prev | Home | Next
pspell_new_personal | Up | pspell_save_wordlist


pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5)

pspell_save_wordlist -- Save the personal wordlist to a file

Description

bool pspell_save_wordlist ( int dictionary_link )

pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Example 1. pspell_add_to_personal()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?&#62;

Prev | Home | Next
pspell_new | Up | pspell_store_replacement


pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5)

pspell_store_replacement -- Store a replacement pair for a word

Description

bool pspell_store_replacement ( int dictionary_link, string misspelled, string correct )

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Example 1. pspell_store_replacement()

&#60;?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?&#62;

Prev | Home | Next
pspell_save_wordlist | Up | pspell_suggest


pspell_suggest

(PHP 4 >= 4.0.2, PHP 5)

pspell_suggest -- Suggest spellings of a word

Description

array pspell_suggest ( int dictionary_link, string word )

pspell_suggest() returns an array of possible spellings for the given word.

Example 1. pspell_suggest() example

&#60;?php
$pspell_link = pspell_new("en");

if (!pspell_check($pspell_link, "testt")) {
    $suggestions = pspell_suggest($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion&#60;br /&#62;";
    }
}
?&#62;

Prev | Home | Next
pspell_store_replacement | Up | qtdom Functions


qtdom Functions

PHP Manual
Prev Next

CXXXI. qtdom 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.

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.

Requirements

You need the Qt-library >=2.2.0

Installation

Configure PHP --with-qtdom to use these functions.

Table of Contents
qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occurred
qdom_tree -- Creates a tree of an XML string

Prev | Home | Next
pspell_suggest | Up | qdom_error


qdom_error

(PHP 4 >= 4.0.5, PECL)

qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occurred

Description

string qdom_error ( void )

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.

Prev | Home | Next
qtdom Functions | Up | qdom_tree


qdom_tree

(PHP 4 >= 4.0.4, PECL)

qdom_tree -- Creates a tree of an XML string

Description

QDomDocument qdom_tree ( string doc )

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.

Prev | Home | Next
qdom_error | Up | Radius


Rar Functions

PHP Manual
Prev Next

CXXXIII. Rar Functions

Introduction

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by UnRar library and is directly prohibited by it's license.

More information about Rar and UnRar can be found at http://www.rarlabs.com/.

Requirements

No external libraries are needed to build this extension.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Installation

Rar is currently available through PECL http://pecl.php.net/package/rar.

Also you can use the PECL installer to install the Rar extension, using the following command: pecl -v install rar.

You can always download the tar.gz package and install Rar by hand:

Example 1. Rar installation

gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install

Windows users can download the extension dll php_rar.dll here: http://snaps.php.net/win32/PECL_STABLE/.

Resource Types

There is one resource used in Rar extension: a file descriptor returned by rar_open().

Predefined Constants

RAR_HOST_MSDOS (integer)

RAR_HOST_OS2 (integer)

RAR_HOST_WIN32 (integer)

RAR_HOST_UNIX (integer)

RAR_HOST_BEOS (integer)

Examples

Example 2. Rar extension overview example

&#60;?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entries = rar_list($rar_file);

foreach ($entries as $entry) {
    echo 'Filename: ' . $entry-&#62;getName() . "\n";
    echo 'Packed size: ' . $entry-&#62;getPackedSize() . "\n";
    echo 'Unpacked size: ' . $entry-&#62;getUnpackedSize() . "\n";

    $entry-&#62;extract('/dir/extract/to/');
}

rar_close($rar_file);

?&#62;

This example opens a Rar file archive and extracts each entry to the specified directory.

Table of Contents
rar_close -- Close Rar archive and free all resources
rar_entry_get -- Get entry object from the Rar archive
Rar::extract -- Extract entry from the archive
Rar::getAttr -- Get attributes of the entry
Rar::getCrc -- Get CRC of the entry
Rar::getFileTime -- Get entry last modification time
Rar::getHostOs -- Get entry host OS
Rar::getMethod -- Get pack method of the entry
Rar::getName -- Get name of the entry
Rar::getPackedSize -- Get packed size of the entry
Rar::getUnpackedSize -- Get unpacked size of the entry
Rar::getVersion -- Get version of the archiver used to add the entry
rar_list -- Get entries list from the Rar archive
rar_open -- Open Rar archive

Prev | Home | Next
radius_strerror | Up | rar_close


rar_close

(no version information, might be only in CVS)

rar_close -- Close Rar archive and free all resources

Description

bool rar_close ( resource rar_file )

Close Rar archive and free all allocated resources.

rar_close() returns FALSE on error.

Prev | Home | Next
Rar Functions | Up | rar_entry_get


rar_entry_get

(no version information, might be only in CVS)

rar_entry_get -- Get entry object from the Rar archive

Description

RarEntry rar_entry_get ( resource rar_file, string entry_name )

Get entry object from the Rar archive.

Example 1. Rar::() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

print_r($entry);

?&#62;

rar_get_entry() returns entry object or FALSE on error.

Prev | Home | Next
rar_close | Up | Rar::extract


Rar::extract

(no version information, might be only in CVS)

Rar::extract -- Extract entry from the archive

Description

bool Rar::extract ( string dir [, string filepath] )

Rar::extract() extracts entry's data to the dir. It will create new file in the specified dir with the name identical to the entry's name. If parameter filepath is specified instead dir, Rar::extract() will extract entry's data to the specified file.

Example 1. Rar::extract() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

$entry-&#62;extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry-&#62;extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?&#62;

Example 2. How to extract all files in archive:

&#60;?php

/* example by Erik Jenssen aka erix */

$filename = "foobar.rar";
$filepath = "/home/foo/bar/";

$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
    $entry = rar_entry_get($rar_file, $file);
    $entry-&#62;extract("."); // extract to the current dir
}
rar_close($rar_file);

?&#62;

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
rar_entry_get | Up | Rar::getAttr


Rar::getAttr

(no version information, might be only in CVS)

Rar::getAttr -- Get attributes of the entry

Description

int Rar::getAttr ( void )

Rar::getAttr() returns attributes of the archive entry.

Example 1. Rar::getAttr() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");

$host_os = $entry-&#62;getHostOs();
$attr = $entry-&#62;getAttr();

switch($host_os) {
    case RAR_HOST_MSDOS:
    case RAR_HOST_OS2:
    case RAR_HOST_WIN32:
    case RAR_HOST_MACOS:
        printf("%c%c%c%c%c%c\n",
                ($attr &#38; 0x08) ? 'V' : '.',
                ($attr &#38; 0x10) ? 'D' : '.',
                ($attr &#38; 0x01) ? 'R' : '.',
                ($attr &#38; 0x02) ? 'H' : '.',
                ($attr &#38; 0x04) ? 'S' : '.',
                ($attr &#38; 0x20) ? 'A' : '.');
        break;
    case RAR_HOST_UNIX:
    case RAR_HOST_BEOS:
        switch ($attr &#38; 0xF000)
        {
            case 0x4000:
                printf("d");
                break;
            case 0xA000:
                printf("l");
                break;
            default:
                printf("-");
                break;
        }
        printf("%c%c%c%c%c%c%c%c%c\n",
                ($attr &#38; 0x0100) ? 'r' : '-',
                ($attr &#38; 0x0080) ? 'w' : '-',
                ($attr &#38; 0x0040) ? (($attr &#38; 0x0800) ? 's':'x'):(($attr &#38; 0x0800) ? 'S':'-'),
                ($attr &#38; 0x0020) ? 'r' : '-',
                ($attr &#38; 0x0010) ? 'w' : '-',
                ($attr &#38; 0x0008) ? (($attr &#38; 0x0400) ? 's':'x'):(($attr &#38; 0x0400) ? 'S':'-'),
                ($attr &#38; 0x0004) ? 'r' : '-',
                ($attr &#38; 0x0002) ? 'w' : '-',
                ($attr &#38; 0x0001) ? 'x' : '-');
        break;
}

rar_close($rar_file);

?&#62;

Rar::getAttr() returns FALSE on error.

See also Rar::getHostOs().

Prev | Home | Next
Rar::extract | Up | Rar::getCrc


Rar::getCrc

(no version information, might be only in CVS)

Rar::getCrc -- Get CRC of the entry

Description

int Rar::getCrc ( void )

Rar::getCrc() returns CRC of the archive entry.

Example 1. Rar::getCrc() example

&#60;?php

?&#62;

Rar::getCrc() returns FALSE on error.

Prev | Home | Next
Rar::getAttr | Up | Rar::getFileTime


Rar::getFileTime

(no version information, might be only in CVS)

Rar::getFileTime -- Get entry last modification time

Description

string Rar::getFileTime ( void )

Rar::getFileTime() returns entry last modification time as string in format YYYY-MM-DD HH:II:SS.

Example 1. Rar::() example

&#60;?php

?&#62;

Rar::getFileTime() returns FALSE on error.

Prev | Home | Next
Rar::getCrc | Up | Rar::getHostOs


Rar::getHostOs

(no version information, might be only in CVS)

Rar::getHostOs -- Get entry host OS

Description

int Rar::getHostOs ( void )

Rar::getHostOs() return code of the host OS of the archive entry.

Example 1. Rar::getHostOs() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry-&#62;getHostOs()) {
    case RAR_HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RAR_HOST_OS2:
        echo "OS2\n";
        break;
    case RAR_HOST_WIN32:
        echo "Win32\n";
        break;
    case RAR_HOST_MACOS:
        echo "MacOS\n";
        break;
    case RAR_HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RAR_HOST_BEOS:
        echo "BeOS\n";
        break;
}

?&#62;

Rar::getHostOs() returns FALSE on error.

Prev | Home | Next
Rar::getFileTime | Up | Rar::getMethod


Rar::getMethod

(no version information, might be only in CVS)

Rar::getMethod -- Get pack method of the entry

Description

int Rar::getMethod ( void )

Rar::getMethod() returns number of the method used when adding current archive entry.

Example 1. Rar::getMethod() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Method number: " . $entry-&#62;getMethod();

?&#62;

Rar::getMethod() returns FALSE on error.

Prev | Home | Next
Rar::getHostOs | Up | Rar::getName


Rar::getName

(no version information, might be only in CVS)

Rar::getName -- Get name of the entry

Description

string Rar::getName ( void )

Rar::getName() returns full name of the archive entry.

Example 1. Rar::getName() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Entry name: " . $entry-&#62;getName();

?&#62;

Rar::getName() returns FALSE on error.

Prev | Home | Next
Rar::getMethod | Up | Rar::getPackedSize


Rar::getPackedSize

(no version information, might be only in CVS)

Rar::getPackedSize -- Get packed size of the entry

Description

int Rar::getPackedSize ( void )

Get packed size of the archive entry.

Example 1. Rar::() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Packed size of " . $entry-&#62;getName() . " = " . $entry-&#62;getPackedSize() . " bytes";

?&#62;

Rar::getPackedSize() returns FALSE on error.

Prev | Home | Next
Rar::getName | Up | Rar::getUnpackedSize


Rar::getUnpackedSize

(no version information, might be only in CVS)

Rar::getUnpackedSize -- Get unpacked size of the entry

Description

int Rar::getUnpackedSize ( void )

Get unpacked size of the archive entry.

Example 1. Rar::getUnpackedSize() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Unpacked size of " . $entry-&#62;getName() . " = " . $entry-&#62;getPackedSize() . " bytes";

?&#62;

Rar::getUnpackedSize() returns FALSE on error.

Prev | Home | Next
Rar::getPackedSize | Up | Rar::getVersion


Rar::getVersion

(no version information, might be only in CVS)

Rar::getVersion -- Get version of the archiver used to add the entry

Description

int Rar::getVersion ( void )

Get version of the archiver used to add the archive entry.

Example 1. Rar::getVersion() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Rar (WinRAR) version used: " . $entry-&#62;getVersion();

?&#62;

Rar::getVersion() returns FALSE on error.

Prev | Home | Next
Rar::getUnpackedSize | Up | rar_list


rar_list

(no version information, might be only in CVS)

rar_list -- Get entries list from the Rar archive

Description

array rar_list ( resource rar_file )

Get entries list from the Rar archive.

Example 1. Rar::() example

&#60;?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entries_list = rar_list($rar_file);

print_r($entries_list);

?&#62;

rar_list() returns array of entries or FALSE on error.

Prev | Home | Next
Rar::getVersion | Up | rar_open


rar_open

(no version information, might be only in CVS)

rar_open -- Open Rar archive

Description

resource rar_open ( string filename [, string password] )

Open specified Rar archive and return Rar file resource.

rar_open() returns Rar file resource or FALSE on error.

Prev | Home | Next
rar_list | Up | GNU Readline


GNU Readline

PHP Manual
Prev Next

CXXXIV. GNU Readline

Introduction

The readline functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts used from a command line.

Note: This extension is not available on Windows platforms.

Requirements

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from http://www.thrysoee.dk/editline/.

Installation

To use these functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].

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
readline_add_history -- Adds a line to the history
readline_callback_handler_install -- Initializes the readline callback interface and terminal, prints the prompt and returns immediately
readline_callback_handler_remove -- Removes a previously installed callback handler and restores terminal settings
readline_callback_read_char -- Reads a character and informs the readline callback interface when a line is received
readline_clear_history -- Clears the history
readline_completion_function -- Registers a completion function
readline_info -- Gets/sets various internal readline variables
readline_list_history -- Lists the history
readline_on_new_line -- Inform readline that the cursor has moved to a new line
readline_read_history -- Reads the history
readline_redisplay -- Redraws the display
readline_write_history -- Writes the history
readline -- Reads a line

Prev | Home | Next
rar_open | Up | readline_add_history


readline_add_history

(PHP 4, PHP 5)

readline_add_history -- Adds a line to the history

Description

bool readline_add_history ( string line )

This function adds a line to the command line history.

Parameters

line

The line to be added in the history.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
GNU Readline | Up | readline_callback_handler_install


readline_callback_handler_install

(PHP 5 >= 5.1.0RC1)

readline_callback_handler_install -- Initializes the readline callback interface and terminal, prints the prompt and returns immediately

Description

bool readline_callback_handler_install ( string prompt, callback callback )

Sets up a readline callback interface then prints prompt and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Parameters

prompt

The prompt message.

callback

The callback function takes one parameter; the user input returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Readline Callback Interface Example

&#60;?php
function rl_callback($ret)
{
    global $c, $prompting;

    echo "You entered: $ret\n";
    $c++;

    if ($c &#62; 10) {
        $prompting = false;
        readline_callback_handler_remove();
    } else {
        readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
    }
}

$c = 1;
$prompting = true;

readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');

while ($prompting) {
    $w = NULL;
    $e = NULL;
    $n = stream_select($r = array(STDIN), $w, $e, null);
    if ($n &#38;&#38; in_array(STDIN, $r)) {
        // read a character, will call the callback when a newline is entered
        readline_callback_read_char();
    }
}

echo "Prompting disabled. All done.\n";
?&#62;

See Also

readline_callback_handler_remove()
readline_callback_read_char()
stream_select()

Prev | Home | Next
readline_add_history | Up | readline_callback_handler_remove


readline_callback_handler_remove

(PHP 5 >= 5.1.0RC1)

readline_callback_handler_remove -- Removes a previously installed callback handler and restores terminal settings

Description

bool readline_callback_handler_remove ( void )

Removes a previously installed callback handler and restores terminal settings.

Return Values

Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.

Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

See Also

readline_callback_handler_install()
readline_callback_read_char()

Prev | Home | Next
readline_callback_handler_install | Up | readline_callback_read_char


readline_callback_read_char

(PHP 5 >= 5.1.0RC1)

readline_callback_read_char -- Reads a character and informs the readline callback interface when a line is received

Description

void readline_callback_read_char ( void )

Reads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.

Return Values

No value is returned.

Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

See Also

readline_callback_handler_install()
readline_callback_handler_remove()

Prev | Home | Next
readline_callback_handler_remove | Up | readline_clear_history


readline_clear_history

(PHP 4, PHP 5)

readline_clear_history -- Clears the history

Description

bool readline_clear_history ( void )

This function clears the entire command line history.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
readline_callback_read_char | Up | readline_completion_function


readline_completion_function

(PHP 4, PHP 5)

readline_completion_function -- Registers a completion function

Description

bool readline_completion_function ( callback function )

This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

Parameters

function

You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
readline_clear_history | Up | readline_info


readline_info

(PHP 4, PHP 5)

readline_info -- Gets/sets various internal readline variables

Description

mixed readline_info ( [string varname [, string newvalue]] )

Gets or sets various internal readline variables.

Parameters

varname

A variable name.

newvalue

If provided, this will be the new value of the setting.

Return Values

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one or two parameters, the old value is returned.

Prev | Home | Next
readline_completion_function | Up | readline_list_history


readline_list_history

(PHP 4, PHP 5)

readline_list_history -- Lists the history

Description

array readline_list_history ( void )

Gets the entire command line history.

Return Values

Returns an array of the entire command line history. The elements are indexed by integers starting at zero.

Prev | Home | Next
readline_info | Up | readline_on_new_line


readline_on_new_line

(PHP 5 >= 5.1.0RC1)

readline_on_new_line -- Inform readline that the cursor has moved to a new line

Description

void readline_on_new_line ( void )

Tells readline that the cursor has moved to a new line.

Return Values

No value is returned.

Prev | Home | Next
readline_list_history | Up | readline_read_history


readline_read_history

(PHP 4, PHP 5)

readline_read_history -- Reads the history

Description

bool readline_read_history ( [string filename] )

This function reads a command history from a file.

Parameters

filename

Path to the filename containing the command history.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
readline_on_new_line | Up | readline_redisplay


readline_redisplay

(PHP 5 >= 5.1.0RC1)

readline_redisplay -- Redraws the display

Description

void readline_redisplay ( void )

Redraws readline to redraw the display.

Return Values

No value is returned.

Prev | Home | Next
readline_read_history | Up | readline_write_history


readline_write_history

(PHP 4, PHP 5)

readline_write_history -- Writes the history

Description

bool readline_write_history ( [string filename] )

This function writes the command history to a file.

Parameters

filename

Path to the saved file.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
readline_redisplay | Up | readline


readline

(PHP 4, PHP 5)

readline -- Reads a line

Description

string readline ( [string prompt] )

Reads a single line from the user. You must add this line to the history yourself using readline_add_history().

Parameters

prompt

You may specify a string with which to prompt the user.

Return Values

Returns a single string from the user. The line returned has the ending newline removed.

Examples

Example 1. readline() Example

&#60;?php
//get 3 commands from user
for ($i=0; $i &#60; 3; $i++) {
        $line = readline("Command: ");
        readline_add_history($line);
}

//dump history
print_r(readline_list_history());

//dump variables
print_r(readline_info());
?&#62;

Prev | Home | Next
readline_write_history | Up | GNU Recode Functions


GNU Recode Functions

PHP Manual
Prev Next

CXXXV. GNU Recode Functions

Introduction

This module contains an interface to the GNU Recode library. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most RFC 1345 character sets are supported.

Note: This extension is not available on Windows platforms.

Requirements

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from http://directory.fsf.org/All_GNU_Packages/recode.html.

Warning

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.

Installation

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Warning

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proved to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they both share the same internal symbol.

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
recode_file -- Recode from file to file according to recode request
recode_string -- Recode a string according to a recode request
recode -- Alias of recode_string()

Prev | Home | Next
readline | Up | recode_file


recode_file

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

recode_file -- Recode from file to file according to recode request

Description

bool recode_file ( string request, resource input, resource output )

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request.

Parameters

request

The desired recode request type

input

A local file handle resource for the input

output

A local file handle resource for the output

Return Values

Returns FALSE, if unable to comply, TRUE otherwise.

Examples

Example 1. Basic recode_file() example

&#60;?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?&#62;

Notes

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

See Also

fopen()

Prev | Home | Next
GNU Recode Functions | Up | recode_string


recode_string

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

recode_string -- Recode a string according to a recode request

Description

string recode_string ( string request, string string )

Recode the string string according to the recode request request.

Parameters

request

The desired recode request type

string

The string to be recoded

Return Values

Returns the recoded string or FALSE, if unable to perform the recode request.

Examples

Example 1. Basic recode_string() example

&#60;?php
echo recode_string("us..flat", "The following character has a diacritical mark: &#38;aacute;");
?&#62;

Notes

A simple recode request may be "lat1..iso646-de".

See Also

The GNU Recode documentation of your installation for detailed instructions about recode requests.

Prev | Home | Next
recode_file | Up | recode


recode

(PHP 4, PHP 5)

recode -- Alias of recode_string()

Description

This function is an alias of: recode_string().

Prev | Home | Next
recode_string | Up | RPM Header Reading Functions


Regular Expression Functions (POSIX Extended)

PHP Manual
Prev Next

CXXIV. Regular Expression Functions (POSIX Extended)

Introduction

Tip: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

Warning

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

Requirements

No external libraries are needed to build this extension.

Installation

Warning

Do not change the TYPE unless you know what you are doing.

To enable regexp support configure PHP --with-regex[=TYPE]. TYPE can be one of system, apache, php. The default is to use php.

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

This extension has no constants defined.

Examples

Example 1. Regular Expression Examples

&#60;?php
// Returns true if "abc" is found anywhere in $string.
ereg("abc", $string);

// Returns true if "abc" is found at the beginning of $string.
ereg("^abc", $string);

// Returns true if "abc" is found at the end of $string.
ereg("abc$", $string);

// Returns true if client browser is Netscape 2, 3 or MSIE 3.
eregi("(ozilla.[23]|MSIE.3)", $HTTP_USER_AGENT);

// Places three space separated words into $regs[1], $regs[2] and $regs[3].
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string, $regs);

// Put a &#60;br /&#62; tag at the beginning of $string.
$string = ereg_replace("^", "&#60;br /&#62;", $string);

// Put a &#60;br /&#62; tag at the end of $string.
$string = ereg_replace("$", "&#60;br /&#62;", $string);

// Get rid of any newline characters in $string.
$string = ereg_replace("\n", "", $string);
?&#62;

See Also

For regular expressions in Perl-compatible syntax have a look at the PCRE functions. The simpler shell style wildcard pattern matching is provided by fnmatch().

Table of Contents
ereg_replace -- Replace regular expression
ereg -- Regular expression match
eregi_replace -- Replace regular expression case insensitive
eregi -- Case insensitive regular expression match
split -- Split string into array by regular expression
spliti -- Split string into array by regular expression case insensitive
sql_regcase -- Make regular expression for case insensitive match

Prev | Home | Next
posix_uname | Up | ereg_replace


ereg_replace

(PHP 3, PHP 4, PHP 5)

ereg_replace -- Replace regular expression

Description

string ereg_replace ( string pattern, string replacement, string string )

This function scans string for matches to pattern, then replaces the matched text with replacement.

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

If no matches are found in string, then string will be returned unchanged.

For example, the following code snippet prints "This was a test" three times:

Example 1. ereg_replace() example

&#60;?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?&#62;

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

Example 2. ereg_replace() example

&#60;?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?&#62;

Example 3. Replace URLs with links

&#60;?php
$text = ereg_replace("[[:alpha:]]+://[^&#60;&#62;[:space:]]+[[:alnum:]/]",
                     "&#60;a href=\"\\0\"&#62;\\0&#60;/a&#62;", $text);
?&#62;

Tip: preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

See also ereg(), eregi(),
eregi_replace(), str_replace(), and
preg_match().

Prev | Home | Next
Regular Expression Functions (POSIX Extended) | Up | ereg


ereg

(PHP 3, PHP 4, PHP 5)

ereg -- Regular expression match

Description

int ereg ( string pattern, string string [, array &regs] )

Note: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Note: Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred. If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

Example 1. ereg() example

&#60;?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Invalid date format: $date";
}
?&#62;

See also eregi(), ereg_replace(),
eregi_replace(), preg_match(),
strpos(), and strstr().

Prev | Home | Next
ereg_replace | Up | eregi_replace


eregi_replace

(PHP 3, PHP 4, PHP 5)

eregi_replace -- Replace regular expression case insensitive

Description

string eregi_replace ( string pattern, string replacement, string string )

This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

Example 1. Highlight search results

&#60;?php
$pattern = '(&#62;[^&#60;]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1&#60;span class="search"&#62;\\2&#60;/span&#62;';
$body = eregi_replace($pattern, $replacement, $body);
?&#62;

See also ereg(), eregi(), and ereg_replace().

Prev | Home | Next
ereg | Up | eregi


eregi

(PHP 3, PHP 4, PHP 5)

eregi -- Case insensitive regular expression match

Description

int eregi ( string pattern, string string [, array &regs] )

This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.

Example 1. eregi() example

&#60;?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?&#62;

See also ereg(), ereg_replace(),
eregi_replace(), stripos(), and
stristr().

Prev | Home | Next
eregi_replace | Up | split


split

(PHP 3, PHP 4, PHP 5)

split -- Split string into array by regular expression

Description

array split ( string pattern, string string [, int limit] )

Tip: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.

To split off the first four fields from a line from /etc/passwd:

Example 1. split() example

&#60;?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?&#62;

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty.

To parse a date which may be delimited with slashes, dots, or hyphens:

Example 2. split() example

&#60;?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year&#60;br /&#62;\n";
?&#62;

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split() or str_split().

Please note that pattern is a regular expression. If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

See also: preg_split(), spliti(),
str_split(),
explode(), implode(),
chunk_split(), and wordwrap().

Prev | Home | Next
eregi | Up | spliti


spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti -- Split string into array by regular expression case insensitive

Description

array spliti ( string pattern, string string [, int limit] )

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

This example splits a string using 'a' as the separator :

Example 1. spliti() example

&#60;?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?&#62;

The above example will output:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

See also preg_split(), split(), explode(), and implode().

Prev | Home | Next
split | Up | sql_regcase


sql_regcase

(PHP 3, PHP 4, PHP 5)

sql_regcase -- Make regular expression for case insensitive match

Description

string sql_regcase ( string string )

Returns a valid regular expression which will match string, ignoring case. This expression is string with each alphabetic character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form. Other characters remain unchanged.

Example 1. sql_regcase() example

&#60;?php
echo sql_regcase("Foo - bar.");
?&#62;

The above example will output:

[Ff][Oo][Oo] - [Bb][Aa][Rr].

This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.

Prev | Home | Next
spliti | Up | PostgreSQL Functions


Semaphore, Shared Memory and IPC Functions

PHP Manual
Prev Next

CXLIV. Semaphore, Shared Memory and IPC Functions

Introduction

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

Table 1. Limits of Shared Memory by the Unix OS

SHMMAX | max size of shared memory, normally 131072 bytes
SHMMIN | minimum size of shared memory, normally 1 byte
SHMMNI | max amount of shared memory segments on a system, normally 100
SHMSEG | max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using Unix domain sockets.

Note: This extension is not available on Windows platforms.

Requirements

No external libraries are needed to build this extension.

Installation

Support for this functions are not enabled by default. To enable System V semaphore support compile PHP with the option --enable-sysvsem. To enable the System V shared memory support compile PHP with the option --enable-sysvshm. To enable the System V messages support compile PHP with the option --enable-sysvmsg.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 2. Semaphore Configuration Options

Name | Default | Changeable | Changelog
sysvmsg.value | "42" | PHP_INI_ALL |
sysvmsg.string | "foobar" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

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 3. System V message constants

Constant | Type | Changelog
MSG_IPC_NOWAIT | integer |
MSG_EAGAIN | integer | As of 5.2.0
MSG_ENOMSG | integer | As of 5.2.0
MSG_NOERROR | integer |
MSG_EXCEPT | integer |

Table of Contents
ftok -- Convert a pathname and a project identifier to a System V IPC key
msg_get_queue -- Create or attach to a message queue
msg_receive -- Receive a message from a message queue
msg_remove_queue -- Destroy a message queue
msg_send -- Send a message to a message queue
msg_set_queue -- Set information in the message queue data structure
msg_stat_queue -- Returns information from the message queue data structure
sem_acquire -- Acquire a semaphore
sem_get -- Get a semaphore id
sem_release -- Release a semaphore
sem_remove -- Remove a semaphore
shm_attach -- Creates or open a shared memory segment
shm_detach -- Disconnects from shared memory segment
shm_get_var -- Returns a variable from shared memory
shm_put_var -- Inserts or updates a variable in shared memory
shm_remove_var -- Removes a variable from shared memory
shm_remove -- Removes shared memory from Unix systems

Prev | Home | Next
SDO_DAS_Relational::executeQuery | Up | ftok


ftok

(PHP 4 >= 4.2.0, PHP 5)

ftok -- Convert a pathname and a project identifier to a System V IPC key

Description

int ftok ( string pathname, string proj )

The function converts the pathname of an existing accessible file and a project identifier (proj) into a integer for use with for example shmop_open() and other System V IPC keys. The proj parameter must be a one character string.

On success the return value will be the created key value, otherwise -1 is returned.

See also shmop_open() and sem_get().

Prev | Home | Next
Semaphore, Shared Memory and IPC Functions | Up | msg_get_queue


msg_get_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_get_queue -- Create or attach to a message queue

Description

resource msg_get_queue ( int key [, int perms] )

msg_get_queue() returns an id that can be used to access the System V message queue with the given key. The first call creates the message queue with the optional perms (default: 0666). A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue. If the message queue already exists, the perms will be ignored.

See also msg_remove_queue(),
msg_receive(), msg_send(),
msg_stat_queue() and
msg_set_queue().

Prev | Home | Next
ftok | Up | msg_receive


msg_receive

(PHP 4 >= 4.3.0, PHP 5)

msg_receive -- Receive a message from a message queue

Description

bool msg_receive ( resource queue, int desiredmsgtype, int &msgtype, int maxsize, mixed &message [, bool unserialize [, int flags [, int &errorcode]]] )

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype. The type of the message that was received will be stored in msgtype. The maximum size of message to be accepted is specified by the maxsize; if the message in the queue is larger than this size the function will fail (unless you set flags as described below). The received message will be stored in message, unless there were errors receiving the message, in which case the optional errorcode will be set to the value of the system errno variable to help you identify the cause.

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with the lowest type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

unserialize defaults to TRUE; if it is set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source. If unserialize is FALSE, the message will be returned as a binary-safe string.

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Table 1. Flag values for msg_receive

MSG_IPC_NOWAIT | If there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to MSG_ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype.
MSG_NOERROR | If the message is longer than maxsize, setting this flag will truncate the message to maxsize and will not signal an error.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

msg_receive() returns TRUE on success or FALSE on failure. If the function fails, the optional errorcode will be set to the value of the system errno variable.

See also msg_remove_queue(),
msg_send(),
msg_stat_queue() and
msg_set_queue().

Prev | Home | Next
msg_get_queue | Up | msg_remove_queue


msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_remove_queue -- Destroy a message queue

Description

bool msg_remove_queue ( resource queue )

msg_remove_queue() destroys the message queue specified by the queue. Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

See also msg_get_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

Prev | Home | Next
msg_receive | Up | msg_send


msg_send

(PHP 4 >= 4.3.0, PHP 5)

msg_send -- Send a message to a message queue

Description

bool msg_send ( resource queue, int msgtype, mixed message [, bool serialize [, bool blocking [, int &errorcode]]] )

msg_send() sends a message of type msgtype (which MUST be greater than 0) to the message queue specified by queue.

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

See also msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

Prev | Home | Next
msg_remove_queue | Up | msg_set_queue


msg_set_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_set_queue -- Set information in the message queue data structure

Description

bool msg_set_queue ( resource queue, array data )

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure. You specify the values you require by setting the value of the keys that you require in the data array.

Changing the data structure will require that PHP be running as the same user that created the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

See also msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_get_queue().

Prev | Home | Next
msg_send | Up | msg_stat_queue


msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_stat_queue -- Returns information from the message queue data structure

Description

array msg_stat_queue ( resource queue )

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue. This is useful, for example, to determine which process sent the message that was just received.

The return value is an array whose keys and values have the following meanings:

Table 1. Array structure for msg_stat_queue

msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The number of bytes of space currently available in the queue to hold sent messages until they are received.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

See also msg_remove_queue(),
msg_receive(),
msg_get_queue() and
msg_set_queue().

Prev | Home | Next
msg_set_queue | Up | sem_acquire


sem_acquire

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_acquire -- Acquire a semaphore

Description

bool sem_acquire ( resource sem_identifier )

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its maximum number of semaphore to be exceeded. sem_identifier is a semaphore resource, obtained from sem_get().

Returns TRUE on success or FALSE on failure.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

See also sem_get(), and sem_release().

Prev | Home | Next
msg_stat_queue | Up | sem_get


sem_get

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_get -- Get a semaphore id

Description

resource sem_get ( int key [, int max_acquire [, int perm [, int auto_release]]] )

sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

Optional parameter auto_release specifies if the semaphore should be automatically released on request shutdown. It is available since PHP 4.3.0.

Returns a positive semaphore identifier on success, or FALSE on error.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

See also sem_acquire(), sem_release(), and ftok().

Prev | Home | Next
sem_acquire | Up | sem_release


sem_release

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_release -- Release a semaphore

Description

bool sem_release ( resource sem_identifier )

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

Returns TRUE on success or FALSE on failure.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

See also sem_get() and sem_acquire().

Prev | Home | Next
sem_get | Up | sem_remove


sem_remove

(PHP 4 >= 4.1.0, PHP 5)

sem_remove -- Remove a semaphore

Description

bool sem_remove ( resource sem_identifier )

sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(), otherwise generates a warning.

Returns TRUE on success or FALSE on failure.

After removing the semaphore, it is no more accessible.

See also sem_get(),
sem_release() and
sem_acquire().

Prev | Home | Next
sem_release | Up | shm_attach


shm_attach

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_attach -- Creates or open a shared memory segment

Description

int shm_attach ( int key [, int memsize [, int perm]] )

shm_attach() returns an id that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with memsize (default: sysvshm.init_mem in the php.ini, otherwise 10000 bytes) and the optional perm-bits perm (default: 0666).

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. Memsize and perm will be ignored.

See also ftok(), and shm_detach().

Prev | Home | Next
sem_remove | Up | shm_detach


shm_detach

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_detach -- Disconnects from shared memory segment

Description

bool shm_detach ( int shm_identifier )

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

shm_detach() always returns TRUE.

See also shm_attach(), shm_remove(), and shm_remove_var().

Prev | Home | Next
shm_attach | Up | shm_get_var


shm_get_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_get_var -- Returns a variable from shared memory

Description

mixed shm_get_var ( int shm_identifier, int variable_key )

shm_get_var() returns the variable with a given variable_key, in the shared memory segment identified by shm_identifier. shm_identifier was obtained from shm_attach(). The variable is still present in the shared memory.

Prev | Home | Next
shm_detach | Up | shm_put_var


shm_put_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_put_var -- Inserts or updates a variable in shared memory

Description

bool shm_put_var ( int shm_identifier, int variable_key, mixed variable )

shm_put_var() inserts or updates the variable with the given variable_key. All variable-types are supported.

Returns TRUE on success or FALSE on failure.

Warnings (E_WARNING level) will be issued if shm_identifier is not a valid SysV shared memory index or if there was not enough shared memory remaining to complete your request.

Prev | Home | Next
shm_get_var | Up | shm_remove_var


shm_remove_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_remove_var -- Removes a variable from shared memory

Description

bool shm_remove_var ( int shm_identifier, int variable_key )

Removes a variable with a given variable_key and frees the occupied memory.

See also shm_remove().

Prev | Home | Next
shm_put_var | Up | shm_remove


shm_remove

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_remove -- Removes shared memory from Unix systems

Description

bool shm_remove ( int shm_identifier )

shm_remove() removes the shared memory shm_identifier. All data will be destroyed.

See also shm_remove_var().

Prev | Home | Next
shm_remove_var | Up | SESAM Database Functions


SESAM Database Functions

PHP Manual
Prev Next

CXLV. SESAM Database Functions

Introduction

SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.

In numerous productive BS2000 installations, SESAM/SQL-Server has proven

  • the ease of use of Java-, Web- and client/server connectivity,

  • the capability to work with an availability of more than 99.99%,

  • the ability to manage tens and even hundreds of thousands of users.

There is a PHP 3 SESAM interface available which allows database operations via PHP-scripts.

Note: Access to SESAM is only available with the latest CVS-Version of PHP 3. PHP 4 does not support the SESAM database.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

sesam_oml string

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

sesam_configfile string

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

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

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

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

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

Configuration notes

There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.

Table 1. SESAM Configuration directives

Directive Meaning
php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions.

Example:

php3_sesam_oml $.SYSLNK.SESAM-SQL.030

php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions.

Example:

php3_sesam_configfile $SESAM.SESAM.CONF.AW

It will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

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

Example:

php3_sesam_messagecatalog $.SYSMES.SESAM-SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:

  • starting the SESAM database handler (DBH), and

  • connecting the databases with the SESAM database handler

To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.

In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.

The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.

Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).

Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.

Runtime considerations

Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.

When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.

Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.

Cursor Types

The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:

Table 2. Scrolled Cursor Post-Processing

Scroll Type | Action
SESAM_SEEK_NEXT | none
SESAM_SEEK_PRIOR | none
SESAM_SEEK_FIRST | set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST | set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTE | Auto-Increment internal offset value
SESAM_SEEK_RELATIVE | none. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)

Porting note

Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective PHP sesam functions include a note that the index is zero based.

Security concerns

When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to PHP scripts which must administer the database by using password control and/or SSL security.

Migration from other SQL databases

No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:

  • Vendor specific data types

    Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).

  • Keywords as SQL identifiers

    In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

  • Display length in data types

    SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

  • SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes

    Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.

  • int ... DEFAULT '0000'

    Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );

  • $count = xxxx_num_rows();

    Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.

  • DROP TABLE thename;

    In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.

Notes on the use of various SQL types

SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.

At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:

Table 3. SQL to PHP Type Conversions

SQL Type | PHP Type
SMALLINT, INTEGER | integer
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE | float
DATE, TIME, TIMESTAMP | string
VARCHAR, CHARACTER | string
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).

Support of SESAM's "multiple fields" feature

The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:

Example 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (
    pkey CHAR(20) PRIMARY KEY,
    multi(3) CHAR(12)
)
and can be filled in using:

Example 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )
    VALUES ('Second', <'first_val', 'second_val'>)
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).

When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.

See Also

For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.

Table of Contents
sesam_affected_rows -- Get number of rows affected by an immediate query
sesam_commit -- Commit pending updates to the SESAM database
sesam_connect -- Open SESAM database connection
sesam_diagnostic -- Return status information for last SESAM call
sesam_disconnect -- Detach from SESAM connection
sesam_errormsg -- Returns error message of last SESAM call
sesam_execimm -- Execute an "immediate" SQL-statement
sesam_fetch_array -- Fetch one row as an associative array
sesam_fetch_result -- Return all or part of a query result
sesam_fetch_row -- Fetch one row as an array
sesam_field_array -- Return meta information about individual columns in a result
sesam_field_name -- Return one column name of the result set
sesam_free_result -- Releases resources for the query
sesam_num_fields -- Return the number of fields/columns in a result set
sesam_query -- Perform a SESAM SQL query and prepare the result
sesam_rollback -- Discard any pending updates to the SESAM database
sesam_seek_row -- Set scrollable cursor mode for subsequent fetches
sesam_settransaction -- Set SESAM transaction parameters

Prev | Home | Next
shm_remove | Up | sesam_affected_rows


sesam_affected_rows

(PHP 3 CVS only)

sesam_affected_rows -- Get number of rows affected by an immediate query

Description

int sesam_affected_rows ( string result_id )

Gets the number of rows affected by an immediate query.

The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries.

Parameters

result_id

A valid result id returned by sesam_query().

Return Values

Returns the number of rows affected by a query associated with result_id.

Examples

Example 1. sesam_affected_rows() example

&#60;?php
$result = sesam_execimm("DELETE FROM PHONE WHERE LASTNAME = '" . strtoupper($name) . "'");
if (!$result) {
    /* ... error ... */
}
echo sesam_affected_rows($result).
    " entries with last name " . $name . " deleted.\n";
?&#62;

See Also

sesam_query()
sesam_execimm()

Prev | Home | Next
SESAM Database Functions | Up | sesam_commit


sesam_commit

(PHP 3 CVS only)

sesam_commit -- Commit pending updates to the SESAM database

Description

bool sesam_commit ( void )

Commits any pending updates to the database.

Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Committing an update to the SESAM database

&#60;?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (!sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', &#60;0, 8, 15&#62;)"))
        die("insert failed");
    if (!sesam_commit())
        die("commit failed");
}
?&#62;

See Also

sesam_rollback()

Prev | Home | Next
sesam_affected_rows | Up | sesam_connect


sesam_connect

(PHP 3 CVS only)

sesam_connect -- Open SESAM database connection

Description

bool sesam_connect ( string catalog, string schema, string user )

Establishes a connection to a SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.

Parameters

catalog

When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)

schema

The schema references the desired database schema (see SESAM handbook).

user

The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Connect to a SESAM database

&#60;?php
if (!sesam_connect ("mycatalog", "myschema", "otto")) {
    die("Unable to connect to SESAM");
}
?&#62;

See Also

sesam_disconnect()

Prev | Home | Next
sesam_commit | Up | sesam_diagnostic


sesam_diagnostic

(PHP 3 CVS only)

sesam_diagnostic -- Return status information for last SESAM call

Description

array sesam_diagnostic ( void )

Returns status information for last SESAM call.

Return Values

Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:

Table 1. Status information returned by sesam_diagnostic()

Element | Contents
$array["sqlstate"] | 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE)
$array["rowcount"] | number of affected rows in last update/insert/delete (set after "immediate" statements only)
$array["errmsg"] | "human readable" error message string (set after errors only)
$array["errcol"] | error column number of previous error (0-based; or -1 if undefined. Set after errors only)
$array["errlin"] | error line number of previous error (0-based; or -1 if undefined. Set after errors only)

Examples

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:

Example 1. Displaying SESAM error messages with error position

&#60;?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode($exec_str)
{
    $err = Sesam_Diagnostic();
    $colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
    if ($err["errlin"] == -1)
        --$colspan;
    if ($err["errcol"] == -1)
        --$colspan;
    if ($err["rowcount"] == 0)
        --$colspan;
    echo "&#60;table border=\"1\"&#62;\n";
    echo "&#60;tr&#62;&#60;th colspan=\"" . $colspan . "\"&#62;&#60;span class=\"spanred\"&#62;ERROR:&#60;/span&#62; ".
         htmlspecialchars($err["errmsg"]) . "&#60;/th&#62;&#60;/tr&#62;\n";
    if ($err["errcol"] &#62;= 0) {
        echo "&#60;tr&#62;&#60;td colspan=\"" . $colspan . "\"&#62;&#60;pre&#62;\n";
        $errstmt = $exec_str . "\n";
        for ($lin=0; $errstmt != ""; ++$lin) {
            if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
                if (!($i = strchr($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                if ($line != "\n")
                    echo htmlspecialchars($line);
            } else {
                if (! ($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                for ($col=0; $col &#60; $err["errcol"]; ++$col) {
                    echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "&#60;span class=\"spanred\"&#62;\\&#60;/span&#62;\n";
                echo "&#60;span class=\"normal\"&#62;" . htmlspecialchars($line) . "&#60;/span&#62;";
                for ($col=0; $col &#60; $err["errcol"]; ++$col) {
                    echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "&#60;span class=\"spanred\"&#62;/&#60;/span&#62;\n";
            }
        }
        echo "&#60;/pre&#62;&#60;/td&#62;&#60;/tr&#62;\n";
    }
    echo "&#60;tr&#62;\n";
    echo " &#60;td&#62;sqlstate=" . $err["sqlstate"] . "&#60;/td&#62;\n";
    if ($err["errlin"] != -1)
        echo " &#60;td&#62;errlin=" . $err["errlin"] . "&#60;/td&#62;\n";
    if ($err["errcol"] != -1)
        echo " &#60;td&#62;errcol=" . $err["errcol"] . "&#60;/td&#62;\n";
    if ($err["rowcount"] != 0)
         echo " &#60;td&#62;rowcount=" . $err["rowcount"] . "&#60;/td&#62;\n";
    echo "&#60;/tr&#62;\n";
    echo "&#60;/table&#62;\n";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))
  die ("cannot connect");

$stmt = "SELECT * FROM phone\n" .
        " WHERE@ LASTNAME='KRAEMER'\n" .
        " ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
    PrintReturncode ($stmt);
?&#62;

See Also

sesam_errormsg()

Prev | Home | Next
sesam_connect | Up | sesam_disconnect


sesam_disconnect

(PHP 3 CVS only)

sesam_disconnect -- Detach from SESAM connection

Description

bool sesam_disconnect ( void )

Closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).

Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.

sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.

Examples

Always returns TRUE.

Examples

Example 1. Closing a SESAM connection

&#60;?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    /* ... some queries and stuff ... */
    sesam_disconnect();
}
?&#62;

See Also

sesam_connect()

Prev | Home | Next
sesam_diagnostic | Up | sesam_errormsg


sesam_errormsg

(PHP 3 CVS only)

sesam_errormsg -- Returns error message of last SESAM call

Description

string sesam_errormsg ( void )

Gets the SESAM error message associated with the most recent SESAM error.

Return Values

Returns the SESAM error message associated with the most recent SESAM error. An empty string means no errors.

Examples

Example 1. sesam_errormsg() example

&#60;?php
if (!sesam_execimm($stmt)) {
  echo sesam_errormsg() . "&#60;br /&#62;\n";
}
?&#62;

See Also

sesam_diagnostic()

Prev | Home | Next
sesam_disconnect | Up | sesam_execimm


sesam_execimm

(PHP 3 CVS only)

sesam_execimm -- Execute an "immediate" SQL-statement

Description

string sesam_execimm ( string query )

Executes an "immediate" statement.

Sets the affected_rows value for retrieval by the sesam_affected_rows() function.

Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".

Parameters

query

An "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm().

Return Values

Returns a SESAM result identifier on success, or FALSE on error.

The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.

Examples

Example 1. sesam_execimm() Example

&#60;?php
$stmt = "INSERT INTO mytable VALUES ('one', 'two')";
$result = sesam_execimm($stmt);
$err = sesam_diagnostic();
echo "sqlstate = " . $err["sqlstate"] . "\n".
       "Affected rows = " . $err["rowcount"] . " == " .
       sesam_affected_rows($result) . "\n";
?&#62;

See Also

sesam_query()
sesam_affected_rows()

Prev | Home | Next
sesam_errormsg | Up | sesam_fetch_array


sesam_fetch_array

(PHP 3 CVS only)

sesam_fetch_array -- Fetch one row as an associative array

Description

array sesam_fetch_array ( string result_id [, int whence [, int offset]] )

sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.

sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.

Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:

CREATE TABLE ... ( ... MULTI(3) INT )

the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.

Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Parameters

result_id

A valid result id returned by sesam_query().

whence

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

Table 1. Valid values for "whence" parameter

Value | Constant | Meaning
0 | SESAM_SEEK_NEXT | read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1 | SESAM_SEEK_PRIOR | read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2 | SESAM_SEEK_FIRST | rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 | SESAM_SEEK_LAST | seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 | SESAM_SEEK_ABSOLUTE | seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5 | SESAM_SEEK_RELATIVE | seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset

Only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example 1. SESAM fetch array

&#60;?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table:
echo "&#60;table border=\"1\"&#62;\n";
while (($row = sesam_fetch_array($result)) &#38;&#38; count($row) &#62; 0) {
    echo "&#60;tr&#62;\n";
    echo "&#60;td&#62;" . htmlspecialchars($row["firstname"]) . "&#60;/td&#62;\n";
    echo "&#60;td&#62;" . htmlspecialchars($row["lastname"]) . "&#60;/td&#62;\n";
    echo "&#60;td&#62;" . htmlspecialchars($row["phoneno"]) . "&#60;/td&#62;\n";
    echo "&#60;/tr&#62;\n";
}
echo "&#60;/table&#62;\n";
sesam_free_result($result);
?&#62;

See Also

sesam_fetch_row()

Prev | Home | Next
sesam_execimm | Up | sesam_fetch_result


sesam_fetch_result

(PHP 3 CVS only)

sesam_fetch_result -- Return all or part of a query result

Description

mixed sesam_fetch_result ( string result_id [, int max_rows] )

Fetches a result, optionally limited to max_rows.

Parameters

result_id

A valid result id returned by sesam_query().

max_rows

Note that the amount of memory used up by a large query may be gigantic. Use the max_rows parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result will not use up all available memory.

Return Values

Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.

Table 1. Mixed result set returned by sesam_fetch_result()

Array Element | Contents
int $arr["count"] | number of columns in result set (or zero if this was an "immediate" query)
int $arr["rows"] | number of rows in result set (between zero and max_rows)
bool $arr["truncated"] | TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries.
mixed $arr[col][row] | result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

See Also

sesam_fetch_array()
sesam_fetch_row()
sesam_query()

Prev | Home | Next
sesam_fetch_array | Up | sesam_fetch_row


sesam_fetch_row

(PHP 3 CVS only)

sesam_fetch_row -- Fetch one row as an array

Description

array sesam_fetch_row ( string result_id [, int whence [, int offset]] )

Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().

Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Parameters

result_id

A valid result id returned by sesam_query().

whence

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

Table 1. Valid values for "whence" parameter

Value | Constant | Meaning
0 | SESAM_SEEK_NEXT | read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1 | SESAM_SEEK_PRIOR | read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2 | SESAM_SEEK_FIRST | rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 | SESAM_SEEK_LAST | seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 | SESAM_SEEK_ABSOLUTE | seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5 | SESAM_SEEK_RELATIVE | seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset

Only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example 1. SESAM fetch rows

&#60;?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n" .
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table in backward order
echo "&#60;table border=\"1\"&#62;\n";
$row = sesam_fetch_row($result, SESAM_SEEK_LAST);
while (is_array($row)) {
    echo "&#60;tr&#62;\n";
    for ($col = 0; $col &#60; $row["count"]; ++$col) {
        echo "&#60;td&#62;" . htmlspecialchars($row[$col]) . "&#60;/td&#62;\n";
    }
    echo "&#60;/tr&#62;\n";
    // use implied SESAM_SEEK_PRIOR
    $row = sesam_fetch_row($result);
}
echo "&#60;/table&#62;\n";
sesam_free_result($result);
?&#62;

See Also

sesam_fetch_array()
sesam_fetch_result()

Prev | Home | Next
sesam_fetch_result | Up | sesam_field_array


sesam_field_array

(PHP 3 CVS only)

sesam_field_array -- Return meta information about individual columns in a result

Description

array sesam_field_array ( string result_id )

Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.

Parameters

result_id

A valid result id returned by sesam_query().

Return Values

Table 1. Mixed result set returned by sesam_field_array()

Array Element | Contents
int $arr["count"] | Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns.
string $arr[col]["name"] | column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name.
string $arr[col]["count"] | The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute.
string $arr[col]["type"] PHP variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • integer

  • float

  • string

depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same PHP type.
string $arr[col]["sqltype"] SQL variable type of the column data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • "CHARACTER"

  • "VARCHAR"

  • "NUMERIC"

  • "DECIMAL"

  • "INTEGER"

  • "SMALLINT"

  • "FLOAT"

  • "REAL"

  • "DOUBLE"

  • "DATE"

  • "TIME"

  • "TIMESTAMP"

describing the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same SQL type.
string $arr[col]["length"] | The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute.
string $arr[col]["precision"] | The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute.
string $arr[col]["scale"] | The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute.

See Also

sesam_query()

Prev | Home | Next
sesam_fetch_row | Up | sesam_field_name


sesam_field_name

(PHP 3 CVS only)

sesam_field_name -- Return one column name of the result set

Description

int sesam_field_name ( string result_id, int index )

Gets the field name.

Parameters

result_id

A valid result id returned by sesam_query().

index

The column index is zero-based, not one-based as in SESAM.

Return Values

Returns the name of a field in the result set, or FALSE on error.

For "immediate" queries, or for dynamic columns, an empty string is returned.

See Also

sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".

Prev | Home | Next
sesam_field_array | Up | sesam_free_result


sesam_free_result

(PHP 3 CVS only)

sesam_free_result -- Releases resources for the query

Description

bool sesam_free_result ( string result_id )

Releases resources for the query.

Parameters

result_id

A valid result id returned by sesam_query().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
sesam_field_name | Up | sesam_num_fields


sesam_num_fields

(PHP 3 CVS only)

sesam_num_fields -- Return the number of fields/columns in a result set

Description

int sesam_num_fields ( string result_id )

After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result.

For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.

Parameters

result_id

A valid result id returned by sesam_query().

Return Values

Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.

See Also

sesam_query()
sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.

Prev | Home | Next
sesam_free_result | Up | sesam_query


sesam_query

(PHP 3 CVS only)

sesam_query -- Perform a SESAM SQL query and prepare the result

Description

string sesam_query ( string query [, bool scrollable] )

sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result).

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().

For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.

Parameters

query

The query statement.

scrollable

For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.

Return Values

Returns a SESAM "result identifier" on success, or FALSE on error. This result id is used by the other functions.

Examples

Example 1. Show all rows of the "phone" table as a HTML table

&#60;?php
if (!sesam_connect("phonedb", "demo", "otto"))
    die("cannot connect");
$result = sesam_query("select * from phone");
if (!$result) {
    $err = sesam_diagnostic();
    die ($err["errmsg"]);
}
echo "&#60;table border&#62;\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array($result)) {
    echo "&#60;tr&#62;&#60;th colspan=" . $cols["count"] . "&#62;Result:&#60;/th&#62;&#60;/tr&#62;\n";
    echo "&#60;tr&#62;\n";
    for ($col = 0; $col &#60; $cols["count"]; ++$col) {
        $colattr = $cols[$col];
        /* Span the table head over SESAM's "Multiple Fields": */
        if ($colattr["count"] &#62; 1) {
            echo "&#60;th colspan=\"" . $colattr["count"] . "\"&#62;" . $colattr["name"] .
                "(1.." . $colattr["count"] . ")&#60;/th&#62;\n";
            $col += $colattr["count"] - 1;
        } else
            echo "&#60;th&#62;" . $colattr["name"] . "&#60;/th&#62;\n";
    }
    echo "&#60;/tr&#62;\n";
}

do {
    // Fetch the result in chunks of 100 rows max.
    $ok = sesam_fetch_result($result, 100);
    for ($row=0; $row &#60; $ok["rows"]; ++$row) {
        echo " &#60;tr&#62;\n";
        for ($col = 0; $col &#60; $ok["cols"]; ++$col) {
            if (isset($ok[$col][$row])) {
                echo "&#60;td&#62;" . $ok[$col][$row] . "&#60;/td&#62;\n";
            } else {
                echo "&#60;td&#62;-empty-&#60;/td&#62;\n";
            }
        }
        echo "&#60;/tr&#62;\n";
    }
} while ($ok["truncated"]); // while there may be more data

echo "&#60;/table&#62;\n";
// free result id
sesam_free_result($result);
?&#62;

See Also

sesam_fetch_row()
sesam_fetch_result()

Prev | Home | Next
sesam_num_fields | Up | sesam_rollback


sesam_rollback

(PHP 3 CVS only)

sesam_rollback -- Discard any pending updates to the SESAM database

Description

bool sesam_rollback ( void )

sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.

At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Discarding an update to the SESAM database

&#60;?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', &#60;0, 8, 15&#62;)")
        &#38;&#38; sesam_execimm ("INSERT INTO othertable VALUES (*, 'Another Test', 1)")) {
        sesam_commit();
    } else {
        sesam_rollback();
    }
}
?&#62;

See Also

sesam_commit()

Prev | Home | Next
sesam_query | Up | sesam_seek_row


sesam_seek_row

(PHP 3 CVS only)

sesam_seek_row -- Set scrollable cursor mode for subsequent fetches

Description

bool sesam_seek_row ( string result_id, int whence [, int offset] )

Sets the scrollable cursor mode for subsequent fetches.

Parameters

result_id

result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).

whence

whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:

Table 1. Valid values for whence

Value | Constant | Meaning
0 | SESAM_SEEK_NEXT | read sequentially
1 | SESAM_SEEK_PRIOR | read sequentially backwards
2 | SESAM_SEEK_FIRST | fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 | SESAM_SEEK_LAST | fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 | SESAM_SEEK_ABSOLUTE | fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented)
5 | SESAM_SEEK_RELATIVE | fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches).

offset

An optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
sesam_rollback | Up | sesam_settransaction


sesam_settransaction

(PHP 3 CVS only)

sesam_settransaction -- Set SESAM transaction parameters

Description

bool sesam_settransaction ( int isolation_level, int read_only )

Overrides the default values for the isolation level and read-only transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only. See the SESAM handbook for detailed explanation of the semantics.

This function can only be called before starting a transaction, not after the transaction has been started already.

The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.

Parameters

isolation_level

Table 1. Valid values for isolation_level parameter

Value | Constant | Meaning
1 | SESAM_TXISOL_READ_UNCOMMITTED | Read Uncommitted
2 | SESAM_TXISOL_READ_COMMITTED | Read Committed
3 | SESAM_TXISOL_REPEATABLE_READ | Repeatable Read
4 | SESAM_TXISOL_SERIALIZABLE | Serializable

read_only

Table 2. Valid values for read_only parameter

Value | Constant | Meaning
0 | SESAM_TXREAD_READWRITE | Read/Write
1 | SESAM_TXREAD_READONLY | Read-Only

Return Values

Returns TRUE if the values are valid, and the settransaction operation was successful, FALSE otherwise.

Examples

Example 1. Setting SESAM transaction parameters

&#60;?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
                     SESAM_TXREAD_READONLY);
?&#62;

Prev | Home | Next
sesam_seek_row | Up | PostgreSQL Session Save Handler


Session Handling Functions

PHP Manual
Prev Next

CXLVII. Session Handling Functions

Introduction

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.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Caution

If you do turn on session.auto_start then you cannot put objects into your sessions since the class definition has to be loaded before starting the session in order to recreate the objects in your session.

All registered variables are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

Warning

Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object).

Note: Session handling was added in PHP 4.0.

Note: Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.

Sessions and security

External links: Session fixation

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. You need to take additional measures to actively protect the integrity of the session, depending on the value associated with it.

Assess the importance of the data carried by your sessions and deploy additional protections -- this usually comes at a price, reduced convenience for the user. For example, if you want to protect users from simple social engineering tactics, you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.

Requirements

No external libraries are needed to build this extension.

Note: Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropriate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked. Session data is stored in memory thus web server restart deletes it.

Installation

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP --with-mm[=DIR] .

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: By default, all data related to a particular session will be stored in a file in the directory specified by the session.save_path INI option. A file for each session (regardless of if any data is associated with that session) will be created. This is due to the fact that a session is opened (a file is created) but no data is even written to that file. Note that this behavior is a side-effect of the limitations of working with the file system and it is possible that a custom session handler (such as one which uses a database) does not keep track of sessions which store no data.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Session configuration options

Name | Default | Changeable | Changelog
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Available since PHP 4.0.4.
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.referer_check | "" | PHP_INI_ALL |
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42 | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.hash_function | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 5.0.0.
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Available since PHP 4.0.4.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

session.save_handler string

session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. Note that individual extensions may register their own save_handlers; registered handlers can be obtained on a per-installation basis by referring to phpinfo(). See also session_set_save_handler().

session.save_path string

session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. Defaults to /tmp. See also session_save_path().

There is an optional N argument to this directive that determines the number of directory levels your session files will be spread around in. For example, setting to '5;/tmp' may end up creating a session file and location like /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you must create all of these directories before use. A small shell script exists in ext/session to do this, it's called mod_files.sh. Also note that if N is used and greater than 0 then automatic garbage collection will not be performed, see a copy of php.ini for further information. Also, if you use N, be sure to surround session.save_path in "quotes" because the separator (;) is also used for comments in php.ini.

Warning

If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp.

session.name string

session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().

session.auto_start boolean

session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).

session.serialize_handler string

session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.

session.gc_probability integer

session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details.

session.gc_divisor integer

session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.

session.gc_maxlifetime integer

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

Note: If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

session.referer_check string

session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.

session.entropy_file string

session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems.

session.entropy_length integer

session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).

session.use_cookies boolean

session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).

session.use_only_cookies boolean

session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0.

session.cookie_lifetime integer

session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params(). Since the cookie is returned by the browser, it is not prolonged to suffice the lifetime. It must be sent manually by setcookie().

session.cookie_path string

session.cookie_path specifies path to set in session_cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_domain string

session.cookie_domain specifies the domain to set in session_cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_secure boolean

session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_httponly boolean

Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

session.cache_limiter string

session.cache_limiter specifies cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache. See also session_cache_limiter().

session.cache_expire integer

session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().

session.use_trans_sid boolean

session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

Note: For PHP 4.1.2 or less, it is enabled by compiling with --enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled.

URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

session.bug_compat_42 boolean

PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.

session.bug_compat_warn boolean

PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.

session.hash_function mixed

session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

Since PHP 6.0.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.

Note: This was introduced in PHP 5.

session.hash_bits_per_character integer

session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

Note: This was introduced in PHP 5.

url_rewriter.tags string

url_rewriter.tags specifies which HTML tags are rewritten to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Note: If you want HTML/XHTML strict conformity, remove the form entry and use the <fieldset> tags around your form fields.

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

Note: As of PHP 4.0.3, track_vars is always turned on.

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.

SID (string)

Constant containing either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie.

Examples

Note: As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

If register_globals is disabled, only members of the global associative array $_SESSION can be registered as session variables. The restored session variables will only be available in the array $_SESSION.

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readability. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.

Example 1. Registering a variable with $_SESSION.

&#60;?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count']++;
}
?&#62;

Example 2. Unregistering a variable with $_SESSION and register_globals disabled.

&#60;?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?&#62;

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Warning

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.

Caution

Before PHP 4.3, if you are using $_SESSION and you have disabled register_globals, don't use session_register(), session_is_registered() or session_unregister(). Disabling register_globals is recommended for both security and performance reasons.

If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance. However, if the variable is registered by $_SESSION then the global variable is available since the next request.

There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.

Passing the Session ID

There are two methods to propagate a session id:

  • Cookies

  • URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. Unless you are using PHP 4.2 or later, you need to enable it manually when building PHP. Under Unix, pass --enable-trans-sid to configure. If this build option and the run-time option session.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.

Note: The arg_separator.output php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

Example 3. Counting the number of hits of a single user

&#60;?php

session_start();

if (empty($_SESSION['count'])) {
   $_SESSION['count'] = 1;
} else {
   $_SESSION['count']++;
}
?&#62;

&#60;p&#62;
Hello visitor, you have seen this page &#60;?php echo $_SESSION['count']; ?&#62; times.
&#60;/p&#62;

&#60;p&#62;
To continue, &#60;a href="nextpage.php?&#60;?php echo htmlspecialchars(SID); ?&#62;"&#62;click
here&#60;/a&#62;.
&#60;/p&#62;

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.

Note: Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.

Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions.

Table of Contents
session_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string
session_destroy -- Destroys all data registered to a session
session_encode -- Encodes the current session data as a string
session_get_cookie_params -- Get the session cookie parameters
session_id -- Get and/or set the current session id
session_is_registered -- Find out whether a global variable is registered in a session
session_module_name -- Get and/or set the current session module
session_name -- Get and/or set the current session name
session_regenerate_id -- Update the current session id with a newly generated one
session_register -- Register one or more global variables with the current session
session_save_path -- Get and/or set the current session save path
session_set_cookie_params -- Set the session cookie parameters
session_set_save_handler -- Sets user-level session storage functions
session_start -- Initialize session data
session_unregister -- Unregister a global variable from the current session
session_unset -- Free all session variables
session_write_close -- Write session data and end session

Prev | Home | Next
session_pgsql_status | Up | session_cache_expire


session_cache_expire

(PHP 4 >= 4.2.0, PHP 5)

session_cache_expire -- Return current cache expire

Description

int session_cache_expire ( [int new_cache_expire] )

session_cache_expire() returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180. If new_cache_expire is given, the current cache expire is replaced with new_cache_expire.

The cache expire is reset to the default value of 180 stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called).

Example 1. session_cache_expire() example

&#60;?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* set the cache expire to 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* start the session */

session_start();

echo "The cache limiter is now set to $cache_limiter&#60;br /&#62;";
echo "The cached session pages expire after $cache_expire minutes";
?&#62;

Note: Setting new_cache_expire is of value only, if session.cache_limiter is set to a value different from nocache.

See also the configuration settings session.cache_expire, session.cache_limiter and session_cache_limiter().

Prev | Home | Next
Session Handling Functions | Up | session_cache_limiter


session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5)

session_cache_limiter -- Get and/or set the current cache limiter

Description

string session_cache_limiter ( [string cache_limiter] )

session_cache_limiter() returns the name of the current cache limiter. If cache_limiter is specified, the name of the current cache limiter is changed to the new value.

The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies. Setting the cache limiter to nocache disallows any client/proxy caching. A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents.

In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The expire header is never sent to the client in this mode.

Note: private_no_expire was added in PHP 4.2.0.

The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called).

Example 1. session_cache_limiter() example

&#60;?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "The cache limiter is now set to $cache_limiter&#60;br /&#62;";
?&#62;

Also see the session.cache_limiter configuration directive.

Prev | Home | Next
session_cache_expire | Up | session_commit


session_commit

(PHP 4 >= 4.3.11, PHP 5)

session_commit -- Alias of session_write_close()

Description

This function is an alias of: session_write_close().

Prev | Home | Next
session_cache_limiter | Up | session_decode


session_decode

(PHP 4, PHP 5)

session_decode -- Decodes session data from a string

Description

bool session_decode ( string data )

session_decode() decodes the session data in data, setting variables stored in the session.

See also session_encode().

Prev | Home | Next
session_commit | Up | session_destroy


session_destroy

(PHP 4, PHP 5)

session_destroy -- Destroys all data registered to a session

Description

bool session_destroy ( void )

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

Returns TRUE on success or FALSE on failure.

Example 1. Destroying a session with $_SESSION

&#60;?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');
}

// Finally, destroy the session.
session_destroy();
?&#62;

Note: Only use session_unset() for older deprecated code that does not use $_SESSION.

See also unset() and setcookie().

Prev | Home | Next
session_decode | Up | session_encode


session_encode

(PHP 4, PHP 5)

session_encode -- Encodes the current session data as a string

Description

string session_encode ( void )

session_encode() returns a string with the contents of the current session encoded within.

See also session_decode()

Prev | Home | Next
session_destroy | Up | session_get_cookie_params


session_get_cookie_params

(PHP 4, PHP 5)

session_get_cookie_params -- Get the session cookie parameters

Description

array session_get_cookie_params ( void )

The session_get_cookie_params() function returns an array with the current session cookie information, the array contains the following items:

  • "lifetime" - The lifetime of the cookie in seconds.

  • "path" - The path where information is stored.

  • "domain" - The domain of the cookie.

  • "secure" - The cookie should only be sent over secure connections. (This item was added in PHP 4.0.4.)

  • "httponly" - The cookie can only be accessed through the HTTP protocol (This item was added in PHP 5.2.0).

See also the configuration directives session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure, session.cookie_httponly, and session_set_cookie_params().

Prev | Home | Next
session_encode | Up | session_id


session_id

(PHP 4, PHP 5)

session_id -- Get and/or set the current session id

Description

string session_id ( [string id] )

session_id() is used to get or set the session id for the current session.

The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling.

Parameters

id

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!

Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.

Return Values

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

See Also

session_regenerate_id()
session_start()
session_set_save_handler()
session.save_handler

Prev | Home | Next
session_get_cookie_params | Up | session_is_registered


session_is_registered

(PHP 4, PHP 5)

session_is_registered -- Find out whether a global variable is registered in a session

Description

bool session_is_registered ( string name )

session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session.

Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

Caution

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister().

Prev | Home | Next
session_id | Up | session_module_name


session_module_name

(PHP 4, PHP 5)

session_module_name -- Get and/or set the current session module

Description

string session_module_name ( [string module] )

session_module_name() returns the name of the current session module. If module is specified, that module will be used instead.

Prev | Home | Next
session_is_registered | Up | session_name


session_name

(PHP 4, PHP 5)

session_name -- Get and/or set the current session name

Description

string session_name ( [string name] )

session_name() returns the name of the current session. If name is specified, the name of the current session is changed to its value.

The session name references the session id in cookies and URLs. It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).

Warning

The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.

Example 1. session_name() examples

&#60;?php

/* set the session name to WebsiteID */

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name&#60;br /&#62;";
?&#62;

See also the session.name configuration directive.

Prev | Home | Next
session_module_name | Up | session_regenerate_id


session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5)

session_regenerate_id -- Update the current session id with a newly generated one

Description

bool session_regenerate_id ( [bool delete_old_session] )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Parameters

delete_old_session

Whether to delete the old associated session file or not. Defaults to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
4.3.3 | Since then, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id.
5.1.0 | Added the delete_old_session parameter.

Examples

Example 1. A session_regenerate_id() example

&#60;?php
session_start();

$old_sessionid = session_id();

session_regenerate_id();

$new_sessionid = session_id();

echo "Old Session: $old_sessionid&#60;br /&#62;";
echo "New Session: $new_sessionid&#60;br /&#62;";

print_r($_SESSION);
?&#62;

See Also

session_id()
session_start()
session_name()

Prev | Home | Next
session_name | Up | session_register


session_register

(PHP 4, PHP 5)

session_register -- Register one or more global variables with the current session

Description

bool session_register ( mixed name [, mixed ...] )

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

Caution

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

register_globals: important note: Since PHP 4.2.0, the default value for the PHP directive register_globals is off, and it is completely removed as of PHP 6.0.0. The PHP community encourages all to not rely on this directive but instead use other means, such as the superglobals.

Caution

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

Caution

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

This function returns TRUE when all of the variables are successfully registered with the session.

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start() before use.

You can also create a session variable by simply setting the appropriate member of the $_SESSION or $HTTP_SESSION_VARS (PHP < 4.1.0) array.

&#60;?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");

// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";

// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?&#62;

Note: It is currently impossible to register resource variables in a session. For example, you cannot create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definition. A list of functions that return resources are available in the resource types appendix.

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, assign values to $_SESSION. For example: $_SESSION['var'] = 'ABC';

See also session_is_registered(), session_unregister(), and $_SESSION.

Prev | Home | Next
session_regenerate_id | Up | session_save_path


session_save_path

(PHP 4, PHP 5)

session_save_path -- Get and/or set the current session save path

Description

string session_save_path ( [string path] )

session_save_path() returns the path of the current directory used to save session data. If path is specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

Note: On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.

See also the session.save_path configuration directive.

Prev | Home | Next
session_register | Up | session_set_cookie_params


session_set_cookie_params

(PHP 4, PHP 5)

session_set_cookie_params -- Set the session cookie parameters

Description

void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure [, bool httponly]]]] )

Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

Note: The secure parameter was added in PHP 4.0.4, while the httponly parameter was added in PHP 5.2.0.

See also the configuration directives session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure, session.cookie_httponly, and session_get_cookie_params().

Prev | Home | Next
session_save_path | Up | session_set_save_handler


session_set_save_handler

(PHP 4, PHP 5)

session_set_save_handler -- Sets user-level session storage functions

Description

bool session_set_save_handler ( callback open, callback close, callback read, callback write, callback destroy, callback gc )

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database. Returns TRUE on success or FALSE on failure.

Note: The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Read function must return string value always to make save handler work as expected. Return empty string if there is no data to read. Return values from other handlers are converted to boolean expression. TRUE for success, FALSE for failure.

Warning

Write and Close handlers are called after destructing objects since PHP 5.0.5. Thus destructors can use sessions but session handler can't use objects. In prior versions, they were called in the opposite order. It is possible to call session_write_close() from the destructor to solve this chicken and egg problem.

Example 1. session_set_save_handler() example

&#60;?php
function open($save_path, $session_name)
{
  global $sess_save_path;

  $sess_save_path = $save_path;
  return(true);
}

function close()
{
  return(true);
}

function read($id)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  return (string) @file_get_contents($sess_file);
}

function write($id, $sess_data)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    $return = fwrite($fp, $sess_data);
    fclose($fp);
    return $return;
  } else {
    return(false);
  }

}

function destroy($id)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

function gc($maxlifetime)
{
  global $sess_save_path;

  foreach (glob("$sess_save_path/sess_*") as $filename) {
    if (filemtime($filename) + $maxlifetime &#60; time()) {
      @unlink($filename);
    }
  }
  return true;
}

session_set_save_handler("open", "close", "read", "write", "destroy", "gc");

session_start();

// proceed to use sessions normally

?&#62;

See also the session.save_handler configuration directive.

Prev | Home | Next
session_set_cookie_params | Up | session_start


session_start

(PHP 4, PHP 5)

session_start -- Initialize session data

Description

bool session_start ( void )

session_start() creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie.

This function always returns TRUE.

Note: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.

Example 1. A session example: page1.php

&#60;?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '&#60;br /&#62;&#60;a href="page2.php"&#62;page 2&#60;/a&#62;';

// Or maybe pass along the session id, if needed
echo '&#60;br /&#62;&#60;a href="page2.php?' . SID . '"&#62;page 2&#60;/a&#62;';
?&#62;

After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.

Example 2. A session example: page2.php

&#60;?php
// page2.php

session_start();

echo 'Welcome to page #2&#60;br /&#62;';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '&#60;br /&#62;&#60;a href="page1.php"&#62;page 1&#60;/a&#62;';
?&#62;

If you want to use a named session, you must call session_name() before calling session_start().

session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output. For example, user must register ob_gzhandler before session start.

Note: Use of zlib.output_compression is recommended rather than ob_gzhandler()

Note: As of PHP 4.3.3, calling session_start() while the session has already been started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.

See also $_SESSION, session.auto_start, and session_id().

Prev | Home | Next
session_set_save_handler | Up | session_unregister


session_unregister

(PHP 4, PHP 5)

session_unregister -- Unregister a global variable from the current session

Description

bool session_unregister ( string name )

session_unregister() unregisters the global variable named name from the current session.

This function returns TRUE when the variable is successfully unregistered from the session.

Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister a session variable. Do not unset() $_SESSION itself as this will disable the special function of the $_SESSION superglobal.

Caution

This function does not unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable.

Caution

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister().

Prev | Home | Next
session_start | Up | session_unset


session_unset

(PHP 4, PHP 5)

session_unset -- Free all session variables

Description

void session_unset ( void )

The session_unset() function frees all session variables currently registered.

Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);.

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Prev | Home | Next
session_unregister | Up | session_write_close


session_write_close

(PHP 4 >= 4.0.4, PHP 5)

session_write_close -- Write session data and end session

Description

void session_write_close ( void )

End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

Prev | Home | Next
session_unset | Up | Shared Memory Functions


Shared Memory Functions

PHP Manual
Prev Next

CXLVIII. Shared Memory Functions

Introduction

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.

Note: Versions of Windows previous to Windows 2000 do not support shared memory. Under Windows, Shmop will only work when PHP is running as a web server module, such as Apache or IIS (CLI and CGI will not work).

Note: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

Requirements

No external libraries are needed to build this extension.

Installation

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Predefined Constants

This extension has no constants defined.

Examples

Example 1. Shared Memory Operations Overview

&#60;?php

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: " . $shm_size . " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?&#62;

Table of Contents
shmop_close -- Close shared memory block
shmop_delete -- Delete shared memory block
shmop_open -- Create or open shared memory block
shmop_read -- Read data from shared memory block
shmop_size -- Get size of shared memory block
shmop_write -- Write data into shared memory block

Prev | Home | Next
session_write_close | Up | shmop_close


shmop_close

(PHP 4 >= 4.0.4, PHP 5)

shmop_close -- Close shared memory block

Description

void shmop_close ( int shmid )

shmop_close() is used to close a shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

No value is returned.

Examples

Example 1. Closing shared memory block

&#60;?php
shmop_close($shm_id);
?&#62;

This example will close shared memory block identified by $shm_id.

See Also

shmop_open()

Prev | Home | Next
Shared Memory Functions | Up | shmop_delete


shmop_delete

(PHP 4 >= 4.0.4, PHP 5)

shmop_delete -- Delete shared memory block

Description

bool shmop_delete ( int shmid )

shmop_delete() is used to delete a shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Deleting shared memory block

&#60;?php
shmop_delete($shm_id);
?&#62;

This example will delete shared memory block identified by $shm_id.

Prev | Home | Next
shmop_close | Up | shmop_open


shmop_open

(PHP 4 >= 4.0.4, PHP 5)

shmop_open -- Create or open shared memory block

Description

int shmop_open ( int key, string flags, int mode, int size )

shmop_open() can create or open a shared memory block.

Parameters

key

System's id for the shared memory block. Can be passed as a decimal or hex.

flags

The flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only

  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write

  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.

  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

mode

The permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form, like for example 0644

size

The size of the shared memory block you wish to create in bytes

Note: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

Return Values

On success shmop_open() will return an id that you can use to access the shared memory segment you've created. FALSE is returned on failure.

Examples

Example 1. Create a new shared memory block

&#60;?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?&#62;

This example opened a shared memory block with a system id returned by ftok().

See Also

shmop_close()
shmop_delete()

Prev | Home | Next
shmop_delete | Up | shmop_read


shmop_read

(PHP 4 >= 4.0.4, PHP 5)

shmop_read -- Read data from shared memory block

Description

string shmop_read ( int shmid, int start, int count )

shmop_read() will read a string from shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

start

Offset from which to start reading

count

The number of bytes to read

Return Values

Returns the data or FALSE on failure.

Examples

Example 1. Reading shared memory block

&#60;?php
$shm_data = shmop_read($shm_id, 0, 50);
?&#62;

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

See Also

shmop_write()

Prev | Home | Next
shmop_open | Up | shmop_size


shmop_size

(PHP 4 >= 4.0.4, PHP 5)

shmop_size -- Get size of shared memory block

Description

int shmop_size ( int shmid )

shmop_size() is used to get the size, in bytes of the shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

Returns an int, which represents the number of bytes the shared memory block occupies.

Examples

Example 1. Getting the size of the shared memory block

&#60;?php
$shm_size = shmop_size($shm_id);
?&#62;

This example will put the size of shared memory block identified by $shm_id into $shm_size.

Prev | Home | Next
shmop_read | Up | shmop_write


shmop_write

(PHP 4 >= 4.0.4, PHP 5)

shmop_write -- Write data into shared memory block

Description

int shmop_write ( int shmid, string data, int offset )

shmop_write() will write a string into shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

data

A string to write into shared memory block

offset

Specifies where to start writing data inside the shared memory segment.

Return Values

The size of the written data, or FALSE on failure.

Examples

Example 1. Writing to shared memory block

&#60;?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?&#62;

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

See Also

shmop_read()

Prev | Home | Next
shmop_size | Up | SimpleXML functions


SimpleXML functions

PHP Manual
Prev Next

CXLIX. SimpleXML functions

Introduction

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

Requirements

The SimpleXML extension requires PHP 5.

Installation

The SimpleXML extension is enabled by default. To disable it, use the --disable-simplexml configure option.

Examples

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Example 1. Include file example.php with XML string

&#60;?php
$xmlstr = &#60;&#60;&#60;XML
&#60;?xml version='1.0' standalone='yes'?&#62;
&#60;movies&#62;
 &#60;movie&#62;
  &#60;title&#62;PHP: Behind the Parser&#60;/title&#62;
  &#60;characters&#62;
   &#60;character&#62;
    &#60;name&#62;Ms. Coder&#60;/name&#62;
    &#60;actor&#62;Onlivia Actora&#60;/actor&#62;
   &#60;/character&#62;
   &#60;character&#62;
    &#60;name&#62;Mr. Coder&#60;/name&#62;
    &#60;actor&#62;El Act&#38;#211;r&#60;/actor&#62;
   &#60;/character&#62;
  &#60;/characters&#62;
  &#60;plot&#62;
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  &#60;/plot&#62;
  &#60;rating type="thumbs"&#62;7&#60;/rating&#62;
  &#60;rating type="stars"&#62;5&#60;/rating&#62;
 &#60;/movie&#62;
&#60;/movies&#62;
XML;
?&#62;

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example 2. Getting <plot>

&#60;?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

echo $xml-&#62;movie[0]-&#62;plot; // "So this language. It's like..."
?&#62;

Example 3. Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

&#60;?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

/* For each &#60;movie&#62; node, we echo a separate &#60;plot&#62;. */
foreach ($xml-&#62;movie as $movie) {
   echo $movie-&#62;plot, '&#60;br /&#62;';
}

?&#62;

Example 4. Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

&#60;?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

/* Access the &#60;rating&#62; nodes of the first movie.
 * Output the rating scale, too. */
foreach ($xml-&#62;movie[0]-&#62;rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?&#62;

Example 5. Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

&#60;?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

if ((string) $xml-&#62;movie-&#62;title == 'PHP: Behind the Parser') {
    print 'My favorite movie.';
}

htmlentities((string) $xml-&#62;movie-&#62;title);
?&#62;

Example 6. Using XPath

SimpleXML includes builtin XPath support. To find all <character> elements:

&#60;?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);

foreach ($xml-&#62;xpath('//character') as $character) {
    echo $character-&#62;name, 'played by ', $character-&#62;actor, '&#60;br /&#62;';
}
?&#62;

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

Example 7. Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

&#60;?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);

$xml-&#62;movie[0]-&#62;characters-&#62;character[0]-&#62;name = 'Miss Coder';

echo $xml-&#62;asXML();
?&#62;

The above code will output a new XML document, just like the original, except that the new XML will change Ms. Coder to Miss Coder.

Example 8. Adding elements and attributes

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes.

&#60;?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);

$character = $xml-&#62;movie[0]-&#62;characters-&#62;addChild('character');
$character-&#62;addChild('name', 'Mr. Parser');
$character-&#62;addChild('actor', 'John Doe');

$rating = $xml-&#62;movie[0]-&#62;addChild('rating', 'PG');
$rating-&#62;addAttribute('type', 'mpaa');

echo $xml-&#62;asXML();
?&#62;

The above code will output an XML document based on the original but having a new character and rating.

Example 9. DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

&#60;?php
$dom = new domDocument;
$dom-&#62;loadXML('&#60;books&#62;&#60;book&#62;&#60;title&#62;blah&#60;/title&#62;&#60;/book&#62;&#60;/books&#62;');
if (!$dom) {
     echo 'Error while parsing the document';
     exit;
}

$s = simplexml_import_dom($dom);

echo $s-&#62;book[0]-&#62;title;
?&#62;

Table of Contents
SimpleXMLElement->addAttribute() -- Adds an attribute to the SimpleXML element
SimpleXMLElement->addChild() -- Adds a child element to the XML node
SimpleXMLElement->asXML() -- Return a well-formed XML string based on SimpleXML element
SimpleXMLElement->attributes() -- Identifies an element's attributes
SimpleXMLElement->children() -- Finds children of given node
SimpleXMLElement->__construct() -- Creates a new SimpleXMLElement object
SimpleXMLElement->getDocNamespaces() -- Returns namespaces declared in document
SimpleXMLElement->getName() -- Gets the name of the XML element
SimpleXMLElement->getNamespaces() -- Returns namespaces used in document
SimpleXMLElement->registerXPathNamespace() -- Creates a prefix/ns context for the next XPath query
SimpleXMLElement->xpath() -- Runs XPath query on XML data
simplexml_import_dom -- Get a SimpleXMLElement object from a DOM node.
simplexml_load_file -- Interprets an XML file into an object
simplexml_load_string -- Interprets a string of XML into an object

Prev | Home | Next
shmop_write | Up | SimpleXMLElement->addAttribute()


SimpleXMLElement->asXML()

(no version information, might be only in CVS)

SimpleXMLElement->asXML() -- Return a well-formed XML string based on SimpleXML element

Description

class SimpleXMLElement {

mixed asXML ( [string filename] )

}

The asXML method formats the parent object's data in XML version 1.0.

Parameters

filename

If specified, the function writes the data to the file rather than returning it.

Return Values

If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Examples

Example 1. Get XML

&#60;?php
$string = &#60;&#60;&#60;XML
&#60;a&#62;
 &#60;b&#62;
  &#60;c&#62;text&#60;/c&#62;
  &#60;c&#62;stuff&#60;/c&#62;
 &#60;/b&#62;
 &#60;d&#62;
  &#60;c&#62;code&#60;/c&#62;
 &#60;/d&#62;
&#60;/a&#62;
XML;

$xml = new SimpleXMLElement($string);

echo $xml-&#62;asXML(); // &#60;?xml ... &#60;a&#62;&#60;b&#62;&#60;c&#62;text&#60;/c&#62;&#60;c&#62;stuff&#60;/c&#62; ...

?&#62;

asXML also works on Xpath results:

Example 2. Using asXML() on Xpath results

&#60;?php
// Continued from example XML above.

/* Search for &#60;a&#62;&#60;b&#62;&#60;c&#62; */
$result = $xml-&#62;xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo $node-&#62;asXML(); // &#60;c&#62;text&#60;/c&#62; and &#60;c&#62;stuff&#60;/c&#62;
}
?&#62;

Prev | Home | Next
SimpleXMLElement->addChild() | Up | SimpleXMLElement->attributes()


SimpleXMLElement->attributes()

(no version information, might be only in CVS)

SimpleXMLElement->attributes() -- Identifies an element's attributes

Description

class SimpleXMLElement {

SimpleXMLElement attributes ( [string ns [, bool is_prefix]] )

}

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

ns

An optional namespace for the retrieved attributes

is_prefix

Default to FALSE

Return Values

Examples

Example 1. Interpret an XML string

&#60;?php
$string = &#60;&#60;&#60;XML
&#60;a xmlns:b&#62;
 &#60;foo name="one" game="lonely"&#62;1&#60;/foo&#62;
&#60;/a&#62;
XML;

$xml = simplexml_load_string($string);
foreach($xml-&#62;foo[0]-&#62;attributes() as $a =&#62; $b) {
    echo $a,'="',$b,"\"\n";
}
?&#62;

The above example will output:

name="one"
game="lonely"

Prev | Home | Next
SimpleXMLElement->asXML() | Up | SimpleXMLElement->children()


SimpleXMLElement->children()

(no version information, might be only in CVS)

SimpleXMLElement->children() -- Finds children of given node

Description

class SimpleXMLElement {

SimpleXMLElement children ( [string ns [, bool is_prefix]] )

}

This method finds the children of the element of which it is a member. The result follows normal iteration rules.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

ns

is_prefix

Default to FALSE

Return Values

Examples

Example 1. Traversing a children() pseudo-array

&#60;?php
$xml = new SimpleXMLElement(
'&#60;person&#62;
 &#60;child role="son"&#62;
  &#60;child role="daughter"/&#62;
 &#60;/child&#62;
 &#60;child role="daughter"&#62;
  &#60;child role="son"&#62;
   &#60;child role="son"/&#62;
  &#60;/child&#62;
 &#60;/child&#62;
&#60;/person&#62;');

foreach ($xml-&#62;children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen-&#62;children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';

        foreach ($third_gen-&#62;children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}
?&#62;

The above example will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Prev | Home | Next
SimpleXMLElement->attributes() | Up | SimpleXMLElement->__construct()


SimpleXMLElement->xpath()

(no version information, might be only in CVS)

SimpleXMLElement->xpath() -- Runs XPath query on XML data

Description

class SimpleXMLElement {

array xpath ( string path )

}

The xpath method searches the SimpleXML node for children matching the XPath path.

Parameters

path

An XPath path

Return Values

Always returns an array of SimpleXMLElement objects.

Examples

Example 1. Xpath

&#60;?php
$string = &#60;&#60;&#60;XML
&#60;a&#62;
 &#60;b&#62;
  &#60;c&#62;text&#60;/c&#62;
  &#60;c&#62;stuff&#60;/c&#62;
 &#60;/b&#62;
 &#60;d&#62;
  &#60;c&#62;code&#60;/c&#62;
 &#60;/d&#62;
&#60;/a&#62;
XML;

$xml = new SimpleXMLElement($string);

/* Search for &#60;a&#62;&#60;b&#62;&#60;c&#62; */
$result = $xml-&#62;xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml-&#62;xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?&#62;

The above example will output:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

Prev | Home | Next
SimpleXMLElement->registerXPathNamespace() | Up | simplexml_import_dom


simplexml_import_dom

(PHP 5)

simplexml_import_dom -- Get a SimpleXMLElement object from a DOM node.

Description

SimpleXMLElement simplexml_import_dom ( DOMNode node [, string class_name] )

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

Parameters

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Return Values

Returns a SimpleXMLElement or FALSE on failure.

Examples

Example 1. Importing DOM

&#60;?php
$dom = new DOMDocument;
$dom-&#62;loadXML('&#60;books&#62;&#60;book&#62;&#60;title&#62;blah&#60;/title&#62;&#60;/book&#62;&#60;/books&#62;');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s-&#62;book[0]-&#62;title; // blah
?&#62;

See Also

dom_import_simplexml()

Prev | Home | Next
SimpleXMLElement->xpath() | Up | simplexml_load_file


simplexml_load_file

(PHP 5)

simplexml_load_file -- Interprets an XML file into an object

Description

object simplexml_load_file ( string filename [, string class_name [, int options [, string ns [, bool is_prefix]]]] )

Convert the well-formed XML document in the given file to an object.

Parameters

filename

Path to the XML file

Note: Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

is_prefix

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.

Examples

Example 1. Interpret an XML document

&#60;?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    var_dump($xml);
} else {
    exit('Failed to open test.xml.');
}
?&#62;

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

See Also

simplexml_load_string
SimpleXMLElement->__construct()

Prev | Home | Next
simplexml_import_dom | Up | simplexml_load_string


simplexml_load_string

(PHP 5)

simplexml_load_string -- Interprets a string of XML into an object

Description

object simplexml_load_string ( string data [, string class_name [, int options [, string ns [, bool is_prefix]]]] )

Takes a well-formed XML string and returns it as an object.

Parameters

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

is_prefix

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document. On errors, it will return FALSE.

Examples

Example 1. Interpret an XML string

&#60;?php
$string = &#60;&#60;&#60;XML
&#60;?xml version='1.0'?&#62;
&#60;document&#62;
 &#60;title&#62;Forty What?&#60;/title&#62;
 &#60;from&#62;Joe&#60;/from&#62;
 &#60;to&#62;Jane&#60;/to&#62;
 &#60;body&#62;
  I know that's the answer -- but what's the question?
 &#60;/body&#62;
&#60;/document&#62;
XML;

$xml = simplexml_load_string($string);

var_dump($xml);
?&#62;

The above example will output:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

See Also

simplexml_load_file
SimpleXMLElement->__construct()

Prev | Home | Next
simplexml_load_file | Up | SNMP Functions


SNMP Functions

PHP Manual
Prev Next

CL. SNMP Functions

Introduction

Requirements

In order to use the SNMP functions on Unix you need to install the NET-SNMP package. On Windows these functions are only available on NT and not on Win95/98.

Installation

Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h or acconfig.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:

#define NO_ZEROLENGTH_COMMUNITY 1
Now compile PHP --with-snmp[=DIR].

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.

The Windows distribution contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.c:\usr\mibs.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

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.

SNMP_OID_OUTPUT_FULL (integer)

As of 5.2.0

SNMP_OID_OUTPUT_NUMERIC (integer)

As of 5.2.0

SNMP_VALUE_LIBRARY (integer)

SNMP_VALUE_PLAIN (integer)

SNMP_VALUE_OBJECT (integer)

SNMP_BIT_STR (integer)

SNMP_OCTET_STR (integer)

SNMP_OPAQUE (integer)

SNMP_NULL (integer)

SNMP_OBJECT_ID (integer)

SNMP_IPADDRESS (integer)

SNMP_COUNTER (integer)

SNMP_UNSIGNED (integer)

SNMP_TIMETICKS (integer)

SNMP_UINTEGER (integer)

SNMP_INTEGER (integer)

SNMP_COUNTER64 (integer)

Table of Contents
snmp_get_quick_print -- Fetches the current value of the UCD library's quick_print setting
snmp_get_valueretrieval -- Return the method how the SNMP values will be returned
snmp_read_mib -- Reads and parses a MIB file into the active MIB tree
snmp_set_enum_print -- Return all values that are enums with their enum value instead of the raw integer
snmp_set_oid_numeric_print -- Return all objects including their respective object id within the specified one
snmp_set_oid_output_format -- Set the OID output format
snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library
snmp_set_valueretrieval -- Specify the method how the SNMP values will be returned
snmpget -- Fetch an SNMP object
snmpgetnext -- Fetch a SNMP object
snmprealwalk -- Return all objects including their respective object ID within the specified one
snmpset -- Set an SNMP object
snmpwalk -- Fetch all the SNMP objects from an agent
snmpwalkoid -- Query for a tree of information about a network entity

Prev | Home | Next
simplexml_load_string | Up | snmp_get_quick_print


snmp_get_quick_print

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmp_get_quick_print -- Fetches the current value of the UCD library's quick_print setting

Description

bool snmp_get_quick_print ( void )

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

Return Values

Returns TRUE if quick_print is on, FALSE otherwise.

Examples

Example 1. snmp_get_quick_print() example

&#60;?php
$quickprint = snmp_get_quick_print();
?&#62;

See Also

snmp_set_quick_print() for a full description of what quick_print does.

Prev | Home | Next
SNMP Functions | Up | snmp_get_valueretrieval


snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_get_valueretrieval -- Return the method how the SNMP values will be returned

Description

int snmp_get_valueretrieval ( void )

Warning

This function is currently not documented; only the argument list is available.

See Also

snmp_set_valueretrieval()

Prev | Home | Next
snmp_get_quick_print | Up | snmp_read_mib


snmp_read_mib

(PHP 5)

snmp_read_mib -- Reads and parses a MIB file into the active MIB tree

Description

bool snmp_read_mib ( string filename )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
snmp_get_valueretrieval | Up | snmp_set_enum_print


snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_enum_print -- Return all values that are enums with their enum value instead of the raw integer

Description

void snmp_set_enum_print ( int enum_print )

Warning

This function is currently not documented; only the argument list is available.

Notes

Note: snmp_set_enum_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

Prev | Home | Next
snmp_read_mib | Up | snmp_set_oid_numeric_print


snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_oid_numeric_print -- Return all objects including their respective object id within the specified one

Description

void snmp_set_oid_numeric_print ( int oid_numeric_print )

Warning

This function is currently not documented; only the argument list is available.

ChangeLog

Version | Description
5.2.0 | Since PHP 5.2.0, This function is an alias of: snmp_set_oid_output_format().

See Also

snmp_set_oid_output_format()

Prev | Home | Next
snmp_set_enum_print | Up | snmp_set_oid_output_format


snmp_set_quick_print

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library

Description

void snmp_set_quick_print ( bool quick_print )

Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.

Currently strings are still returned with extra quotes, this will be corrected in a later release.

Parameters

quick_print

Return Values

No value is returned.

Examples

Setting quick_print is often used when using the information returned rather then displaying it.

Example 1. Using snmp_set_quick_print()

&#60;?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
?&#62;

The above example will output something similar to:

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

See Also

snmp_get_quick_print()

Prev | Home | Next
snmp_set_oid_output_format | Up | snmp_set_valueretrieval


snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_set_valueretrieval -- Specify the method how the SNMP values will be returned

Description

void snmp_set_valueretrieval ( int method )

Warning

This function is currently not documented; only the argument list is available.

See Also

snmp_get_valueretrieval()

Prev | Home | Next
snmp_set_quick_print | Up | snmpget


snmpget

(PHP 3, PHP 4, PHP 5)

snmpget -- Fetch an SNMP object

Description

string snmpget ( string hostname, string community, string object_id [, int timeout [, int retries]] )

The snmpget() function is used to read the value of an SNMP object specified by the object_id.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

retries

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example 1. Using snmpget()

&#60;?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?&#62;

See Also

snmpset()

Prev | Home | Next
snmp_set_valueretrieval | Up | snmpgetnext


snmpgetnext

(PHP 5)

snmpgetnext -- Fetch a SNMP object

Description

string snmpgetnext ( string host, string community, string object_id [, int timeout [, int retries]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
snmpget | Up | snmprealwalk


snmprealwalk

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmprealwalk -- Return all objects including their respective object ID within the specified one

Description

array snmprealwalk ( string host, string community, string object_id [, int timeout [, int retries]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
snmpgetnext | Up | snmpset


snmpset

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

snmpset -- Set an SNMP object

Description

bool snmpset ( string hostname, string community, string object_id, string type, mixed value [, int timeout [, int retries]] )

snmpset() is used to set the value of an SNMP object specified by the object_id.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

The SNMP object.

type

value

timeout

retries

Return Values

Returns TRUE on success or FALSE on failure.

See Also

snmpget()

Prev | Home | Next
snmprealwalk | Up | snmpwalk


snmpwalk

(PHP 3, PHP 4, PHP 5)

snmpwalk -- Fetch all the SNMP objects from an agent

Description

array snmpwalk ( string hostname, string community, string object_id [, int timeout [, int retries]] )

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

retries

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example 1. snmpwalk() Example

&#60;?php
$a = snmpwalk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?&#62;

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

snmpwalkoid()

Prev | Home | Next
snmpset | Up | snmpwalkoid


snmpwalkoid

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmpwalkoid -- Query for a tree of information about a network entity

Description

array snmpwalkoid ( string hostname, string community, string object_id [, int timeout [, int retries]] )

snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by hostname.

The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

retries

Return Values

Returns an associative array with object ids and their respective object value starting from the object_id as root or FALSE on error.

Examples

Example 1. snmpwalkoid() Example

&#60;?php
$a = snmpwalkoid("127.0.0.1", "public", "");
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]&#60;br /&#62;\n";
}
?&#62;

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

snmpwalk()

Prev | Home | Next
snmpwalk | Up | SOAP Functions


SOAP Functions

PHP Manual
Prev Next

CLI. SOAP Functions

Introduction

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of SOAP 1.1, SOAP 1.2 and WSDL 1.1 specifications.

Requirements

This extension makes use of the GNOME xml library. Download and install this library. You will need at least libxml-2.5.4.

Installation

This extension is only available if PHP was configured with --enable-soap.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. SOAP Configuration Options

Name | Default | Changeable | Changelog
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

soap.wsdl_cache_enabled boolean

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl int

Sets the number of seconds (time to live) that cached files will be used instead the originals.

Predefined Classes

SoapClient

Constructor

  • SoapClient->__construct() - constructs a new SoapClient object

Methods

  • SoapClient->__call() - Calls a SOAP function (deprecated)

  • SoapClient->__doRequest() - Performs a SOAP request

  • SoapClient->__getFunctions() - Returns list of SOAP functions

  • SoapClient->__getLastRequest() - Returns last SOAP request

  • SoapClient->__getLastRequestHeaders() - Returns last SOAP request headers

  • SoapClient->__getLastResponse() - Returns last SOAP response

  • SoapClient->__getLastResponseHeaders() - Returns last SOAP response headers

  • SoapClient->__getTypes() - Returns list of SOAP types

  • SoapClient->__setCookie() - Sets the cookie that will be sent with the SOAP request

  • SoapClient->__soapCall() - Calls a SOAP function

SoapFault

Constructor

  • SoapFault->__construct() - construct a new SoapFault object

SoapHeader

SoapHeader is a special low-level class for passing or returning SOAP headers. It's just a data holder and it does not have any special methods except its constructor. It can be used in the SoapClient->__soapCall() method to pass a SOAP header or in a SOAP header handler to return the header in a SOAP response.

Constructor

  • SoapHeader->__construct() - construct a new SoapHeader object

SoapParam

SoapParam is a special low-level class for naming parameters and returning values in non-WSDL mode. It's just a data holder and it does not have any special methods except its constructor.

Constructor

  • SoapParam->__construct() - construct a new SoapParam object

SoapServer

Constructor

  • SoapServer->__construct() - construct a new SoapServer object

Methods

  • SoapServer->addFunction() - Adds one or several functions those will handle SOAP requests

  • SoapServer->fault() -

  • SoapServer->getFunctions() - Returns list of defined functions

  • SoapServer->handle() - Handles a SOAP request

  • SoapServer->setClass() - Sets class which will handle SOAP requests

  • SoapServer->setPersistence() - Sets persistence mode of SoapServer

SoapVar

SoapVar is a special low-level class for encoding parameters and returning values in non-WSDL mode. It's just a data holder and does not have any special methods except the constructor. It's useful when you want to set the type property in SOAP request or response.

Constructor

  • SoapVar->__construct() - construct a new SoapVar object

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.

SOAP_1_1 (integer)

SOAP_1_2 (integer)

SOAP_PERSISTENCE_SESSION (integer)

SOAP_PERSISTENCE_REQUEST (integer)

SOAP_FUNCTIONS_ALL (integer)

SOAP_ENCODED (integer)

SOAP_LITERAL (integer)

SOAP_RPC (integer)

SOAP_DOCUMENT (integer)

SOAP_ACTOR_NEXT (integer)

SOAP_ACTOR_NONE (integer)

SOAP_ACTOR_UNLIMATERECEIVER (integer)

SOAP_COMPRESSION_ACCEPT (integer)

SOAP_COMPRESSION_GZIP (integer)

SOAP_COMPRESSION_DEFLATE (integer)

SOAP_WAIT_ONE_WAY_CALLS (integer)

Added in PHP 5.1.0.

UNKNOWN_TYPE (integer)

XSD_STRING (integer)

XSD_BOOLEAN (integer)

XSD_DECIMAL (integer)

XSD_FLOAT (integer)

XSD_DOUBLE (integer)

XSD_DURATION (integer)

XSD_DATETIME (integer)

XSD_TIME (integer)

XSD_DATE (integer)

XSD_GYEARMONTH (integer)

XSD_GYEAR (integer)

XSD_GMONTHDAY (integer)

XSD_GDAY (integer)

XSD_GMONTH (integer)

XSD_HEXBINARY (integer)

XSD_BASE64BINARY (integer)

XSD_ANYURI (integer)

XSD_ANYXML (integer)

Added in PHP 5.1.0.

XSD_QNAME (integer)

XSD_NOTATION (integer)

XSD_NORMALIZEDSTRING (integer)

XSD_TOKEN (integer)

XSD_LANGUAGE (integer)

XSD_NMTOKEN (integer)

XSD_NAME (integer)

XSD_NCNAME (integer)

XSD_ID (integer)

XSD_IDREF (integer)

XSD_IDREFS (integer)

XSD_ENTITY (integer)

XSD_ENTITIES (integer)

XSD_INTEGER (integer)

XSD_NONPOSITIVEINTEGER (integer)

XSD_NEGATIVEINTEGER (integer)

XSD_LONG (integer)

XSD_INT (integer)

XSD_SHORT (integer)

XSD_BYTE (integer)

XSD_NONNEGATIVEINTEGER (integer)

XSD_UNSIGNEDLONG (integer)

XSD_UNSIGNEDINT (integer)

XSD_UNSIGNEDSHORT (integer)

XSD_UNSIGNEDBYTE (integer)

XSD_POSITIVEINTEGER (integer)

XSD_NMTOKENS (integer)

XSD_ANYTYPE (integer)

SOAP_ENC_OBJECT (integer)

SOAP_ENC_ARRAY (integer)

XSD_1999_TIMEINSTANT (integer)

XSD_NAMESPACE (string)

XSD_1999_NAMESPACE (string)

Table of Contents
is_soap_fault -- Checks if SOAP call was failed
SoapClient->__call() -- Calls a SOAP function (deprecated)
SoapClient->__construct() -- SoapClient constructor
SoapClient->__doRequest() -- Performs a SOAP request
SoapClient->__getFunctions() -- Returns list of SOAP functions
SoapClient->__getLastRequest() -- Returns last SOAP request
SoapClient->__getLastRequestHeaders() -- Returns last SOAP request headers
SoapClient->__getLastResponse() -- Returns last SOAP response.
SoapClient->__getLastResponseHeaders() -- Returns last SOAP response headers.
SoapClient->__getTypes() -- Returns list of SOAP types
SoapClient->__setCookie() -- Sets the cookie that will be sent with the SOAP request
SoapClient->__soapCall() -- Calls a SOAP function
SoapFault->__construct() -- SoapFault constructor
SoapHeader->__construct() -- SoapHeader constructor
SoapParam->__construct() -- SoapParam constructor
SoapServer->addFunction() -- Adds one or several functions those will handle SOAP requests
SoapServer->__construct() -- SoapServer constructor
SoapServer->fault() -- Issue SoapServer fault indicating an error
SoapServer->getFunctions() -- Returns list of defined functions
SoapServer->handle() -- Handles a SOAP request
SoapServer->setClass() -- Sets class which will handle SOAP requests
SoapServer->setPersistence() -- Sets persistence mode of SoapServer
SoapVar->__construct() -- SoapVar constructor
use_soap_error_handler -- Set whether to use the SOAP error handler and return the former value

Prev | Home | Next
snmpwalkoid | Up | is_soap_fault


is_soap_fault

(PHP 5)

is_soap_fault -- Checks if SOAP call was failed

Description

bool is_soap_fault ( mixed obj )

This function is useful when you like to check if the SOAP call failed, but don't like to use exceptions. To use it you must create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

Parameters

obj

The tested object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. is_soap_fault() example

&#60;?php
$client = new SoapClient("some.wsdl", array('exceptions' =&#62; 0));
$result = $client-&#62;SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result-&#62;faultcode}, faultstring: {$result-&#62;faultstring})", E_USER_ERROR);
}
?&#62;

Example 2. SOAP's standard method for error reporting is exceptions

&#60;?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client-&#62;SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault-&#62;faultcode}, faultstring: {$fault-&#62;faultstring})", E_USER_ERROR);
}
?&#62;

See Also

SoapClient->__construct()
SoapFault->__construct()

Prev | Home | Next
SOAP Functions | Up | SoapClient->__call()


SoapClient->__call()

(no version information, might be only in CVS)

SoapClient->__call() -- Calls a SOAP function (deprecated)

Description

class SoapClient {

mixed __call ( string function_name, array arguments [, array options [, array input_headers [, array output_headers]]] )

}

This method is deprecated. Use SoapClient->__soapCall() instead of it.

Prev | Home | Next
is_soap_fault | Up | SoapClient->__construct()


SoapClient->__construct()

(no version information, might be only in CVS)

SoapClient->__construct() -- SoapClient constructor

Description

class SoapClient {

__construct ( mixed wsdl [, array options] )

}

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

Parameters

wsdl

URI of the WSDL file or NULL if working in non-WSDL mode.

Note: During development stage, you may want to disable WSDL caching by the mean of the soap.wsdl_cache_ttl php.ini setting, otherwise changes made to the WSDL file will have no effect until soap.wsdl_cache_ttl is expired.

options

An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, you must set the location and uri options, where location is the URL to request and uri is the target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.

The soap_version option specifies whether to use SOAP 1.1, or SOAP 1.2 client.

For HTTP authentication, you may use the login and password options. For making an HTTP connection through a proxy server, use the options proxy_host, proxy_port, proxy_login and proxy_password. For HTTPS client certificate authentication use local_cert and passphrase options.

The compression option allows to use compression of HTTP SOAP requests and responses.

The encoding option defines internal character encoding. This option does not change the encoding of SOAP requests (it is always utf-8), but converts strings into it.

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Setting the boolean trace option enables use of the
methods
SoapClient->__getLastRequest,

SoapClient->__getLastRequestHeaders,

SoapClient->__getLastResponse and

SoapClient->__getLastResponseHeaders.

The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.

The connection_timeout option defines a timeout in seconds for the connection to the SOAP service. This option does not define a timeout for services with slow responses. To limit the time to wait for calls to finish the default_socket_timeout setting is available.

Examples

Example 1. SoapClient examples

&#60;?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   =&#62; SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          =&#62; "some_name",
                                            'password'       =&#62; "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     =&#62; "localhost",
                                            'proxy_port'     =&#62; 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     =&#62; "localhost",
                                            'proxy_port'     =&#62; 8080,
                                            'proxy_login'    =&#62; "some_name",
                                            'proxy_password' =&#62; "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     =&#62; "cert_key.pem"));

$client = new SoapClient(null, array('location' =&#62; "http://localhost/soap.php",
                                     'uri'      =&#62; "http://test-uri/"));

$client = new SoapClient(null, array('location' =&#62; "http://localhost/soap.php",
                                     'uri'      =&#62; "http://test-uri/",
                                     'style'    =&#62; SOAP_DOCUMENT,
                                     'use'      =&#62; SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
  array('compression' =&#62; SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$server = new SoapClient("some.wsdl", array('encoding'=&#62;'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapClient("books.wsdl", array('classmap' =&#62; array('book' =&#62; "MyBook")));

?&#62;

Prev | Home | Next
SoapClient->__call() | Up | SoapClient->__doRequest()


SoapClient->__doRequest()

(no version information, might be only in CVS)

SoapClient->__doRequest() -- Performs a SOAP request

Description

class SoapClient {

string __doRequest ( string request, string location, string action, int version )

}

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

Parameters

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

version

The SOAP version.

Return Values

The XML SOAP response.

Examples

Example 1. Some examples

&#60;?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this-&#62;server = new SoapServer($wsdl, $options);
    $this-&#62;server-&#62;addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version) {
    ob_start();
    $this-&#62;server-&#62;handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=&#62;'test://',
                                   'uri'=&#62;'http://testuri.org'));
var_dump($x-&#62;Add(3,4));
?&#62;

Prev | Home | Next
SoapClient->__construct() | Up | SoapClient->__getFunctions()


SoapClient->__getFunctions()

(no version information, might be only in CVS)

SoapClient->__getFunctions() -- Returns list of SOAP functions

Description

class SoapClient {

array __getFunctions ( void )

}

Returns the list of SOAP functions.

Note: This function works only in WSDL mode.

Return Values

The list of SOAP functions.

Examples

Example 1. SoapClient->__getFunctions() example

&#60;?php
$client = new SoapClient('some.wsdl');
var_dump($client-&#62;__getFunctions());
?&#62;

See Also

SoapClient->__construct()

Prev | Home | Next
SoapClient->__doRequest() | Up | SoapClient->__getLastRequest()


SoapClient->__getLastRequest()

(no version information, might be only in CVS)

SoapClient->__getLastRequest() -- Returns last SOAP request

Description

class SoapClient {

string __getLastRequest ( void )

}

Note: This method works only if the SoapClient object was created with the trace option.

Return Values

The last SOAP request.

Examples

Example 1. SoapClient->__getLastRequest() example

&#60;?php
$client = SoapClient("some.wsdl", array('trace' =&#62; 1));
$result = $client-&#62;SomeFunction();
echo "REQUEST:\n" . $client-&#62;__getLastRequest() . "\n";
?&#62;

See Also

SoapClient->__construct()
SoapClient->__getLastRequestHeaders()
SoapClient->__getLastResponse()
SoapClient->__getLastResponseHeaders()

Prev | Home | Next
SoapClient->__getFunctions() | Up | SoapClient->__getLastRequestHeaders()


SoapClient->__getLastRequestHeaders()

(no version information, might be only in CVS)

SoapClient->__getLastRequestHeaders() -- Returns last SOAP request headers

Description

class SoapClient {

string __getLastRequestHeaders ( void )

}

Note: This method works only if the SoapClient object was created with the trace option.

Return Values

The last SOAP request headers.

See Also

SoapClient->__construct()
SoapClient->__getLastRequest()
SoapClient->__getLastResponse()
SoapClient->__getLastResponseHeaders()

Prev | Home | Next
SoapClient->__getLastRequest() | Up | SoapClient->__getLastResponse()


SoapClient->__getLastResponse()

(no version information, might be only in CVS)

SoapClient->__getLastResponse() -- Returns last SOAP response.

Description

class SoapClient {

string __getLastResponse ( void )

}

Note: This method works only if the SoapClient object was created with the trace option.

Return Values

The last SOAP response.

Examples

Example 1. SoapClient->__getLastResponse() example

&#60;?php
$client = SoapClient("some.wsdl", array('trace' =&#62; 1));
$result = $client-&#62;SomeFunction();
echo "RESPONSE:\n" . $client-&#62;__getLastResponse() . "\n";
?&#62;

See Also

SoapClient->__construct()
SoapClient->__getLastResponseHeaders()
SoapClient->__getLastRequest()
SoapClient->__getLastRequestHeaders()

Prev | Home | Next
SoapClient->__getLastRequestHeaders() | Up | SoapClient->__getLastResponseHeaders()


SoapClient->__getLastResponseHeaders()

(no version information, might be only in CVS)

SoapClient->__getLastResponseHeaders() -- Returns last SOAP response headers.

Description

class SoapClient {

string __getLastResponseHeaders ( void )

}

Note: This method works only if the SoapClient object was created with the trace option.

Return Values

The last SOAP response headers.

See Also

SoapClient->__construct()
SoapClient->__getLastResponse()
SoapClient->__getLastRequest()
SoapClient->__getLastRequestHeaders()

Prev | Home | Next
SoapClient->__getLastResponse() | Up | SoapClient->__getTypes()


SoapClient->__getTypes()

(no version information, might be only in CVS)

SoapClient->__getTypes() -- Returns list of SOAP types

Description

class SoapClient {

array __getTypes ( void )

}

This function works only in WSDL mode.

Return Values

The list of SOAP types.

Examples

Example 1. SoapClient->__getTypes() example

&#60;?php
$client = new SoapClient("some.wsdl");
var_dump($client-&#62;__getTypes());
?&#62;

See Also

SoapClient->__construct()

Prev | Home | Next
SoapClient->__getLastResponseHeaders() | Up | SoapClient->__setCookie()


SoapClient->__setCookie()

(no version information, might be only in CVS)

SoapClient->__setCookie() -- Sets the cookie that will be sent with the SOAP request

Description

class SoapClient {

void __setCookie ( string name [, string value] )

}

Defines a cookie to be sent along with the SOAP requests.

Note: Calling this method will affect all following calls to SoapClient methods.

Parameters

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

Return Values

No value is returned.

Prev | Home | Next
SoapClient->__getTypes() | Up | SoapClient->__soapCall()


SoapClient->__soapCall()

(no version information, might be only in CVS)

SoapClient->__soapCall() -- Calls a SOAP function

Description

class SoapClient {

mixed __soapCall ( string function_name, array arguments [, array options [, mixed input_headers [, array &output_headers]]] )

}

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, you can simply call SOAP functions as SoapClient methods. This method useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

Return Values

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.

Examples

Example 1. SoapClient->__soapCall() Examples

&#60;?php

$client = new SoapClient("some.wsdl");
$client-&#62;SomeFunction($a, $b, $c);

$client-&#62;__soapCall("SomeFunction", array($a, $b, $c));
$client-&#62;__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' =&#62; "http://localhost/soap.php",
                                     'uri'      =&#62; "http://test-uri/"));
$client-&#62;SomeFunction($a, $b, $c);
$client-&#62;__soapCall("SomeFunction", array($a, $b, $c));
$client-&#62;__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' =&#62; 'some_action',
                          'uri'        =&#62; 'some_uri'));
?&#62;

See Also

SoapClient->__construct()
SoapParam->__construct()
SoapVar->__construct()
SoapHeader->__construct()
SoapFault->__construct()
is_soap_fault()

Prev | Home | Next
SoapClient->__setCookie() | Up | SoapFault->__construct()


SoapFault->__construct()

(no version information, might be only in CVS)

SoapFault->__construct() -- SoapFault constructor

Description

class SoapFault {

__construct ( string faultcode, string faultstring [, string faultactor [, mixed detail [, string faultname [, SoapHeader headerfault]]]] )

}

This class is useful when you would like to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and details are standard elements of SOAP Fault;

Parameters

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

Examples

Example 1. Some examples

&#60;?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' =&#62; "http://test-uri/"));
$server-&#62;addFunction("test");
$server-&#62;handle();
?&#62;

It is possible to use PHP exception mechanism to throw SOAP Fault.

Example 2. Some examples

&#60;?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' =&#62; "http://test-uri/"));
$server-&#62;addFunction("test");
$server-&#62;handle();
?&#62;

See Also

SoapClient->__construct()
SoapClient->__soapCall()
SoapVar->__construct()
SoapParam->__construct()
SoapFault->__construct()
is_soap_fault()

Prev | Home | Next
SoapClient->__soapCall() | Up | SoapHeader->__construct()


SoapHeader->__construct()

(no version information, might be only in CVS)

SoapHeader->__construct() -- SoapHeader constructor

Description

class SoapHeader {

__construct ( string namespace, string name [, mixed data [, bool mustUnderstand [, mixed actor]]] )

}

Constructs a new SoapHeader object.

Parameters

namespace

The namespace of the SOAP header element.

name

The name of the SOAP header element.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

Examples

Example 1. Some examples

&#60;?php
$client = new SoapClient(null, array('location' =&#62; "http://localhost/soap.php",
                                     'uri'      =&#62; "http://test-uri/"));
$client-&#62;__call("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?&#62;

See Also

SoapClient->__soapCall()
SoapVar->__construct()
SoapParam->__construct()

Prev | Home | Next
SoapFault->__construct() | Up | SoapParam->__construct()


SoapParam->__construct()

(no version information, might be only in CVS)

SoapParam->__construct() -- SoapParam constructor

Description

class SoapParam {

__construct ( mixed data, string name )

}

Constructs a new SoapParam object.

Parameters

data

The data to pass or return. You can pass this parameter directly as PHP value, but in this case it will be named as paramN and the SOAP Service may not understand it.

name

The parameter name.

Examples

Example 1. Some examples

&#60;?php
$client = new SoapClient(null,array('location' =&#62; "http://localhost/soap.php",
                                    'uri'      =&#62; "http://test-uri/"));
$client-&#62;SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?&#62;

See Also

SoapClient->__soapCall()
SoapVar->__construct()

Prev | Home | Next
SoapHeader->__construct() | Up | SoapServer->addFunction()


SoapServer->addFunction()

(no version information, might be only in CVS)

SoapServer->addFunction() -- Adds one or several functions those will handle SOAP requests

Description

class SoapServer {

void addFunction ( mixed functions )

}

Exports one or more functions for remote clients.

Parameters

functions

To export one function, pass the function name into this parameter as a string.

To export several functions, pass an array of function names.

To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.

Note: functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.

Return Values

No value is returned.

Examples

Example 1. Some examples

&#60;?php

function echoString($inputString)
{
    return $inputString;
}

$server-&#62;addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" =&#62; $inputString1,
                 "outputString2" =&#62; $inputString2);
}
$server-&#62;addFunction(array("echoString", "echoTwoStrings"));

$server-&#62;addFunction(SOAP_FUNCTIONS_ALL);

?&#62;

See Also

SoapServer->__construct()
SoapServer->setClass()

Prev | Home | Next
SoapParam->__construct() | Up | SoapServer->__construct()


SoapServer->__construct()

(no version information, might be only in CVS)

SoapServer->__construct() -- SoapServer constructor

Description

class SoapServer {

__construct ( mixed wsdl [, array options] )

}

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Parameters

wsdl

If you want the WSDL mode, you must set this to the URI of a WSDL file. In the other case, you must set this to NULL and set the uri option.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor). The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Examples

Example 1. Some examples

&#60;?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' =&#62; SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' =&#62; "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=&#62;'ISO-8859-1'));

$server = new SoapServer(null, array('uri' =&#62; "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' =&#62; array('book' =&#62; "MyBook")));

?&#62;

Prev | Home | Next
SoapServer->addFunction() | Up | SoapServer->fault()


SoapServer->fault()

(no version information, might be only in CVS)

SoapServer->fault() -- Issue SoapServer fault indicating an error

Description

class SoapServer {

void fault ( string code, string string [, string actor [, mixed details [, string name]]] )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SoapFault->__construct()

Prev | Home | Next
SoapServer->__construct() | Up | SoapServer->getFunctions()


SoapServer->getFunctions()

(no version information, might be only in CVS)

SoapServer->getFunctions() -- Returns list of defined functions

Description

class SoapServer {

array getFunctions ( void )

}

This method returns the list of all functions added by SoapServer->addFunction() or SoapServer->setClass().

Return Values

The list of all functions.

Examples

Example 1. Some examples

&#60;?php
$server = new SoapServer(NULL, array("uri" =&#62; "http://test-uri"));
$server-&#62;addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server-&#62;handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server-&#62;getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?&#62;

See Also

SoapServer->__construct()
SoapServer->addFunction()
SoapServer->setClass()

Prev | Home | Next
SoapServer->fault() | Up | SoapServer->handle()


SoapServer->handle()

(no version information, might be only in CVS)

SoapServer->handle() -- Handles a SOAP request

Description

class SoapServer {

void handle ( [string soap_request] )

}

Processes a SOAP request, calls necessary functions, and sends a response back.

Parameters

soap_request

The SOAP request. If this argument is omitted, the request is supposed to be in the $HTTP_RAW_POST_DATA PHP variable.

Return Values

No value is returned.

Examples

Example 1. Some examples

&#60;?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' =&#62; "http://test-uri/"));
$server-&#62;addFunction("test");
$server-&#62;handle();
?&#62;

See Also

SoapServer->__construct()

Prev | Home | Next
SoapServer->getFunctions() | Up | SoapServer->setClass()


SoapServer->setClass()

(no version information, might be only in CVS)

SoapServer->setClass() -- Sets class which will handle SOAP requests

Description

class SoapServer {

void setClass ( string class_name [, mixed args [, mixed ...]] )

}

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer->setPersistence() method.

Parameters

class_name

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

Return Values

No value is returned.

Examples

Example 1. Some examples

&#60;?php

class foo {
    function foo()
    {
    }
}
$server-&#62;setClass("foo");

class bar {
    function bar($x, $y)
    {
    }
}
$server-&#62;setClass("bar", $arg1, $arg2);

?&#62;

See Also

SoapServer->__construct()
SoapServer->addFunction()
SoapServer->setPersistence()

Prev | Home | Next
SoapServer->handle() | Up | SoapServer->setPersistence()


SoapServer->setPersistence()

(no version information, might be only in CVS)

SoapServer->setPersistence() -- Sets persistence mode of SoapServer

Description

class SoapServer {

void setPersistence ( int mode )

}

This function allows saving data between requests in a PHP session. It works only with a server that exports functions from a class with SoapServer->setClass().

Parameters

mode

One of the SOAP_PERSISTENCE_XXX constants.

Return Values

No value is returned.

Examples

Example 1. Some examples

&#60;?php

$server-&#62;setPersistence(SOAP_PERSISTENCE_SESSION);

$server-&#62;setPersistence(SOAP_PERSISTENCE_REQUEST);

?&#62;

Note: The persistence SOAP_PERSISTENCE_SESSION makes persistent only object of given class, but not the class static data. You may use $this->bar instead of self::$bar.

See Also

SoapServer->__construct()
SoapServer->setClass()

Prev | Home | Next
SoapServer->setClass() | Up | SoapVar->__construct()


SoapVar->__construct()

(no version information, might be only in CVS)

SoapVar->__construct() -- SoapVar constructor

Description

class SoapVar {

__construct ( mixed data, int encoding [, string type_name [, string type_namespace [, string node_name [, string node_namespace]]]] )

}

Constructs a new SoapVar object.

Parameters

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

Examples

Example 1. Some examples

&#60;?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this-&#62;varString = $s;
        $this-&#62;varInt = $i;
        $this-&#62;varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' =&#62; "http://localhost/soap.php",
                                     'uri'      =&#62; "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client-&#62;echoStruct(new SoapParam($soapstruct, "inputStruct"));
?&#62;

See Also

SoapClient->__soapCall()
SoapParam->__construct()

Prev | Home | Next
SoapServer->setPersistence() | Up | use_soap_error_handler


use_soap_error_handler

(PHP 5)

use_soap_error_handler -- Set whether to use the SOAP error handler and return the former value

Description

bool use_soap_error_handler ( [bool handler] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SoapVar->__construct() | Up | Socket Functions


Socket Functions

PHP Manual
Prev Next

CLII. Socket Functions

Introduction

The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.

For a more generic client-side socket interface, see
stream_socket_client(),
stream_socket_server(),
fsockopen(), and
pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The Unix Socket FAQ might be a good start.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

Requirements

No external libraries are needed to build this extension.

Installation

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

Note: IPv6 Support was added with PHP 5.0.0.

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.

AF_UNIX (integer)

AF_INET (integer)

AF_INET6 (integer)

SOCK_STREAM (integer)

SOCK_DGRAM (integer)

SOCK_RAW (integer)

SOCK_SEQPACKET (integer)

SOCK_RDM (integer)

MSG_OOB (integer)

MSG_WAITALL (integer)

MSG_PEEK (integer)

MSG_DONTROUTE (integer)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)

Socket Errors

The socket extension was written to provide a usable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn't happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It's common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.

Note: The E_WARNING messages generated by the socket extension are in English though the retrieved error message will appear depending on the current locale (LC_MESSAGES):

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

Examples

Example 1. Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

#!/usr/local/bin/php -q
&#60;?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?&#62;

Example 2. Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

&#60;?php
error_reporting(E_ALL);

echo "&#60;h2&#62;TCP/IP Connection&#60;/h2&#62;\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?&#62;

Table of Contents
socket_accept -- Accepts a connection on a socket
socket_bind -- Binds a name to a socket
socket_clear_error -- Clears the error on the socket or the last error code
socket_close -- Closes a socket resource
socket_connect -- Initiates a connection on a socket
socket_create_listen -- Opens a socket on port to accept connections
socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in an array
socket_create -- Create a socket (endpoint for communication)
socket_get_option -- Gets socket options for the socket
socket_getpeername -- Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
socket_getsockname -- Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
socket_last_error -- Returns the last error on the socket
socket_listen -- Listens for a connection on a socket
socket_read -- Reads a maximum of length bytes from a socket
socket_recv -- Receives data from a connected socket
socket_recvfrom -- Receives data from a socket, connected or not
socket_select -- Runs the select() system call on the given arrays of sockets with a specified timeout
socket_send -- Sends data to a connected socket
socket_sendto -- Sends a message to a socket, whether it is connected or not
socket_set_block -- Sets blocking mode on a socket resource
socket_set_nonblock -- Sets nonblocking mode for file descriptor fd
socket_set_option -- Sets socket options for the socket
socket_shutdown -- Shuts down a socket for receiving, sending, or both
socket_strerror -- Return a string describing a socket error
socket_write -- Write to a socket

Prev | Home | Next
use_soap_error_handler | Up | socket_accept


socket_accept

(PHP 4 >= 4.1.0, PHP 5)

socket_accept -- Accepts a connection on a socket

Description

resource socket_accept ( resource socket )

After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned.

The socket resource returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.

Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_bind(),
socket_connect(),
socket_listen(),
socket_create(), and
socket_strerror().

Prev | Home | Next
Socket Functions | Up | socket_bind


socket_bind

(PHP 4 >= 4.1.0, PHP 5)

socket_bind -- Binds a name to a socket

Description

bool socket_bind ( resource socket, string address [, int port] )

Binds the name given in address to the socket described by socket. This has to be done before a connection can be established using socket_connect() or socket_listen().

Parameters

socket

A valid socket resource created with socket_create().

address

If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).

If the socket is of the AF_UNIX family, the address is the path of a Unix-domain socket (e.g. /tmp/my.sock).

port (Optional)

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

Return Values

Returns TRUE on success or FALSE on failure.

The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Examples

Example 1. Using socket_bind() to set the source address

&#60;?php
// Create a new socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// An example list of IP addresses owned by the computer
$sourceips['kevin']    = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// Bind the source address
socket_bind($sock, $sourceips['madcoder']);

// Connect to destination address
socket_connect($sock, '127.0.0.1', 80);

// Write
$request = 'GET / HTTP/1.1' . "\r\n" .
           'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// Close
socket_close($sock);

?&#62;

Notes

Note: This function must be used on the socket before socket_connect().

Note: Windows 9x/ME compatibility note: socket_last_error() may return an invalid error code if trying to bind the socket to a wrong address that does not belong to your machine.

See Also

socket_connect()
socket_listen()
socket_create()
socket_last_error()
socket_strerror()

Prev | Home | Next
socket_accept | Up | socket_clear_error


socket_clear_error

(PHP 4 >= 4.2.0, PHP 5)

socket_clear_error -- Clears the error on the socket or the last error code

Description

void socket_clear_error ( [resource socket] )

This function clears the error code on the given socket or the global last socket error.

This function allows explicitly resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occurred or not.

See also socket_last_error() and socket_strerror().

Prev | Home | Next
socket_bind | Up | socket_close


socket_close

(PHP 4 >= 4.1.0, PHP 5)

socket_close -- Closes a socket resource

Description

void socket_close ( resource socket )

socket_close() closes the socket resource given by socket.

Note: socket_close() can't be used on PHP file resources created with fopen(), popen(), fsockopen(), or pfsockopen(); it is meant for sockets created with socket_create() or socket_accept().

See also socket_bind(), socket_listen(),
socket_create() and
socket_strerror().

Prev | Home | Next
socket_clear_error | Up | socket_connect


socket_connect

(PHP 4 >= 4.1.0, PHP 5)

socket_connect -- Initiates a connection on a socket

Description

bool socket_connect ( resource socket, string address [, int port] )

Initiates a connection using the socket resource socket, which must be a valid socket resource created with socket_create().

The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix domain socket, if the socket family is AF_UNIX.

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

Returns TRUE on success or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_bind(),
socket_listen(),
socket_create(),
socket_last_error() and
socket_strerror().

Prev | Home | Next
socket_close | Up | socket_create_listen


socket_create_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_create_listen -- Opens a socket on port to accept connections

Description

resource socket_create_listen ( int port [, int backlog] )

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

socket_create_listen() creates a new socket resource of type AF_INET listening on all local interfaces on the given port waiting for new connections.

The backlog parameter defines the maximum length the queue of pending connections may grow to. SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.

socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Note: If you want to create a socket which only listens on a certain interface you need to use socket_create(), socket_bind() and socket_listen().

See also
socket_create(),
socket_bind(),
socket_listen(),
socket_last_error() and
socket_strerror().

Prev | Home | Next
socket_connect | Up | socket_create_pair


socket_create_pair

(PHP 4 >= 4.1.0, PHP 5)

socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in an array

Description

bool socket_create_pair ( int domain, int type, int protocol, array &fd )

socket_create_pair() creates two connected and indistinguishable sockets, and stores them in fd. This function is commonly used in IPC (InterProcess Communication).

The domain parameter specifies the protocol family to be used by the socket.

Table 1. Available address/protocol families

Domain | Description
AF_INET | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. Supported only in windows.
AF_INET6 | IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. Support added in PHP 5.0.0. Supported only in windows.
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

Table 2. Available socket types

Type | Description
SOCK_STREAM | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAM | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKET | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAW | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping, traceroute, etc).
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

Table 3. Common protocols

Name | Description
icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

Example 1. socket_create_pair() example

&#60;?php
$sockets = array();
/* Setup socket pair */
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?&#62;

Example 2. socket_create_pair() IPC example

&#60;?php
$ary = array();
$strone = 'Message From Parent.';
$strtwo = 'Message From Child.';
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {
    echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error());
}
$pid = pcntl_fork();
if ($pid == -1) {
    echo 'Could not fork Process.';
} elseif ($pid) {
    /*parent*/
    socket_close($ary[0]);
    if (socket_write($ary[1], $strone, strlen($strone)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));
    }
    if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {
        echo "Recieved $strtwo\n";
    }
    socket_close($ary[1]);
} else {
    /*child*/
    socket_close($ary[1]);
    if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));
    }
    if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {
        echo "Recieved $strone\n";
    }
    socket_close($ary[0]);
}
?&#62;

Prev | Home | Next
socket_create_listen | Up | socket_create


socket_create

(PHP 4 >= 4.1.0, PHP 5)

socket_create -- Create a socket (endpoint for communication)

Description

resource socket_create ( int domain, int type, int protocol )

Creates and returns a socket resource, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server.

The domain parameter specifies the protocol family to be used by the socket.

Table 1. Available address/protocol families

Domain | Description
AF_INET | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_INET6 | IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. Support added in PHP 5.0.0.
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

Table 2. Available socket types

Type | Description
SOCK_STREAM | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAM | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKET | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAW | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping, traceroute, etc).
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

Table 3. Common protocols

Name | Description
icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

socket_create() Returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Note: If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_last_error(), and
socket_strerror().

Prev | Home | Next
socket_create_pair | Up | socket_get_option


socket_get_option

(PHP 4 >= 4.3.0, PHP 5)

socket_get_option -- Gets socket options for the socket

Description

mixed socket_get_option ( resource socket, int level, int optname )

The socket_get_option() function retrieves the value for the option specified by the optname parameter for the socket specified by the socket parameter. socket_get_option() will return FALSE on failure.

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

Table 1. Available Socket Options

Option | Description
SO_DEBUG | Reports whether debugging information is being recorded.
SO_ACCEPTCONN | Reports whether socket listening is enabled.
SO_BROADCAST | Reports whether transmission of broadcast messages is supported.
SO_REUSEADDR | Reports whether local addresses can be reused.
SO_KEEPALIVE | Reports whether connections are kept active with periodic transmission of messages. If the connected socket fails to respond to these messages, the connection is broken and processes writing to that socket are notified with a SIGPIPE signal.
SO_LINGER | Reports whether the socket lingers on socket_close() if data is present.
SO_OOBINLINE | Reports whether the socket leaves out-of-band data inline.
SO_SNDBUF | Reports send buffer size information.
SO_RCVBUF | Reports recieve buffer size information.
SO_ERROR | Reports information about error status and clears it.
SO_TYPE | Reports the socket type.
SO_DONTROUTE | Reports whether outgoing messages bypass the standard routing facilities.
SO_RCVLOWAT | Reports the minimum number of bytes to process for socket input operations. ( Defaults to 1 )
SO_RCVTIMEO | Reports the timeout value for input operations.
SO_SNDLOWAT | Reports the minimum number of bytes to process for socket output operations.
SO_SNDTIMEO | Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent.

Note: This function used to be called socket_getopt() prior to PHP 4.3.0

Prev | Home | Next
socket_create | Up | socket_getpeername


socket_getpeername

(PHP 4 >= 4.1.0, PHP 5)

socket_getpeername -- Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Description

bool socket_getpeername ( resource socket, string &addr [, int &port] )

If the given socket is of type AF_INET or AF_INET6, socket_getpeername() will return the peers (remote) IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getpeername() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

Note: socket_getpeername() should not be used with AF_UNIX sockets created with socket_accept(). Only sockets created with socket_connect() or a primary server socket following a call to socket_bind() will return meaningful values.

Returns TRUE on success or FALSE on failure. socket_getpeername() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

See also
socket_getsockname(),
socket_last_error() and
socket_strerror().

Prev | Home | Next
socket_get_option | Up | socket_getsockname


socket_getsockname

(PHP 4 >= 4.1.0, PHP 5)

socket_getsockname -- Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Description

bool socket_getsockname ( resource socket, string &addr [, int &port] )

If the given socket is of type AF_INET or AF_INET6, socket_getsockname() will return the local IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getsockname() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

Note: socket_getsockname() should not be used with AF_UNIX sockets created with socket_connect(). Only sockets created with socket_accept() or a primary server socket following a call to socket_bind() will return meaningful values.

Returns TRUE on success or FALSE on failure. socket_getsockname() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

See also
socket_getpeername(),
socket_last_error() and
socket_strerror().

Prev | Home | Next
socket_getpeername | Up | socket_last_error


socket_last_error

(PHP 4 >= 4.1.0, PHP 5)

socket_last_error -- Returns the last error on the socket

Description

int socket_last_error ( [resource socket] )

This function returns a socket error code.

If a socket resource is passed to this function, the last error which occurred on this particular socket is returned. If the socket resource is omitted, the error code of the last failed socket function is returned. The latter is in particular helpful for functions like socket_create() which don't return a socket on failure and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to socket_strerror() which returns a string describing the given error code.

&#60;?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
    die("Couldn't create socket, error code is: " . socket_last_error() .
        ",error message is: " . socket_strerror(socket_last_error()));
}
?&#62;

Note: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

Prev | Home | Next
socket_getsockname | Up | socket_listen


socket_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_listen -- Listens for a connection on a socket

Description

bool socket_listen ( resource socket [, int backlog] )

After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket.

A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.

Note: The maximum number passed to the backlog parameter highly depends on the underlying platform. On Linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

Returns TRUE on success or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_create() and
socket_strerror().

Prev | Home | Next
socket_last_error | Up | socket_read


socket_read

(PHP 4 >= 4.1.0, PHP 5)

socket_read -- Reads a maximum of length bytes from a socket

Description

string socket_read ( resource socket, int length [, int type] )

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions. The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.

Note: socket_read() returns a zero length string ("") when there is no more data to read.

Optional type parameter is a named constant:

  • PHP_BINARY_READ - use the system recv() function. Safe for reading binary data. (Default in PHP >= 4.1.0)

  • PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_last_error(),
socket_strerror() and
socket_write().

Prev | Home | Next
socket_listen | Up | socket_recv


socket_recv

(PHP 4 >= 4.1.0, PHP 5)

socket_recv -- Receives data from a connected socket

Description

int socket_recv ( resource socket, string &buf, int len, int flags )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
socket_read | Up | socket_recvfrom


socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5)

socket_recvfrom -- Receives data from a socket, connected or not

Description

int socket_recvfrom ( resource socket, string &buf, int len, int flags, string &name [, int &port] )

Warning

This function is currently not documented; only the argument list is available.

socket_recvfrom() has been binary safe since PHP 4.3.0

Prev | Home | Next
socket_recv | Up | socket_select


socket_select

(PHP 4 >= 4.1.0, PHP 5)

socket_select -- Runs the select() system call on the given arrays of sockets with a specified timeout

Description

int socket_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec] )

socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.

The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).

The sockets listed in the write array will be watched to see if a write will not block.

The sockets listed in the except array will be watched for exceptions.

Warning

On exit, the arrays are modified to indicate which socket resource actually changed status.

You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.

Example 1. socket_select() example

&#60;?php
/* Prepare the read array */
$read   = array($socket1, $socket2);
$write  = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if ($num_changed_sockets === false) {
    /* Error handling */
} else if ($num_changed_sockets &#62; 0) {
    /* At least at one of the sockets something interesting happened */
}
?&#62;

Note: Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

Example 2. Using NULL with socket_select()

&#60;?php
$e = NULL;
socket_select($r, $w, $e, 0);
?&#62;

The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.

On success socket_select() returns the number of socket resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().

Note: Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:

Example 3. Understanding socket_select()'s result

&#60;?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
    echo "socket_select() failed, reason: " .
        socket_strerror(socket_last_error()) . "\n";
}
?&#62;

Note: Be aware that some socket implementations need to be handled very carefully. A few basic rules:

  • You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.

  • No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.

  • If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

  • It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.

See also
socket_read(),
socket_write(),
socket_last_error() and
socket_strerror().

Prev | Home | Next
socket_recvfrom | Up | socket_send


socket_send

(PHP 4 >= 4.1.0, PHP 5)

socket_send -- Sends data to a connected socket

Description

int socket_send ( resource socket, string buf, int len, int flags )

The function socket_send() sends len bytes to the socket socket from buf

The value of flags can be any ORed combination of the following:

Table 1. possible values for flags

0x1 | Process OOB (out-of-band) data
0x2 | Peek at incoming message
0x4 | Bypass routing, use direct interface
0x8 | Data completes record
0x100 | Data completes transaction

See also socket_sendmsg() and socket_sendto().

Prev | Home | Next
socket_select | Up | socket_sendto


socket_sendto

(PHP 4 >= 4.1.0, PHP 5)

socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int socket_sendto ( resource socket, string buf, int len, int flags, string addr [, int port] )

The function socket_sendto() sends len bytes from buf through the socket socket to the port at the address addr

The value of flags can be one of the following:

Table 1. possible values for flags

0x1 | Process OOB (out-of-band) data.
0x2 | Peek at incoming message.
0x4 | Bypass routing, use direct interface.
0x8 | Data completes record.
0x100 | Data completes transaction.

Example 1. socket_sendto() Example

&#60;?php
    $sh = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (socket_bind($sh, '127.0.0.1', 4242)) {
        echo "Socket bound correctly";
    }
    $buf = 'Test Message';
    $len = strlen($buf);
    if (socket_sendto($sh, $buf, $len, 0x100, '192.168.0.2', 4242) !== false) {
        echo "Message sent correctly";
    }
    socket_close($sh);
?&#62;

See also socket_send() and socket_sendmsg().

Prev | Home | Next
socket_send | Up | socket_set_block


socket_set_block

(PHP 4 >= 4.2.0, PHP 5)

socket_set_block -- Sets blocking mode on a socket resource

Description

bool socket_set_block ( resource socket )

The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.

Example 1. socket_set_block() example

&#60;?php

$port = 9090;
if (($socket = socket_create_listen($port)) === false) {
    echo "socket_create_listen() failed. Reason: ".socket_strerror(socket_last_error());
}

if (socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1) === false) {
    echo "socket_set_option() failed. Reason: ".socket_strerror(socket_last_error($socket));
}

if (socket_set_nonblock($socket) === false) { // $socket is now nonblocking
    echo "socket_set_nonblock() failed. Reason: ".socket_strerror(socket_last_error($socket));
}

if (socket_set_block($socket) === false) {     // $socket is now blocking
    echo "socket_set_block() failed. Reason: ". socket_strerror(socket_last_error($socket));
}

?&#62;

Returns TRUE on success or FALSE on failure.

See also socket_set_nonblock() and socket_set_option()

Prev | Home | Next
socket_sendto | Up | socket_set_nonblock


socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5)

socket_set_nonblock -- Sets nonblocking mode for file descriptor fd

Description

bool socket_set_nonblock ( resource socket )

The socket_set_nonblock() function sets the O_NONBLOCK flag on the socket specified by the socket parameter.

Example 1. socket_set_nonblock() example

&#60;?php
$port = 9090;
if (($socket = socket_create_listen($port)) === false) {
    echo "socket_create_listen() failed. Reason: ".socket_strerror(socket_last_error());
}

if (socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1) === false) {
    echo "socket_set_option() failed. Reason: ".socket_strerror(socket_last_error($socket));
}

if (socket_set_nonblock($socket) === false) {
    echo "socket_set_nonblock() failed. Reason: ".socket_strerror(socket_last_error($socket));
}
?&#62;

Returns TRUE on success or FALSE on failure.

See also socket_set_block() and socket_set_option()

Prev | Home | Next
socket_set_block | Up | socket_set_option


socket_set_option

(PHP 4 >= 4.3.0, PHP 5)

socket_set_option -- Sets socket options for the socket

Description

bool socket_set_option ( resource socket, int level, int optname, mixed optval )

The socket_set_option() function sets the option specified by the optname parameter, at the protocol level specified by the level parameter, to the value pointed to by the optval parameter for the socket specified by the socket parameter. socket_set_option() will return FALSE on failure.

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

The available socket options are the same as those for the socket_get_option() function.

Note: This function used to be called socket_setopt() prior to PHP 4.3.0.

Prev | Home | Next
socket_set_nonblock | Up | socket_shutdown


socket_shutdown

(PHP 4 >= 4.1.0, PHP 5)

socket_shutdown -- Shuts down a socket for receiving, sending, or both

Description

bool socket_shutdown ( resource socket [, int how] )

The socket_shutdown() function allows you to stop incoming, outgoing or all data (the default) from being sent through the socket

The value of how can be one of the following:

Table 1. possible values for how

0 | Shutdown socket reading
1 | Shutdown socket writing
2 | Shutdown socket reading and writing

Prev | Home | Next
socket_set_option | Up | socket_strerror


socket_strerror

(PHP 4 >= 4.1.0, PHP 5)

socket_strerror -- Return a string describing a socket error

Description

string socket_strerror ( int errno )

socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why something didn't work; for instance, instead of having to track down a system include file to find out what '-111' means, you just pass it to socket_strerror(), and it tells you what happened.

Example 1. socket_strerror() example

&#60;?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
   echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (false == (@socket_bind($socket, '127.0.0.1', 80))) {
   echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
?&#62;

The expected output from the above example (assuming the script is not run with root privileges):

socket_bind() failed: reason: Permission denied

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(), and
socket_create().

Prev | Home | Next
socket_shutdown | Up | socket_write


socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_write -- Write to a socket

Description

int socket_write ( resource socket, string buffer [, int length] )

The function socket_write() writes to the socket socket from buffer.

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.

Returns the number of bytes successfully written to the socket or FALSE one error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Note: socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

Note: It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_read() and
socket_strerror().

Prev | Home | Next
socket_strerror | Up | Standard PHP Library (SPL) Functions


Standard PHP Library (SPL) Functions

PHP Manual
Prev Next

CLIII. Standard PHP Library (SPL) Functions

Introduction

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Tip: A more detailed documentation of SPL can be found here.

Installation

This extension is available and compiled by default in PHP 5.

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.

Warning

SPL uses class constants since PHP 5.1. Prior releases use global constants in the form RIT_LEAVES_ONLY.

RecursiveIteratorIterator::LEAVES_ONLY (integer)

RecursiveIteratorIterator::SELF_FIRST (integer)

RecursiveIteratorIterator::CHILD_FIRST (integer)

CachingIterator::CALL_TOSTRING (integer)

CachingIterator::CATCH_GET_CHILD (integer)

Table of Contents
ArrayIterator::current -- Return current array entry
ArrayIterator::key -- Return current array key
ArrayIterator::next -- Move to next entry
ArrayIterator::rewind -- Rewind array back to the start
ArrayIterator::seek -- Seek to position
ArrayIterator::valid -- Check whether array contains more entries
ArrayObject::append -- Appends the value
ArrayObject::__construct -- Construct a new array object
ArrayObject::count -- Return the number of elements in the Iterator
ArrayObject::getIterator -- Create a new iterator from an ArrayObject instance
ArrayObject::offsetExists -- Returns whether the requested $index exists
ArrayObject::offsetGet -- Returns the value at the specified $index
ArrayObject::offsetSet -- Sets the value at the specified $index to $newval
ArrayObject::offsetUnset -- Unsets the value at the specified $index
CachingIterator::hasNext -- Check whether the inner iterator has a valid next element
CachingIterator::next -- Move the iterator forward
CachingIterator::rewind -- Rewind the iterator
CachingIterator::__toString -- Return the string representation of the current element
CachingIterator::valid -- Check whether the current element is valid
CachingRecursiveIterator::getChildren -- Return the inner iterator's children as a CachingRecursiveIterator
CachingRecursiveIterator::hasChildren -- Check whether the current element of the inner iterator has children
DirectoryIterator::__construct -- Constructs a new dir iterator from a path
DirectoryIterator::current -- Return this (needed for Iterator interface)
DirectoryIterator::getATime -- Get last access time of file
DirectoryIterator::getCTime -- Get inode modification time of file
DirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directory
DirectoryIterator::getFilename -- Return filename of current dir entry
DirectoryIterator::getGroup -- Get file group
DirectoryIterator::getInode -- Get file inode
DirectoryIterator::getMTime -- Get last modification time of file
DirectoryIterator::getOwner -- Get file owner
DirectoryIterator::getPath -- Return directory path
DirectoryIterator::getPathname -- Return path and filename of current dir entry
DirectoryIterator::getPerms -- Get file permissions
DirectoryIterator::getSize -- Get file size
DirectoryIterator::getType -- Get file type
DirectoryIterator::isDir -- Returns true if file is directory
DirectoryIterator::isDot -- Returns true if current entry is '.' or '..'
DirectoryIterator::isExecutable -- Returns true if file is executable
DirectoryIterator::isFile -- Returns true if file is a regular file
DirectoryIterator::isLink -- Returns true if file is symbolic link
DirectoryIterator::isReadable -- Returns true if file can be read
DirectoryIterator::isWritable -- Returns true if file can be written
DirectoryIterator::key -- Return current dir entry
DirectoryIterator::next -- Move to next entry
DirectoryIterator::rewind -- Rewind dir back to the start
DirectoryIterator::valid -- Check whether dir contains more entries
FilterIterator::current -- Get the current element value
FilterIterator::getInnerIterator -- Get the inner iterator
FilterIterator::key -- Get the current key
FilterIterator::next -- Move the iterator forward
FilterIterator::rewind -- Rewind the iterator
FilterIterator::valid -- Check whether the current element is valid
LimitIterator::getPosition -- Return the current position
LimitIterator::next -- Move the iterator forward
LimitIterator::rewind -- Rewind the iterator to the specified starting offset
LimitIterator::seek -- Seek to the given position
LimitIterator::valid -- Check whether the current element is valid
ParentIterator::getChildren -- Return the inner iterator's children contained in a ParentIterator
ParentIterator::hasChildren -- Check whether the inner iterator's current element has children
ParentIterator::next -- Move the iterator forward
ParentIterator::rewind -- Rewind the iterator
RecursiveDirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directory
RecursiveDirectoryIterator::hasChildren -- Returns whether current entry is a directory and not '.' or '..'
RecursiveDirectoryIterator::key -- Return path and filename of current dir entry
RecursiveDirectoryIterator::next -- Move to next entry
RecursiveDirectoryIterator::rewind -- Rewind dir back to the start
RecursiveIteratorIterator::current -- Access the current element value
RecursiveIteratorIterator::getDepth -- Get the current depth of the recursive iteration
RecursiveIteratorIterator::getSubIterator -- The current active sub iterator
RecursiveIteratorIterator::key -- Access the current key
RecursiveIteratorIterator::next -- Move forward to the next element
RecursiveIteratorIterator::rewind -- Rewind the iterator to the first element of the top level inner iterator
RecursiveIteratorIterator::valid -- Check whether the current position is valid
SimpleXMLIterator::current -- Return current SimpleXML entry
SimpleXMLIterator::getChildren -- Returns an iterator for the current entry if it is a SimpleXML object
SimpleXMLIterator::hasChildren -- Returns whether current entry is a SimpleXML object
SimpleXMLIterator::key -- Return current SimpleXML key
SimpleXMLIterator::next -- Move to next entry
SimpleXMLIterator::rewind -- Rewind SimpleXML back to the start
SimpleXMLIterator::valid -- Check whether SimpleXML contains more entries
class_implements -- Return the interfaces which are implemented by the given class
class_parents -- Return the parent classes of the given class
iterator_count -- Count the elements in an iterator
iterator_to_array -- Copy the iterator into an array
spl_autoload_call -- Try all registered __autoload() function to load the requested class
spl_autoload_extensions -- Register and return default file extensions for spl_autoload
spl_autoload_functions -- Return all registered __autoload() functions
spl_autoload_register -- Register given function as __autoload() implementation
spl_autoload_unregister -- Unregister given function as __autoload() implementation
spl_autoload -- Default implementation for __autoload()
spl_classes -- Return available SPL classes
spl_object_hash -- Return hash id for given object

Prev | Home | Next
socket_write | Up | ArrayIterator::current


ArrayIterator::current

(no version information, might be only in CVS)

ArrayIterator::current -- Return current array entry

Description

mixed ArrayIterator::current ( void )

This function returns the current array entry

Example 1. ArrayIterator::current() example

&#60;?php
$array = array('1' =&#62; 'one',
               '2' =&#62; 'two',
               '3' =&#62; 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject-&#62;getIterator();
    $iterator-&#62;valid();
    $iterator-&#62;next()) {

    echo $iterator-&#62;key() . ' =&#62; ' . $iterator-&#62;current() . "\n";
}
?&#62;

The above example will output:

1 => one
2 => two
3 => three

Prev | Home | Next
Standard PHP Library (SPL) Functions | Up | ArrayIterator::key


ArrayIterator::key

(no version information, might be only in CVS)

ArrayIterator::key -- Return current array key

Description

mixed ArrayIterator::key ( void )

This function returns the current array key

Example 1. ArrayIterator::key() example

&#60;?php
$array = array('key' =&#62; 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject-&#62;getIterator();

echo $iterator-&#62;key(); //key
?&#62;

Prev | Home | Next
ArrayIterator::current | Up | ArrayIterator::next


ArrayIterator::next

(no version information, might be only in CVS)

ArrayIterator::next -- Move to next entry

Description

void ArrayIterator::next ( void )

This function moves the iterator to the next entry.

Example 1. ArrayIterator::next() example

&#60;?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject-&#62;getIterator();

while($iterator-&#62;valid()) {
    echo $iterator-&#62;key() . ' =&#62; ' . $iterator-&#62;current() . "\n";

    $iterator-&#62;next();
}
?&#62;

The above example will output:

0 => zero
1 => one

Prev | Home | Next
ArrayIterator::key | Up | ArrayIterator::rewind


ArrayIterator::rewind

(no version information, might be only in CVS)

ArrayIterator::rewind -- Rewind array back to the start

Description

void ArrayIterator::rewind ( void )

This function rewinds the iterator to the beginning.

Example 1. ArrayIterator::rewind() example

&#60;?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject-&#62;getIterator();

$iterator-&#62;next();
echo $iterator-&#62;key(); //1

$iterator-&#62;rewind(); //rewinding to the begining
echo $iterator-&#62;key(); //0
?&#62;

Prev | Home | Next
ArrayIterator::next | Up | ArrayIterator::seek


ArrayIterator::seek

(no version information, might be only in CVS)

ArrayIterator::seek -- Seek to position

Description

void ArrayIterator::seek ( int position )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayIterator::rewind | Up | ArrayIterator::valid


ArrayIterator::valid

(no version information, might be only in CVS)

ArrayIterator::valid -- Check whether array contains more entries

Description

bool ArrayIterator::valid ( void )

This function checks if the array contains any more entries.

Example 1. ArrayIterator::valid() example

&#60;?php
$array = array('1' =&#62; 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject-&#62;getIterator();

var_dump($iterator-&#62;valid()); //bool(true)

$iterator-&#62;next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator-&#62;valid());
?&#62;

Prev | Home | Next
ArrayIterator::seek | Up | ArrayObject::append


ArrayObject::append

(no version information, might be only in CVS)

ArrayObject::append -- Appends the value

Description

void ArrayObject::append ( mixed newval )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayIterator::valid | Up | ArrayObject::__construct


ArrayObject::__construct

(no version information, might be only in CVS)

ArrayObject::__construct -- Construct a new array object

Description

ArrayObject ArrayObject::__construct ( mixed input )

This constructs a new array object. The input parameter accepts an array or another ArrayObject.

Example 1. ArrayObject::__construct() example

&#60;?php
$array = array('1' =&#62; 'one',
               '2' =&#62; 'two',
               '3' =&#62; 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?&#62;

The above example will output:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

Prev | Home | Next
ArrayObject::append | Up | ArrayObject::count


ArrayObject::count

(no version information, might be only in CVS)

ArrayObject::count -- Return the number of elements in the Iterator

Description

int ArrayObject::count ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::__construct | Up | ArrayObject::getIterator


ArrayObject::getIterator

(no version information, might be only in CVS)

ArrayObject::getIterator -- Create a new iterator from an ArrayObject instance

Description

ArrayIterator ArrayObject::getIterator ( void )

This function will return an iterator from an ArrayObject.

Example 1. ArrayObject::getIterator() example

&#60;?php
$array = array('1' =&#62; 'one',
               '2' =&#62; 'two',
               '3' =&#62; 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject-&#62;getIterator();

while($iterator-&#62;valid()) {
    echo $iterator-&#62;key() . ' =&#62; ' . $iterator-&#62;current() . "\n";

    $iterator-&#62;next();
}
?&#62;

The above example will output:

1 => one
2 => two
3 => three

Prev | Home | Next
ArrayObject::count | Up | ArrayObject::offsetExists


ArrayObject::offsetExists

(no version information, might be only in CVS)

ArrayObject::offsetExists -- Returns whether the requested $index exists

Description

bool ArrayObject::offsetExists ( mixed index )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::getIterator | Up | ArrayObject::offsetGet


ArrayObject::offsetGet

(no version information, might be only in CVS)

ArrayObject::offsetGet -- Returns the value at the specified $index

Description

mixed ArrayObject::offsetGet ( mixed index )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::offsetExists | Up | ArrayObject::offsetSet


ArrayObject::offsetSet

(no version information, might be only in CVS)

ArrayObject::offsetSet -- Sets the value at the specified $index to $newval

Description

void ArrayObject::offsetSet ( mixed index, mixed newval )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::offsetGet | Up | ArrayObject::offsetUnset


ArrayObject::offsetUnset

(no version information, might be only in CVS)

ArrayObject::offsetUnset -- Unsets the value at the specified $index

Description

void ArrayObject::offsetUnset ( mixed index )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::offsetSet | Up | CachingIterator::hasNext


CachingIterator::hasNext

(no version information, might be only in CVS)

CachingIterator::hasNext -- Check whether the inner iterator has a valid next element

Description

bool CachingIterator::hasNext ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ArrayObject::offsetUnset | Up | CachingIterator::next


CachingIterator::next

(no version information, might be only in CVS)

CachingIterator::next -- Move the iterator forward

Description

void CachingIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingIterator::hasNext | Up | CachingIterator::rewind


CachingIterator::rewind

(no version information, might be only in CVS)

CachingIterator::rewind -- Rewind the iterator

Description

void CachingIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingIterator::next | Up | CachingIterator::__toString


CachingIterator::__toString

(no version information, might be only in CVS)

CachingIterator::__toString -- Return the string representation of the current element

Description

string CachingIterator::__toString ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingIterator::rewind | Up | CachingIterator::valid


CachingIterator::valid

(no version information, might be only in CVS)

CachingIterator::valid -- Check whether the current element is valid

Description

bool CachingIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingIterator::__toString | Up | CachingRecursiveIterator::getChildren


CachingRecursiveIterator::getChildren

(no version information, might be only in CVS)

CachingRecursiveIterator::getChildren -- Return the inner iterator's children as a CachingRecursiveIterator

Description

CachingRecursiveIterator CachingRecursiveIterator::getChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingIterator::valid | Up | CachingRecursiveIterator::hasChildren


CachingRecursiveIterator::hasChildren

(no version information, might be only in CVS)

CachingRecursiveIterator::hasChildren -- Check whether the current element of the inner iterator has children

Description

bolean CachingRecursiveIterator::hasChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingRecursiveIterator::getChildren | Up | DirectoryIterator::__construct


DirectoryIterator::__construct

(no version information, might be only in CVS)

DirectoryIterator::__construct -- Constructs a new dir iterator from a path

Description

DirectoryIterator DirectoryIterator::__construct ( string path )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
CachingRecursiveIterator::hasChildren | Up | DirectoryIterator::current


DirectoryIterator::current

(no version information, might be only in CVS)

DirectoryIterator::current -- Return this (needed for Iterator interface)

Description

DirectoryIterator DirectoryIterator::current ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::__construct | Up | DirectoryIterator::getATime


DirectoryIterator::getATime

(no version information, might be only in CVS)

DirectoryIterator::getATime -- Get last access time of file

Description

int DirectoryIterator::getATime ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::current | Up | DirectoryIterator::getCTime


DirectoryIterator::getCTime

(no version information, might be only in CVS)

DirectoryIterator::getCTime -- Get inode modification time of file

Description

int DirectoryIterator::getCTime ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getATime | Up | DirectoryIterator::getChildren


DirectoryIterator::getChildren

(no version information, might be only in CVS)

DirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directory

Description

RecursiveDirectoryIterator DirectoryIterator::getChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getCTime | Up | DirectoryIterator::getFilename


DirectoryIterator::getFilename

(no version information, might be only in CVS)

DirectoryIterator::getFilename -- Return filename of current dir entry

Description

string DirectoryIterator::getFilename ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getChildren | Up | DirectoryIterator::getGroup


DirectoryIterator::getGroup

(no version information, might be only in CVS)

DirectoryIterator::getGroup -- Get file group

Description

int DirectoryIterator::getGroup ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getFilename | Up | DirectoryIterator::getInode


DirectoryIterator::getInode

(no version information, might be only in CVS)

DirectoryIterator::getInode -- Get file inode

Description

int DirectoryIterator::getInode ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getGroup | Up | DirectoryIterator::getMTime


DirectoryIterator::getMTime

(no version information, might be only in CVS)

DirectoryIterator::getMTime -- Get last modification time of file

Description

int DirectoryIterator::getMTime ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getInode | Up | DirectoryIterator::getOwner


DirectoryIterator::getOwner

(no version information, might be only in CVS)

DirectoryIterator::getOwner -- Get file owner

Description

int DirectoryIterator::getOwner ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getMTime | Up | DirectoryIterator::getPath


DirectoryIterator::getPath

(no version information, might be only in CVS)

DirectoryIterator::getPath -- Return directory path

Description

string DirectoryIterator::getPath ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getOwner | Up | DirectoryIterator::getPathname


DirectoryIterator::getPathname

(no version information, might be only in CVS)

DirectoryIterator::getPathname -- Return path and filename of current dir entry

Description

string DirectoryIterator::getPathname ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getPath | Up | DirectoryIterator::getPerms


DirectoryIterator::getPerms

(no version information, might be only in CVS)

DirectoryIterator::getPerms -- Get file permissions

Description

int DirectoryIterator::getPerms ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getPathname | Up | DirectoryIterator::getSize


DirectoryIterator::getSize

(no version information, might be only in CVS)

DirectoryIterator::getSize -- Get file size

Description

int DirectoryIterator::getSize ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getPerms | Up | DirectoryIterator::getType


DirectoryIterator::getType

(no version information, might be only in CVS)

DirectoryIterator::getType -- Get file type

Description

string DirectoryIterator::getType ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getSize | Up | DirectoryIterator::isDir


DirectoryIterator::isDir

(no version information, might be only in CVS)

DirectoryIterator::isDir -- Returns true if file is directory

Description

bool DirectoryIterator::isDir ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::getType | Up | DirectoryIterator::isDot


DirectoryIterator::isDot

(no version information, might be only in CVS)

DirectoryIterator::isDot -- Returns true if current entry is '.' or '..'

Description

bool DirectoryIterator::isDot ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isDir | Up | DirectoryIterator::isExecutable


DirectoryIterator::isExecutable

(no version information, might be only in CVS)

DirectoryIterator::isExecutable -- Returns true if file is executable

Description

bool DirectoryIterator::isExecutable ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isDot | Up | DirectoryIterator::isFile


DirectoryIterator::isFile

(no version information, might be only in CVS)

DirectoryIterator::isFile -- Returns true if file is a regular file

Description

bool DirectoryIterator::isFile ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isExecutable | Up | DirectoryIterator::isLink


DirectoryIterator::isLink

(no version information, might be only in CVS)

DirectoryIterator::isLink -- Returns true if file is symbolic link

Description

bool DirectoryIterator::isLink ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isFile | Up | DirectoryIterator::isReadable


DirectoryIterator::isReadable

(no version information, might be only in CVS)

DirectoryIterator::isReadable -- Returns true if file can be read

Description

bool DirectoryIterator::isReadable ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isLink | Up | DirectoryIterator::isWritable


DirectoryIterator::isWritable

(no version information, might be only in CVS)

DirectoryIterator::isWritable -- Returns true if file can be written

Description

bool DirectoryIterator::isWritable ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isReadable | Up | DirectoryIterator::key


DirectoryIterator::key

(no version information, might be only in CVS)

DirectoryIterator::key -- Return current dir entry

Description

string DirectoryIterator::key ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::isWritable | Up | DirectoryIterator::next


DirectoryIterator::next

(no version information, might be only in CVS)

DirectoryIterator::next -- Move to next entry

Description

void DirectoryIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::key | Up | DirectoryIterator::rewind


DirectoryIterator::rewind

(no version information, might be only in CVS)

DirectoryIterator::rewind -- Rewind dir back to the start

Description

void DirectoryIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::next | Up | DirectoryIterator::valid


DirectoryIterator::valid

(no version information, might be only in CVS)

DirectoryIterator::valid -- Check whether dir contains more entries

Description

string DirectoryIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::rewind | Up | FilterIterator::current


FilterIterator::current

(no version information, might be only in CVS)

FilterIterator::current -- Get the current element value

Description

mixed FilterIterator::current ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
DirectoryIterator::valid | Up | FilterIterator::getInnerIterator


FilterIterator::getInnerIterator

(no version information, might be only in CVS)

FilterIterator::getInnerIterator -- Get the inner iterator

Description

Iterator FilterIterator::getInnerIterator ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::current | Up | FilterIterator::key


FilterIterator::key

(no version information, might be only in CVS)

FilterIterator::key -- Get the current key

Description

mixed FilterIterator::key ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::getInnerIterator | Up | FilterIterator::next


FilterIterator::next

(no version information, might be only in CVS)

FilterIterator::next -- Move the iterator forward

Description

void FilterIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::key | Up | FilterIterator::rewind


FilterIterator::rewind

(no version information, might be only in CVS)

FilterIterator::rewind -- Rewind the iterator

Description

void FilterIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::next | Up | FilterIterator::valid


FilterIterator::valid

(no version information, might be only in CVS)

FilterIterator::valid -- Check whether the current element is valid

Description

bool FilterIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::rewind | Up | LimitIterator::getPosition


LimitIterator::getPosition

(no version information, might be only in CVS)

LimitIterator::getPosition -- Return the current position

Description

int LimitIterator::getPosition ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
FilterIterator::valid | Up | LimitIterator::next


LimitIterator::next

(no version information, might be only in CVS)

LimitIterator::next -- Move the iterator forward

Description

void LimitIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
LimitIterator::getPosition | Up | LimitIterator::rewind


LimitIterator::rewind

(no version information, might be only in CVS)

LimitIterator::rewind -- Rewind the iterator to the specified starting offset

Description

void LimitIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
LimitIterator::next | Up | LimitIterator::seek


LimitIterator::seek

(no version information, might be only in CVS)

LimitIterator::seek -- Seek to the given position

Description

void LimitIterator::seek ( int position )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
LimitIterator::rewind | Up | LimitIterator::valid


LimitIterator::valid

(no version information, might be only in CVS)

LimitIterator::valid -- Check whether the current element is valid

Description

bool LimitIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
LimitIterator::seek | Up | ParentIterator::getChildren


ParentIterator::getChildren

(no version information, might be only in CVS)

ParentIterator::getChildren -- Return the inner iterator's children contained in a ParentIterator

Description

ParentIterator ParentIterator::getChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
LimitIterator::valid | Up | ParentIterator::hasChildren


ParentIterator::hasChildren

(no version information, might be only in CVS)

ParentIterator::hasChildren -- Check whether the inner iterator's current element has children

Description

bool ParentIterator::hasChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ParentIterator::getChildren | Up | ParentIterator::next


ParentIterator::next

(no version information, might be only in CVS)

ParentIterator::next -- Move the iterator forward

Description

void ParentIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ParentIterator::hasChildren | Up | ParentIterator::rewind


ParentIterator::rewind

(no version information, might be only in CVS)

ParentIterator::rewind -- Rewind the iterator

Description

void ParentIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ParentIterator::next | Up | RecursiveDirectoryIterator::getChildren


RecursiveDirectoryIterator::getChildren

(no version information, might be only in CVS)

RecursiveDirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directory

Description

object RecursiveDirectoryIterator::getChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
ParentIterator::rewind | Up | RecursiveDirectoryIterator::hasChildren


RecursiveDirectoryIterator::hasChildren

(no version information, might be only in CVS)

RecursiveDirectoryIterator::hasChildren -- Returns whether current entry is a directory and not '.' or '..'

Description

bool RecursiveDirectoryIterator::hasChildren ( [bool allow_links] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveDirectoryIterator::getChildren | Up | RecursiveDirectoryIterator::key


RecursiveDirectoryIterator::key

(no version information, might be only in CVS)

RecursiveDirectoryIterator::key -- Return path and filename of current dir entry

Description

string RecursiveDirectoryIterator::key ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveDirectoryIterator::hasChildren | Up | RecursiveDirectoryIterator::next


RecursiveDirectoryIterator::next

(no version information, might be only in CVS)

RecursiveDirectoryIterator::next -- Move to next entry

Description

void RecursiveDirectoryIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveDirectoryIterator::key | Up | RecursiveDirectoryIterator::rewind


RecursiveDirectoryIterator::rewind

(no version information, might be only in CVS)

RecursiveDirectoryIterator::rewind -- Rewind dir back to the start

Description

void RecursiveDirectoryIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveDirectoryIterator::next | Up | RecursiveIteratorIterator::current


RecursiveIteratorIterator::current

(no version information, might be only in CVS)

RecursiveIteratorIterator::current -- Access the current element value

Description

mixed RecursiveIteratorIterator::current ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveDirectoryIterator::rewind | Up | RecursiveIteratorIterator::getDepth


RecursiveIteratorIterator::getDepth

(no version information, might be only in CVS)

RecursiveIteratorIterator::getDepth -- Get the current depth of the recursive iteration

Description

int RecursiveIteratorIterator::getDepth ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::current | Up | RecursiveIteratorIterator::getSubIterator


RecursiveIteratorIterator::getSubIterator

(no version information, might be only in CVS)

RecursiveIteratorIterator::getSubIterator -- The current active sub iterator

Description

RecursiveIterator RecursiveIteratorIterator::getSubIterator ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::getDepth | Up | RecursiveIteratorIterator::key


RecursiveIteratorIterator::key

(no version information, might be only in CVS)

RecursiveIteratorIterator::key -- Access the current key

Description

mixed RecursiveIteratorIterator::key ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::getSubIterator | Up | RecursiveIteratorIterator::next


RecursiveIteratorIterator::next

(no version information, might be only in CVS)

RecursiveIteratorIterator::next -- Move forward to the next element

Description

void RecursiveIteratorIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::key | Up | RecursiveIteratorIterator::rewind


RecursiveIteratorIterator::rewind

(no version information, might be only in CVS)

RecursiveIteratorIterator::rewind -- Rewind the iterator to the first element of the top level inner iterator

Description

void RecursiveIteratorIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::next | Up | RecursiveIteratorIterator::valid


RecursiveIteratorIterator::valid

(no version information, might be only in CVS)

RecursiveIteratorIterator::valid -- Check whether the current position is valid

Description

bolean RecursiveIteratorIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::rewind | Up | SimpleXMLIterator::current


SimpleXMLIterator::current

(no version information, might be only in CVS)

SimpleXMLIterator::current -- Return current SimpleXML entry

Description

mixed SimpleXMLIterator::current ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
RecursiveIteratorIterator::valid | Up | SimpleXMLIterator::getChildren


SimpleXMLIterator::getChildren

(no version information, might be only in CVS)

SimpleXMLIterator::getChildren -- Returns an iterator for the current entry if it is a SimpleXML object

Description

object SimpleXMLIterator::getChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::current | Up | SimpleXMLIterator::hasChildren


SimpleXMLIterator::hasChildren

(no version information, might be only in CVS)

SimpleXMLIterator::hasChildren -- Returns whether current entry is a SimpleXML object

Description

bool SimpleXMLIterator::hasChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::getChildren | Up | SimpleXMLIterator::key


SimpleXMLIterator::key

(no version information, might be only in CVS)

SimpleXMLIterator::key -- Return current SimpleXML key

Description

mixed SimpleXMLIterator::key ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::hasChildren | Up | SimpleXMLIterator::next


SimpleXMLIterator::next

(no version information, might be only in CVS)

SimpleXMLIterator::next -- Move to next entry

Description

void SimpleXMLIterator::next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::key | Up | SimpleXMLIterator::rewind


SimpleXMLIterator::rewind

(no version information, might be only in CVS)

SimpleXMLIterator::rewind -- Rewind SimpleXML back to the start

Description

void SimpleXMLIterator::rewind ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::next | Up | SimpleXMLIterator::valid


SimpleXMLIterator::valid

(no version information, might be only in CVS)

SimpleXMLIterator::valid -- Check whether SimpleXML contains more entries

Description

bool SimpleXMLIterator::valid ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SimpleXMLIterator::rewind | Up | class_implements


class_implements

(PHP 5)

class_implements -- Return the interfaces which are implemented by the given class

Description

array class_implements ( mixed class [, bool autoload] )

This function returns an array with the names of the interfaces that the given class and its parents implement.

Parameters

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.

Return Values

Returns an array or FALSE on error.

ChangeLog

Version | Description
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Examples

Example 1. class_implements() example

&#60;?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// since PHP 5.1 you may also specify the parameter as a string
print_r(class_implements('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_implements('not_loaded', true));

?&#62;

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

See Also

class_parents()

Prev | Home | Next
SimpleXMLIterator::valid | Up | class_parents


class_parents

(PHP 5)

class_parents -- Return the parent classes of the given class

Description

array class_parents ( mixed class [, bool autoload] )

This function returns an array with the name of the parent classes of the given class.

Parameters

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.

Return Values

Returns an array or FALSE on error.

ChangeLog

Version | Description
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Examples

Example 1. class_parents() example

&#60;?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// since PHP 5.1 you may also specify the parameter as a string
print_r(class_parents('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_parents('not_loaded', true));
?&#62;

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

See Also

class_implements()

Prev | Home | Next
class_implements | Up | iterator_count


iterator_count

(PHP 5 >= 5.1.0RC1)

iterator_count -- Count the elements in an iterator

Description

int iterator_count ( IteratorAggregate iterator )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
class_parents | Up | iterator_to_array


iterator_to_array

(PHP 5 >= 5.1.0RC1)

iterator_to_array -- Copy the iterator into an array

Description

array iterator_to_array ( IteratorAggregate iterator )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
iterator_count | Up | spl_autoload_call


spl_classes

(PHP 5)

spl_classes -- Return available SPL classes

Description

array spl_classes ( void )

This function returns an array with the current available SPL classes.

Example 1. spl_classes() example

&#60;?php

print_r(spl_classes());

?&#62;

The above example will output something similar to:

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [CachingRecursiveIterator] => CachingRecursiveIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)

Prev | Home | Next
spl_autoload | Up | spl_object_hash


SQLite Functions

PHP Manual
Prev Next

CLIV. SQLite Functions

Introduction

This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.

SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.

Note: For further information see the SQLite Website (http://sqlite.org/).

Installation

Read the INSTALL file, which comes with the package. Or just use the PEAR installer with pear install sqlite. SQLite itself is already included, You do not need to install any additional software.

Windows users may download the DLL version of the SQLite extension here: (php_sqlite.dll).

In PHP 5, the SQLite extension and the engine itself are bundled and compiled by default. However, since PHP 5.1.0 you need to manually activate the extension in php.ini (because it is now bundled as shared). Moreover, since PHP 5.1.0 SQLite depends on PDO it must be enabled too, by adding the following lines to php.ini (in order):

extension=php_pdo.dll
extension=php_sqlite.dll

On Linux or Unix operating systems, if you build PDO as a shared extension, you must build SQLite as a shared extension using the --with-sqlite=shared configure option.

SQLite 3 is supported through PDO SQLite.

Windows installation for unprivileged accounts: On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:

SetEnv TMP c:/temp

If you are unable to establish this setting at the server level, you can implement the setting in your script:

putenv('TMP=C:/temp');

The setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables

Requirements

In order to have these functions available, you must compile PHP with SQLite support, or load the SQLite extension dynamically from your php.ini.

Resource Types

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.

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 functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

SQLite result type constants

SQLITE_ASSOC (int)

Columns are returned into the array having the field name as the array index.

SQLITE_BOTH (int)

Columns are returned into the array having both a numerical index and the field name as the array index.

SQLITE_NUM (int)

Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

A number of functions may return status codes. The following constants are defined:

SQLite status code constants

SQLITE_OK (int)

Successful result.

SQLITE_ERROR (int)

SQL error or missing database.

SQLITE_INTERNAL (int)

An internal logic error in SQLite.

SQLITE_PERM (int)

Access permission denied.

SQLITE_ABORT (int)

Callback routine requested an abort.

SQLITE_BUSY (int)

The database file is locked.

SQLITE_LOCKED (int)

A table in the database is locked.

SQLITE_NOMEM (int)

Memory allocation failed.

SQLITE_READONLY (int)

Attempt to write a readonly database.

SQLITE_INTERRUPT (int)

Operation terminated internally.

SQLITE_IOERR (int)

Disk I/O error occurred.

SQLITE_CORRUPT (int)

The database disk image is malformed.

SQLITE_NOTFOUND (int)

(Internal) Table or record not found.

SQLITE_FULL (int)

Insertion failed because database is full.

SQLITE_CANTOPEN (int)

Unable to open the database file.

SQLITE_PROTOCOL (int)

Database lock protocol error.

SQLITE_EMPTY (int)

(Internal) Database table is empty.

SQLITE_SCHEMA (int)

The database schema changed.

SQLITE_TOOBIG (int)

Too much data for one row of a table.

SQLITE_CONSTRAINT (int)

Abort due to constraint violation.

SQLITE_MISMATCH (int)

Data type mismatch.

SQLITE_MISUSE (int)

Library used incorrectly.

SQLITE_NOLFS (int)

Uses of OS features not supported on host.

SQLITE_AUTH (int)

Authorized failed.

SQLITE_ROW (int)

Internal process has another row ready.

SQLITE_DONE (int)

Internal process has finished executing.

Predefined Classes

SQLiteDatabase

Represents an opened SQLite database.

Constructor

  • __construct - construct a new SQLiteDatabase object

Methods

  • query - Execute a query

  • queryExec - Execute a result-less query

  • arrayQuery - Execute a query and return the result as an array

  • singleQuery - Execute a query and return either an array for one single column or the value of the first row

  • unbufferedQuery - Execute an unbuffered query

  • lastInsertRowid - Returns the rowid of the most recently inserted row

  • changes - Returns the number of rows changed by the most recent statement

  • createAggregate - Register an aggregating UDF for use in SQL statements

  • createFunction - Register a UDF for use in SQL statements

  • busyTimeout - Sets or disables busy timeout duration

  • lastError - Returns the last error code of the most recently encountered error

  • fetchColumnTypes - Return an array of column types from a particular table

SQLiteResult

Represents a buffered SQLite result set.

Methods

  • fetch - Fetches the next row from the result set as an array

  • fetchObject - Fetches the next row from the result set as an object

  • fetchSingle - Fetches the first column from the result set as a string

  • fetchAll - Fetches all rows from the result set as an array of arrays

  • column - Fetches a column from the current row of the result set

  • numFields - Returns the number of fields in the result set

  • fieldName - Returns the name of a particular field in the result set

  • current - Fetches the current row from the result set as an array

  • key - Return the current row index

  • next - Seek to the next row number

  • valid - Returns whether more rows are available

  • rewind - Seek to the first row number of the result set

  • prev - Seek to the previous row number of the result set

  • hasPrev - Returns whether or not a previous row is available

  • numRows - Returns the number of rows in the result set

  • seek - Seek to a particular row number

SQLiteUnbuffered

Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.

Methods

  • fetch - Fetches the next row from the result set as an array

  • fetchObject - Fetches the next row from the result set as an object

  • fetchSingle - Fetches the first column from the result set as a string

  • fetchAll - Fetches all rows from the result set as an array of arrays

  • column - Fetches a column from the current row of the result set

  • numFields - Returns the number of fields in the result set

  • fieldName - Returns the name of a particular field in the result set

  • current - Fetches the current row from the result set as an array

  • next - Seek to the next row number

  • valid - Returns whether more rows are available

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. SQLite Configure Options

Name | Default | Changeable | Changelog
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

sqlite.assoc_case int

Whether to use mixed case (0), upper case (1) or lower case (2) hash indexes.

This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.

The SQLite library returns the column names in their natural case (that matches the case you used in your schema). When sqlite.assoc_case is set to 0 the natural case will be preserved. When it is set to 1 or 2, PHP will apply case folding on the hash keys to upper- or lower-case the keys, respectively.

Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.

Table of Contents
sqlite_array_query -- Execute a query against a given database and returns an array
sqlite_busy_timeout -- Set busy timeout duration, or disable busy handlers
sqlite_changes -- Returns the number of rows that were changed by the most recent SQL statement
sqlite_close -- Closes an open SQLite database
sqlite_column -- Fetches a column from the current row of a result set
sqlite_create_aggregate -- Register an aggregating UDF for use in SQL statements
sqlite_create_function -- Registers a "regular" User Defined Function for use in SQL statements
sqlite_current -- Fetches the current row from a result set as an array
sqlite_error_string -- Returns the textual description of an error code
sqlite_escape_string -- Escapes a string for use as a query parameter
sqlite_exec -- Executes a result-less query against a given database
sqlite_factory -- Opens a SQLite database and returns a SQLiteDatabase object
sqlite_fetch_all -- Fetches all rows from a result set as an array of arrays
sqlite_fetch_array -- Fetches the next row from a result set as an array
sqlite_fetch_column_types -- Return an array of column types from a particular table
sqlite_fetch_object -- Fetches the next row from a result set as an object
sqlite_fetch_single -- Fetches the first column of a result set as a string
sqlite_fetch_string -- Alias of sqlite_fetch_single()
sqlite_field_name -- Returns the name of a particular field
sqlite_has_more -- Finds whether or not more rows are available
sqlite_has_prev -- Returns whether or not a previous row is available
sqlite_key -- Returns the current row index
sqlite_last_error -- Returns the error code of the last error for a database
sqlite_last_insert_rowid -- Returns the rowid of the most recently inserted row
sqlite_libencoding -- Returns the encoding of the linked SQLite library
sqlite_libversion -- Returns the version of the linked SQLite library
sqlite_next -- Seek to the next row number
sqlite_num_fields -- Returns the number of fields in a result set
sqlite_num_rows -- Returns the number of rows in a buffered result set
sqlite_open -- Opens a SQLite database and create the database if it does not exist
sqlite_popen -- Opens a persistent handle to an SQLite database and create the database if it does not exist
sqlite_prev -- Seek to the previous row number of a result set
sqlite_query -- Executes a query against a given database and returns a result handle
sqlite_rewind -- Seek to the first row number
sqlite_seek -- Seek to a particular row number of a buffered result set
sqlite_single_query -- Executes a query and returns either an array for one single column or the value of the first row
sqlite_udf_decode_binary -- Decode binary data passed as parameters to an UDF
sqlite_udf_encode_binary -- Encode binary data before returning it from an UDF
sqlite_unbuffered_query -- Execute a query that does not prefetch and buffer all data
sqlite_valid -- Returns whether more rows are available

Prev | Home | Next
spl_object_hash | Up | sqlite_array_query


sqlite_array_query

(PHP 5)

sqlite_array_query

(no version information, might be only in CVS)

SQLiteDatabase->arrayQuery -- Execute a query against a given database and returns an array

Description

array sqlite_array_query ( resource dbhandle, string query [, int result_type [, bool decode_binary]] )

array sqlite_array_query ( string query, resource dbhandle [, int result_type [, bool decode_binary]] )

Object oriented style (method):

class SQLiteDatabase {

array arrayQuery ( string query [, int result_type [, bool decode_binary]] )

}

sqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.

Tip: sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.

Parameters

query

The query to be executed.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns an array of the entire result set; FALSE otherwise.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example 1. Procedural style

&#60;?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

Example 2. Object-oriented style

&#60;?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle-&#62;arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

See Also

sqlite_query()
sqlite_fetch_array()
sqlite_fetch_string()

Prev | Home | Next
SQLite Functions | Up | sqlite_busy_timeout


sqlite_busy_timeout

(PHP 5)

sqlite_busy_timeout

(no version information, might be only in CVS)

SQLiteDatabase->busyTimeout -- Set busy timeout duration, or disable busy handlers

Description

void sqlite_busy_timeout ( resource dbhandle, int milliseconds )

Object oriented style (method):

class SQLiteDatabase {

void busyTimeout ( int milliseconds )

}

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

milliseconds

The number of milliseconds. When set to 0, busy handlers will be disabled and SQLite will return immediately with a SQLITE_BUSY status code if another process/thread has the database locked for an update.

PHP sets the default busy timeout to be 60 seconds when the database is opened.

Note: There are one thousand (1000) milliseconds in one second.

Examples

Example 1. Procedural style

&#60;?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?&#62;

Example 2. Object oriented style

&#60;?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle-&#62;busyTimeout(10000); // 10 seconds
$dbhandle-&#62;busyTimeout(0); // disable
?&#62;

See Also

sqlite_open()

Prev | Home | Next
sqlite_array_query | Up | sqlite_changes


sqlite_changes

(PHP 5)

sqlite_changes

(no version information, might be only in CVS)

SQLiteDatabase->changes -- Returns the number of rows that were changed by the most recent SQL statement

Description

int sqlite_changes ( resource dbhandle )

Object oriented style (method):

class SQLiteDatabase {

int changes ( void )

}

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Examples

Example 1. Procedural style

&#60;?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?&#62;

Example 2. Object oriented style

&#60;?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle-&#62;query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle-&#62;changes();
}
?&#62;

See Also

sqlite_open()

Prev | Home | Next
sqlite_busy_timeout | Up | sqlite_close


sqlite_close

(PHP 5)

sqlite_close -- Closes an open SQLite database

Description

void sqlite_close ( resource dbhandle )

Closes the given database handle. If the database was persistent, it will be closed and removed from the persistent list.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Examples

Example 1. sqlite_close() example

&#60;?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?&#62;

See Also

sqlite_open()
sqlite_popen()

Prev | Home | Next
sqlite_changes | Up | sqlite_column


sqlite_column

(PHP 5)

sqlite_column

(no version information, might be only in CVS)

SQLiteResult->column

(no version information, might be only in CVS)

SQLiteUnbuffered->column -- Fetches a column from the current row of a result set

Description

mixed sqlite_column ( resource result, mixed index_or_name [, bool decode_binary] )

class SQLiteResult {

mixed column ( mixed index_or_name [, bool decode_binary] )

}class SQLiteUnbuffered {

mixed column ( mixed index_or_name [, bool decode_binary] )

}

Fetches the value of a column named index_or_name (if it is a string), or of the ordinal column numbered index_or_name (if it is an integer) from the current row of the query result handle result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

index_or_name

The column index or name to fetch.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Notes

Note: Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

See Also

sqlite_fetch_string()

Prev | Home | Next
sqlite_close | Up | sqlite_create_aggregate


sqlite_create_aggregate

(PHP 5)

sqlite_create_aggregate

(no version information, might be only in CVS)

SQLiteDatabase->createAggregate -- Register an aggregating UDF for use in SQL statements

Description

void sqlite_create_aggregate ( resource dbhandle, string function_name, callback step_func, callback finalize_func [, int num_args] )

Object oriented style (method):

class SQLiteDatabase {

void createAggregate ( string function_name, callback step_func, callback finalize_func [, int num_args] )

}

sqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set.

finalize_func

Callback function to aggregate the "stepped" data from each row.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Examples

Example 1. max_length aggregation function example

&#60;?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&#38;$context, $string)
{
    if (strlen($string) &#62; $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&#38;$context)
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?&#62;

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Note: The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.

Tip: It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip: You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

sqlite_create_function()
sqlite_udf_encode_binary()
sqlite_udf_decode_binary()

Prev | Home | Next
sqlite_column | Up | sqlite_create_function


sqlite_create_function

(PHP 5)

sqlite_create_function

(no version information, might be only in CVS)

SQLiteDatabase->createFunction -- Registers a "regular" User Defined Function for use in SQL statements

Description

void sqlite_create_function ( resource dbhandle, string function_name, callback callback [, int num_args] )

Object oriented style (method):

class SQLiteDatabase {

void createFunction ( string function_name, callback callback [, int num_args] )

}

sqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Examples

Example 1. sqlite_create_function() example

&#60;?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);

    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?&#62;

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach() loop after you have queried for the data.

PHP registers a special function named php when the database is first opened. The php function can be used to call any PHP function without having to register it first.

Example 2. Example of using the PHP function

&#60;?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?&#62;

This example will call the md5() on each filename column in the database and return the result into $rows

Note: For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.

Tip: It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.

Tip: You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

sqlite_create_aggregate()

Prev | Home | Next
sqlite_create_aggregate | Up | sqlite_current


sqlite_current

(PHP 5)

sqlite_current

(no version information, might be only in CVS)

SQLiteResult->current

(no version information, might be only in CVS)

SQLiteUnbuffered->current -- Fetches the current row from a result set as an array

Description

array sqlite_current ( resource result [, int result_type [, bool decode_binary]] )

Object oriented style (method):

class SQLiteResult {

array current ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array current ( [int result_type [, bool decode_binary]] )

}

sqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

See Also

sqlite_seek()
sqlite_next()
sqlite_fetch_array()

Prev | Home | Next
sqlite_create_function | Up | sqlite_error_string


sqlite_error_string

(PHP 5)

sqlite_error_string -- Returns the textual description of an error code

Description

string sqlite_error_string ( int error_code )

Returns a human readable description of the error_code returned from sqlite_last_error().

See Also

sqlite_last_error()

Prev | Home | Next
sqlite_current | Up | sqlite_escape_string


sqlite_escape_string

(PHP 5)

sqlite_escape_string -- Escapes a string for use as a query parameter

Description

string sqlite_escape_string ( string item )

sqlite_escape_string() will correctly quote the string specified by item for use in an SQLite SQL statement. This includes doubling up single-quote characters (') and checking for binary-unsafe characters in the query string.

If the item contains a NUL character, or if it begins with a character whose ordinal value is 0x01, PHP will apply a binary encoding scheme so that you can safely store and retrieve binary data.

Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data. In practice, this shouldn't be a problem, as your schema should be such that you don't use such things on binary columns (in fact, it might be better to store binary data using other means, such as in files).

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

Note:
    Do not use this function to encode the return values from UDF's created
    using sqlite_create_function() or
    sqlite_create_aggregate() - use
    sqlite_udf_encode_binary() instead.

See Also

sqlite_udf_encode_binary()

Prev | Home | Next
sqlite_error_string | Up | sqlite_exec


sqlite_exec

(PHP 5)

sqlite_exec

(no version information, might be only in CVS)

SQLiteDatabase->exec -- Executes a result-less query against a given database

Description

bool sqlite_exec ( resource dbhandle, string query [, string &error_msg] )

bool sqlite_exec ( string query, resource dbhandle )

Object oriented style (method):

class SQLiteDatabase {

bool queryExec ( string query [, string &error_msg] )

}

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

ChangeLog

Version | Description
5.1.0 | Added the error_msg parameter

Examples

Example 1. Procedural example

&#60;?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?&#62;

Example 2. Object-oriented example

&#60;?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle-&#62;queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', $dbhandle-&#62;changes();
}
?&#62;

See Also

sqlite_query()
sqlite_unbuffered_query()
sqlite_array_query()

Prev | Home | Next
sqlite_escape_string | Up | sqlite_factory


sqlite_factory

(PHP 5)

sqlite_factory -- Opens a SQLite database and returns a SQLiteDatabase object

Description

SQLiteDatabase sqlite_factory ( string filename [, int mode [, string &error_message]] )

sqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.

Parameters

filename

The filename of the SQLite database.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a SQLiteDatabase object on success, NULL on error.

Examples

Example 1. sqlite_factory() example

&#60;?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle-&#62;query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle-&#62;query('SELECT user_id, username FROM users');

?&#62;

See Also

sqlite_open()
sqlite_popen()

Prev | Home | Next
sqlite_exec | Up | sqlite_fetch_all


sqlite_fetch_all

(PHP 5)

sqlite_fetch_all

(no version information, might be only in CVS)

SQLiteResult->fetchAll

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchAll -- Fetches all rows from a result set as an array of arrays

Description

array sqlite_fetch_all ( resource result [, int result_type [, bool decode_binary]] )

Object oriented style (method):

class SQLiteResult {

array fetchAll ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array fetchAll ( [int result_type [, bool decode_binary]] )

}

sqlite_fetch_all() returns an array of the entire result set from the result resource. It is similar to calling sqlite_query() (or sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example 1. Procedural example

&#60;?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

Example 2. Object-oriented example

&#60;?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle-&#62;query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle-&#62;unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query-&#62;fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

See Also

sqlite_fetch_array()

Prev | Home | Next
sqlite_factory | Up | sqlite_fetch_array


sqlite_fetch_array

(PHP 5)

sqlite_fetch_array

(no version information, might be only in CVS)

SQLiteResult->fetch

(no version information, might be only in CVS)

SQLiteUnbuffered->fetch -- Fetches the next row from a result set as an array

Description

array sqlite_fetch_array ( resource result [, int result_type [, bool decode_binary]] )

Object oriented style (method):

class SQLiteResult {

array fetch ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array fetch ( [int result_type [, bool decode_binary]] )

}

Fetches the next row from the given result handle. If there are no more rows, returns FALSE, otherwise returns an associative array representing the row data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example 1. Procedural example

&#60;?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
while ($entry = sqlite_fetch_array($query, SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

Example 2. Object-oriented example

&#60;?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle-&#62;query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle-&#62;unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry = $query-&#62;fetch(SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?&#62;

See Also

sqlite_array_query()
sqlite_fetch_string()

Prev | Home | Next
sqlite_fetch_all | Up | sqlite_fetch_column_types


sqlite_fetch_column_types

(PHP 5)

sqlite_fetch_column_types

(no version information, might be only in CVS)

SQLiteDatabase->fetchColumnTypes -- Return an array of column types from a particular table

Description

array sqlite_fetch_column_types ( string table_name, resource dbhandle [, int result_type] )

Object oriented style (method):

class SQLiteDatabase {

array fetchColumnTypes ( string table_name [, int result_type] )

}

sqlite_fetch_column_types() returns an array of column data types from the specified table_name table.

Parameters

table_name

The table name to query.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_ASSOC is the default for this function.

Return Values

Returns an array of column data types; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

ChangeLog

Version | Description
5.1.0 | Added result_type

Examples

Example 1. Procedural example

&#60;?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);

foreach ($cols as $column =&#62; $type) {
    echo "Column: $column  Type: $type";
}
?&#62;

Example 2. Object-oriented example

&#60;?php
$db = new SQLiteDatabase('mysqlitedb');
$db-&#62;query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db-&#62;fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column =&#62; $type) {
    echo "Column: $column  Type: $type";
}
?&#62;

The above example will output:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

Prev | Home | Next
sqlite_fetch_array | Up | sqlite_fetch_object


sqlite_fetch_object

(PHP 5)

sqlite_fetch_object

(no version information, might be only in CVS)

SQLiteResult->fetchObject

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchObject -- Fetches the next row from a result set as an object

Description

object sqlite_fetch_object ( resource result [, string class_name [, array ctor_params [, bool decode_binary]]] )

Object oriented style (method):

class SQLiteResult {

object fetchObject ( [string class_name [, array ctor_params [, bool decode_binary]]] )

}class SQLiteUnbuffered {

object fetchObject ( [string class_name [, array ctor_params [, bool decode_binary]]] )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
sqlite_fetch_column_types | Up | sqlite_fetch_single


sqlite_fetch_single

(PHP 5)

sqlite_fetch_single

(no version information, might be only in CVS)

SQLiteResult->fetchSingle

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchSingle -- Fetches the first column of a result set as a string

Description

string sqlite_fetch_single ( resource result [, bool decode_binary] )

Object oriented style (method):

class SQLiteResult {

string fetchSingle ( [bool decode_binary] )

}class SQLiteUnbuffered {

string fetchSingle ( [bool decode_binary] )

}

sqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.

This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Examples

Example 1. A sqlite_fetch_single() example

&#60;?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    $sql = "SELECT id FROM sometable WHERE id = 42";
    $res = sqlite_query($dbhandle, $sql);

    if (sqlite_num_rows($res) &#62; 0) {
        echo sqlite_fetch_single($res); // 42
    }

    sqlite_close($dbhandle);
}
?&#62;

See Also

sqlite_fetch_array()

Prev | Home | Next
sqlite_fetch_object | Up | sqlite_fetch_string


sqlite_fetch_string

(PHP 5)

sqlite_fetch_string -- Alias of sqlite_fetch_single()

Description

This function is an alias of: sqlite_fetch_single().

Prev | Home | Next
sqlite_fetch_single | Up | sqlite_field_name


sqlite_field_name

(PHP 5)

sqlite_field_name

(no version information, might be only in CVS)

SQLiteResult->fieldName

(no version information, might be only in CVS)

SQLiteUnbuffered->fieldName -- Returns the name of a particular field

Description

string sqlite_field_name ( resource result, int field_index )

Object oriented style (method):

class SQLiteResult {

string fieldName ( int field_index )

}class SQLiteUnbuffered {

string fieldName ( int field_index )

}

Given the ordinal column number, field_index, sqlite_field_name() returns the name of that field in the result set result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

field_index

The ordinal column number in the result set.

Return Values

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Prev | Home | Next
sqlite_fetch_string | Up | sqlite_has_more


sqlite_has_more

(PHP 5)

sqlite_has_more -- Finds whether or not more rows are available

Description

bool sqlite_has_more ( resource result )

Finds whether more rows are available from the given result set.

Parameters

result

The SQLite result resource.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

sqlite_num_rows()
sqlite_changes()

Prev | Home | Next
sqlite_field_name | Up | sqlite_has_prev


sqlite_has_prev

(PHP 5)

sqlite_has_prev

(no version information, might be only in CVS)

SQLiteResult->hasPrev -- Returns whether or not a previous row is available

Description

bool sqlite_has_prev ( resource result )

Object oriented style (method):

class SQLiteResult {

bool hasPrev ( void )

}

Find whether there are more previous rows from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

See Also

sqlite_prev()
sqlite_has_more()
sqlite_num_rows()

Prev | Home | Next
sqlite_has_more | Up | sqlite_key


sqlite_key

(no version information, might be only in CVS)

sqlite_key

(no version information, might be only in CVS)

SQLiteResult->key -- Returns the current row index

Description

int sqlite_key ( resource result )

Object oriented style (method):

class SQLiteResult {

int key ( void )

}

sqlite_key() returns the current row index of the buffered result set result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns the current row index of the buffered result set result.

ChangeLog

Version | Description
5.0.4 | Prior to PHP 5.0.4, sqlite_key() was only able to be called as a method on a SQLiteResult object, not procedurally.

See Also

sqlite_next()
sqlite_current()
sqlite_rewind()

Prev | Home | Next
sqlite_has_prev | Up | sqlite_last_error


sqlite_last_error

(PHP 5)

sqlite_last_error

(no version information, might be only in CVS)

SQLiteDatabase->lastError -- Returns the error code of the last error for a database

Description

int sqlite_last_error ( resource dbhandle )

Object oriented style (method):

class SQLiteDatabase {

int lastError ( void )

}

Returns the error code from the last operation performed on dbhandle (the database handle), or 0 when no error occurred. A human readable description of the error code can be retrieved using sqlite_error_string().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

See Also

sqlite_error_string()

Prev | Home | Next
sqlite_key | Up | sqlite_last_insert_rowid


sqlite_last_insert_rowid

(PHP 5)

sqlite_last_insert_rowid

(no version information, might be only in CVS)

SQLiteDatabase->lastInsertRowid -- Returns the rowid of the most recently inserted row

Description

int sqlite_last_insert_rowid ( resource dbhandle )

Object oriented style (method):

class SQLiteDatabase {

int lastInsertRowid ( void )

}

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

Tip: You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Prev | Home | Next
sqlite_last_error | Up | sqlite_libencoding


sqlite_libencoding

(PHP 5)

sqlite_libencoding -- Returns the encoding of the linked SQLite library

Description

string sqlite_libencoding ( void )

The SQLite library may be compiled in either ISO-8859-1 or UTF-8 compatible modes. This function allows you to determine which encoding scheme is used by your version of the library.

Warning

The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode. However, this is a misnomer; rather than handling ISO-8859-1, it operates according to your current locale settings for string comparisons and sort ordering. So, rather than ISO-8859-1, you should think of it as being '8-bit' instead.

When compiled with UTF-8 support, sqlite handles encoding and decoding of UTF-8 multi-byte character sequences, but does not yet do a complete job when working with the data (no normalization is performed for example), and some comparison operations may still not be carried out correctly.

Warning

It is not recommended that you use PHP in a web-server configuration with a version of the SQLite library compiled with UTF-8 support, since libsqlite will abort the process if it detects a problem with the UTF-8 encoding.

See Also

sqlite_lib_version()

Prev | Home | Next
sqlite_last_insert_rowid | Up | sqlite_libversion


sqlite_libversion

(PHP 5)

sqlite_libversion -- Returns the version of the linked SQLite library

Description

string sqlite_libversion ( void )

Returns the version of the linked SQLite library.

See Also

sqlite_libencoding()

Prev | Home | Next
sqlite_libencoding | Up | sqlite_next


sqlite_next

(PHP 5)

sqlite_next

(no version information, might be only in CVS)

SQLiteResult->next

(no version information, might be only in CVS)

SQLiteUnbuffered->next -- Seek to the next row number

Description

bool sqlite_next ( resource result )

Object oriented style (method):

class SQLiteResult {

bool next ( void )

}class SQLiteUnbuffered {

bool next ( void )

}

sqlite_next() advances the result handle result to the next row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns TRUE on success, or FALSE if there are no more rows.

See Also

sqlite_seek()
sqlite_current()
sqlite_rewind()

Prev | Home | Next
sqlite_libversion | Up | sqlite_num_fields


sqlite_num_fields

(PHP 5)

sqlite_num_fields

(no version information, might be only in CVS)

SQLiteResult->numFields

(no version information, might be only in CVS)

SQLiteUnbuffered->numFields -- Returns the number of fields in a result set

Description

int sqlite_num_fields ( resource result )

Object oriented style (method):

class SQLiteResult {

int numFields ( void )

}class SQLiteUnbuffered {

int numFields ( void )

}

Returns the number of fields in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

See Also

sqlite_changes()
sqlite_num_rows()

Prev | Home | Next
sqlite_next | Up | sqlite_num_rows


sqlite_num_rows

(PHP 5)

sqlite_num_rows

(no version information, might be only in CVS)

SQLiteResult->numRows -- Returns the number of rows in a buffered result set

Description

int sqlite_num_rows ( resource result )

Object oriented style (method):

class SQLiteResult {

int numRows ( void )

}

Returns the number of rows in the buffered result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Examples

Example 1. Procedural example

&#60;?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);

echo "Number of rows: $rows";
?&#62;

Example 2. Object-oriented example

&#60;?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db-&#62;query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result-&#62;numRows();

echo "Number of rows: $rows";
?&#62;

See Also

sqlite_changes()
sqlite_query()
sqlite_num_fields()

Prev | Home | Next
sqlite_num_fields | Up | sqlite_open


sqlite_open

(PHP 5)

sqlite_open -- Opens a SQLite database and create the database if it does not exist

Description

resource sqlite_open ( string filename [, int mode [, string &error_message]] )

Object oriented style (constructor):

class SQLiteDatabase {

__construct ( string filename [, int mode [, string &error_message]] )

}

Opens a SQLite database or creates the database if it does not exist.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

Examples

Example 1. sqlite_open() example

&#60;?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result));
} else {
    die($sqliteerror);
}
?&#62;

Notes

Tip: On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you do have such a script, it is recommended that you close the handle prior to forking and then re-open it in the child and/or parent. For more information on this issue, see The C language interface to the SQLite library in the section entitled Multi-Threading And SQLite.

Tip: It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.

Note: Starting with SQLite library version 2.8.2, you can specify :memory: as the filename to create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with the ATTACH DATABASE SQL statement to load other databases and move and query data between them.

Note: SQLite is safe mode and open_basedir aware.

See Also

sqlite_popen()
sqlite_close()
sqlite_factory()

Prev | Home | Next
sqlite_num_rows | Up | sqlite_popen


sqlite_popen

(PHP 5)

sqlite_popen -- Opens a persistent handle to an SQLite database and create the database if it does not exist

Description

resource sqlite_popen ( string filename [, int mode [, string &error_message]] )

This function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.

sqlite_popen() will first check to see if a persistent handle has already been opened for the given filename. If it finds one, it returns that handle to your script, otherwise it opens a fresh handle to the database.

The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).

Note: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled.

To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

See Also

sqlite_open()
sqlite_close()
sqlite_factory()

Prev | Home | Next
sqlite_open | Up | sqlite_prev


sqlite_prev

(PHP 5)

sqlite_prev

(no version information, might be only in CVS)

SQLiteResult->prev -- Seek to the previous row number of a result set

Description

bool sqlite_prev ( resource result )

Object oriented style (method):

class SQLiteResult {

bool prev ( void )

}

sqlite_prev() seeks back the result handle to the previous row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE on success, or FALSE if there are no more previous rows.

See Also

sqlite_has_prev()
sqlite_rewind()
sqlite_next()

Prev | Home | Next
sqlite_popen | Up | sqlite_query


sqlite_query

(PHP 5)

sqlite_query

(no version information, might be only in CVS)

SQLiteDatabase->query -- Executes a query against a given database and returns a result handle

Description

resource sqlite_query ( resource dbhandle, string query [, int result_type [, string &error_msg]] )

resource sqlite_query ( string query, resource dbhandle [, int result_type [, string &error_msg]] )

Object oriented style (method):

class SQLiteDatabase {

SQLiteResult query ( string query [, int result_type [, string &error_msg]] )

}

Executes an SQL statement given by the query against a given database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a result handle or FALSE on failure. For queries that return rows, the result handle can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

Regardless of the query type, this function will return FALSE if the query failed.

sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.

ChangeLog

Version | Description
5.1.0 | Added the error_msg parameter

Notes

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.

When executing multiple queries, the return value of this function will be FALSE if there was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

See Also

sqlite_unbuffered_query()
sqlite_array_query()

Prev | Home | Next
sqlite_prev | Up | sqlite_rewind


sqlite_rewind

(PHP 5)

sqlite_rewind

(no version information, might be only in CVS)

SQLiteResult->rewind -- Seek to the first row number

Description

bool sqlite_rewind ( resource result )

Object oriented style (method):

class SQLiteResult {

bool rewind ( void )

}

sqlite_rewind() seeks back to the first row in the given result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if there are no rows in the result set, TRUE otherwise.

See Also

sqlite_next()
sqlite_current()
sqlite_seek()

Prev | Home | Next
sqlite_query | Up | sqlite_seek


sqlite_seek

(PHP 5)

sqlite_seek

(no version information, might be only in CVS)

SQLiteResult->seek -- Seek to a particular row number of a buffered result set

Description

bool sqlite_seek ( resource result, int rownum )

Object oriented style (method):

class SQLiteResult {

bool seek ( int rownum )

}

sqlite_seek() seeks to the row given by the parameter rownum.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if the row does not exist, TRUE otherwise.

See Also

sqlite_next()
sqlite_current()
sqlite_rewind()

Prev | Home | Next
sqlite_rewind | Up | sqlite_single_query


sqlite_single_query

(PHP 5)

sqlite_single_query

(no version information, might be only in CVS)

SQLiteDatabase->singleQuery -- Executes a query and returns either an array for one single column or the value of the first row

Description

array sqlite_single_query ( resource db, string query [, bool first_row_only [, bool decode_binary]] )

Object oriented style (method):

class SQLiteDatabase {

array singleQuery ( string query [, bool first_row_only [, bool decode_binary]] )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
sqlite_seek | Up | sqlite_udf_decode_binary


sqlite_udf_decode_binary

(PHP 5)

sqlite_udf_decode_binary -- Decode binary data passed as parameters to an UDF

Description

string sqlite_udf_decode_binary ( string data )

sqlite_udf_decode_binary() decodes the binary encoding that was applied to the parameter by either sqlite_udf_encode_binary() or sqlite_escape_string().

You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Examples

Example 1. binary-safe max_length aggregation function example

&#60;?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&#38;$context, $string)
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) &#62; $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&#38;$context)
{
    return $context;
}

sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));

?&#62;

See Also

sqlite_udf_encode_binary()
sqlite_create_function()
sqlite_create_aggregate()

Prev | Home | Next
sqlite_single_query | Up | sqlite_udf_encode_binary


sqlite_udf_encode_binary

(PHP 5)

sqlite_udf_encode_binary -- Encode binary data before returning it from an UDF

Description

string sqlite_udf_encode_binary ( string data )

sqlite_udf_encode_binary() applies a binary encoding to the data so that it can be safely returned from queries (since the underlying libsqlite API is not binary safe).

If there is a chance that your data might be binary unsafe (e.g.: it contains a NUL byte in the middle rather than at the end, or if it has and 0x01 byte as the first character) then you must call this function to encode the return value from your UDF.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Note: Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!

See Also

sqlite_udf_decode_binary()
sqlite_escape_string()
sqlite_create_function()
sqlite_create_aggregate()

Prev | Home | Next
sqlite_udf_decode_binary | Up | sqlite_unbuffered_query


sqlite_unbuffered_query

(PHP 5)

sqlite_unbuffered_query

(no version information, might be only in CVS)

SQLiteDatabase->unbufferedQuery -- Execute a query that does not prefetch and buffer all data

Description

resource sqlite_unbuffered_query ( resource dbhandle, string query [, int result_type [, string &error_msg]] )

resource sqlite_unbuffered_query ( string query, resource dbhandle [, int result_type [, string &error_msg]] )

Object oriented style (method):

class SQLiteDatabase {

SQLiteUnbuffered unbufferedQuery ( string query [, int result_type [, string &error_msg]] )

}

sqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.

This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.

Note:
    Functions such as sqlite_seek(),
    sqlite_rewind(), sqlite_next(),
    sqlite_current(), and
    sqlite_num_rows() do not work on result handles
    returned from sqlite_unbuffered_query().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns a result handle or FALSE on failure.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

ChangeLog

Version | Description
5.1.0 | Added the error_msg parameter

See Also

sqlite_query()

Prev | Home | Next
sqlite_udf_encode_binary | Up | sqlite_valid


sqlite_valid

(PHP 5)

sqlite_valid

(no version information, might be only in CVS)

SQLiteResult->valid

(no version information, might be only in CVS)

SQLiteUnbuffered->valid -- Returns whether more rows are available

Description

bool sqlite_valid ( resource result )

Object oriented style (method):

class SQLiteResult {

bool valid ( void )

}class SQLiteUnbuffered {

bool valid ( void )

}

Finds whether more rows are available from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

sqlite_num_rows()
sqlite_changes()

Prev | Home | Next
sqlite_unbuffered_query | Up | SQLite Functions (PDO_SQLITE)


Secure Shell2 Functions

PHP Manual
Prev Next

CLVI. Secure Shell2 Functions

Introduction

Bindings to the libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.

Installation

Windows binaries may be found at http://snaps.php.net/. To install, download php_ssh2.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_ssh2.dll to your php.ini and restarting your webserver.

extension_dir=c:/php5/exts/
extension=php_ssh2.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Download and install OpenSSL. If you install OpenSSL via your distribution's packaging system be sure to install the development libraries as well. This will typically be a package named openssl-dev, openssl_devel, or some variation thereof.

  • Download and install libssh2. Typically this means executing the following command from the libssh2 source tree. ./configure && make all install.

  • Run the pear installer for PECL/ssh2: pear install ssh2

  • Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.

  • Add extension=ssh2.so to your php.ini

  • Restart your webserver to reload your php.ini settings.

Development Versions: There are currently no stable versions of PECL/ssh2, to force installation of the beta version of PECL/ssh2 execute: pear install ssh2-beta

Compiling PECL/ssh2 without using the PEAR command: Rather than using pear install ssh2 to automatically download and install PECL/ssh2, you may download the tarball from PECL. From the root of the unpacked tarball, run: phpize && ./configure --with-ssh2 && make to generate ssh2.so. Once built, continue the installation from step 4 above.

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/ssh2.

Note: You will need version 0.4 or greater of the libssh2 library (possibly higher, see release notes).

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.

SSH2_FINGERPRINT_MD5 (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.

SSH2_FINGERPRINT_SHA1 (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.

SSH2_FINGERPRINT_HEX (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.

SSH2_FINGERPRINT_RAW (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.

SSH2_TERM_UNIT_CHARS (integer)

Flag to ssh2_shell() specifying that width and height are provided as character sizes.

SSH2_TERM_UNIT_PIXELS (integer)

Flag to ssh2_shell() specifying that width and height are provided in pixel units.

SSH2_DEFAULT_TERM_WIDTH (integer)

Default terminal width requested by ssh2_shell().

SSH2_DEFAULT_TERM_HEIGHT (integer)

Default terminal height requested by ssh2_shell().

SSH2_DEFAULT_TERM_UNIT (integer)

Default terminal units requested by ssh2_shell().

SSH2_STREAM_STDIO (integer)

Flag to ssh2_fetch_stream() requesting STDIO subchannel.

SSH2_STREAM_STDERR (integer)

Flag to ssh2_fetch_stream() requesting STDERR subchannel.

SSH2_DEFAULT_TERMINAL (string)

Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().

Table of Contents
ssh2_auth_hostbased_file -- Authenticate using a public hostkey
ssh2_auth_none -- Authenticate as "none"
ssh2_auth_password -- Authenticate over SSH using a plain password
ssh2_auth_pubkey_file -- Authenticate using a public key
ssh2_connect -- Connect to an SSH server
ssh2_exec -- Execute a command on a remote server
ssh2_fetch_stream -- Fetch an extended data stream
ssh2_fingerprint -- Retreive fingerprint of remote server
ssh2_methods_negotiated -- Return list of negotiated methods
ssh2_publickey_add -- Add an authorized publickey
ssh2_publickey_init -- Initialize Publickey subsystem
ssh2_publickey_list -- List currently authorized publickeys
ssh2_publickey_remove -- Remove an authorized publickey
ssh2_scp_recv -- Request a file via SCP
ssh2_scp_send -- Send a file via SCP
ssh2_sftp_lstat -- Stat a symbolic link
ssh2_sftp_mkdir -- Create a directory
ssh2_sftp_readlink -- Return the target of a symbolic link
ssh2_sftp_realpath -- Resolve the realpath of a provided path string
ssh2_sftp_rename -- Rename a remote file
ssh2_sftp_rmdir -- Remove a directory
ssh2_sftp_stat -- Stat a file on a remote filesystem
ssh2_sftp_symlink -- Create a symlink
ssh2_sftp_unlink -- Delete a file
ssh2_sftp -- Initialize SFTP subsystem
ssh2_shell -- Request an interactive shell
ssh2_tunnel -- Open a tunnel through a remote server

Prev | Home | Next
PDO->sqliteCreateFunction() | Up | ssh2_auth_hostbased_file


ssh2_auth_hostbased_file

(PECL)

ssh2_auth_hostbased_file -- Authenticate using a public hostkey

Description

bool ssh2_auth_hostbased_file ( resource session, string username, string hostname, string pubkeyfile, string privkeyfile [, string passphrase [, string local_username]] )

Authenticate using a public hostkey read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided. If local_username is omitted, then the value for username will be used for it.

Example 1. Authentication using a public hostkey

&#60;?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=&#62;'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
                             '/usr/local/etc/hostkey_rsa.pub',
                             '/usr/local/etc/hostkey_rsa', 'secret',
                             'localusername')) {
  echo "Public Key Hostbased Authentication Successful\n";
} else {
  die('Public Key Hostbased Authentication Failed');
}
?&#62;

Note: ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

Prev | Home | Next
Secure Shell2 Functions | Up | ssh2_auth_none


ssh2_auth_none

(PECL)

ssh2_auth_none -- Authenticate as "none"

Description

mixed ssh2_auth_none ( resource session, string username )

Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods. If the server does accept "none" as an authentication method for username, this function will simply return TRUE.

Example 1. Using ssh2_auth_none() to retreive a list of authentication methods.

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
  echo "Server supports password based authentication\n";
}
?&#62;

Prev | Home | Next
ssh2_auth_hostbased_file | Up | ssh2_auth_password


ssh2_auth_password

(PECL)

ssh2_auth_password -- Authenticate over SSH using a plain password

Description

bool ssh2_auth_password ( resource session, string username, string password )

Authenticate over SSH using a plain password

Example 1. Authenticating with a password

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?&#62;

Prev | Home | Next
ssh2_auth_none | Up | ssh2_auth_pubkey_file


ssh2_auth_pubkey_file

(PECL)

ssh2_auth_pubkey_file -- Authenticate using a public key

Description

bool ssh2_auth_pubkey_file ( resource session, string username, string pubkeyfile, string privkeyfile [, string passphrase] )

Authenticate using a public key read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Example 1. Authentication using a public key

&#60;?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=&#62;'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
                          '/home/username/.ssh/id_rsa.pub',
                          '/home/username/.ssh/id_rsa', 'secret')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}
?&#62;

Prev | Home | Next
ssh2_auth_password | Up | ssh2_connect


ssh2_connect

(PECL)

ssh2_connect -- Connect to an SSH server

Description

resource ssh2_connect ( string host [, int port [, array methods [, array callbacks]]] )

Establish a connection to a remote SSH server and return a resource on success, FALSE on error.

methods may be an associative array with up to four parameters as described below.

Table 1. methods may be an associative array with any or all of the following parameters.

Index | Meaning | Supported Values*
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey | List of hostkey methods to advertise, come separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server. |
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server. |

* - Supported Values are dependent on methods supported by underlying library. See libssh2 documentation for additional information.

Table 2. client_to_server and server_to_client may be an associative array with any or all of the following parameters.

Index | Meaning | Supported Values*
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none
mac | List of MAC methods to advertise, come separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Crypt and MAC method "none": For security reasons, none is disabled by the underlying libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

Table 3. callbackss may be an associative array with any or all of the following parameters.

Index | Meaning | Prototype
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message)
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display)
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet)
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language)

Example 1. Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

&#60;?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

$methods = array(
  'kex' =&#62; 'diffie-hellman-group1-sha1',
  'client_to_server' =&#62; array(
    'crypt' =&#62; '3des-cbc',
    'comp' =&#62; 'none'),
  'server_to_client' =&#62; array(
    'crypt' =&#62; 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' =&#62; 'none'));

$callbacks = array('disconnect' =&#62; 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?&#62;

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

See Also:
ssh2_fingerprint(),
ssh2_auth_none(),
ssh2_auth_password(), and
ssh2_auth_pubkey_file()

Prev | Home | Next
ssh2_auth_pubkey_file | Up | ssh2_exec


ssh2_exec

(PECL)

ssh2_exec -- Execute a command on a remote server

Description

resource ssh2_exec ( resource session, string command [, string pty [, array env [, int width [, int height [, int width_height_type]]]]] )

Execute a command at the remote end and allocate a channel for it. Returns a stream on success or FALSE on failure.

Example 1. Executing a command

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?&#62;

See Also:
ssh2_connect(),
ssh2_shell(), and
ssh2_tunnel()

Prev | Home | Next
ssh2_connect | Up | ssh2_fetch_stream


ssh2_fetch_stream

(PECL)

ssh2_fetch_stream -- Fetch an extended data stream

Description

resource ssh2_fetch_stream ( resource channel, int streamid )

Fetches an alternate substream associated with an SSH2 channel stream identified by streamid. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

Example 1. Opening a shell and retrieving the stderr stream associated with it.

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?&#62;

See Also:
ssh2_shell(),
ssh2_exec(), and
ssh2_connect()

Prev | Home | Next
ssh2_exec | Up | ssh2_fingerprint


ssh2_fingerprint

(PECL)

ssh2_fingerprint -- Retreive fingerprint of remote server

Description

string ssh2_fingerprint ( resource session [, int flags] )

Returns a server hostkey hash from an active session. Defaults to MD5 fingerprint encoded as ASCII hex values.

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW. Defaults to SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX.

Example 1. Checking the fingerprint against a known value

&#60;?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack?");
}
?&#62;

Prev | Home | Next
ssh2_fetch_stream | Up | ssh2_methods_negotiated


ssh2_methods_negotiated

(PECL)

ssh2_methods_negotiated -- Return list of negotiated methods

Description

array ssh2_methods_negotiated ( resource session )

Returns list of negotiated methods.

Example 1. Determining what methods were negotiated

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?&#62;

See Also: ssh2_connect()

Prev | Home | Next
ssh2_fingerprint | Up | ssh2_publickey_add


ssh2_scp_recv

(PECL)

ssh2_scp_recv -- Request a file via SCP

Description

bool ssh2_scp_recv ( resource session, string remote_file, string local_file )

Copy a file from the remote server to the local filesystem using the SCP protocol.

Example 1. Downloading a file via SCP

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?&#62;

See Also: ssh2_scp_send(), and copy()

Prev | Home | Next
ssh2_publickey_remove | Up | ssh2_scp_send


ssh2_scp_send

(PECL)

ssh2_scp_send -- Send a file via SCP

Description

bool ssh2_scp_send ( resource session, string local_file, string remote_file [, int create_mode] )

Copy a file from the local filesystem to the remote server using the SCP protocol. The file will be created with the mode specified by create_mode.

Example 1. Uploading a file via SCP

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?&#62;

See Also: ssh2_scp_recv(), and copy()

Prev | Home | Next
ssh2_scp_recv | Up | ssh2_sftp_lstat


ssh2_sftp_lstat

(PECL)

ssh2_sftp_lstat -- Stat a symbolic link

Description

array ssh2_sftp_lstat ( resource sftp, string path )

Stats a symbolic link on the remote filesystem without following the link. This function is similar to using the lstat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.

Example 1. Stating a symbolic link via SFTP

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?&#62;

See Also:
ssh2_sftp_stat(),
lstat(), and
stat()

Prev | Home | Next
ssh2_scp_send | Up | ssh2_sftp_mkdir


ssh2_sftp_mkdir

(PECL)

ssh2_sftp_mkdir -- Create a directory

Description

bool ssh2_sftp_mkdir ( resource sftp, string dirname [, int mode [, bool recursive]] )

Creates a directory on the remote file server with permissions set to mode. If recursive is TRUE any parent directories required for dirname will be automatically created as well. This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

Example 1. Creating a directory on a remote server

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or:  mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?&#62;

See Also: mkdir(), and ssh2_sftp_rmdir()

Prev | Home | Next
ssh2_sftp_lstat | Up | ssh2_sftp_readlink


ssh2_sftp_readlink

(PECL)

ssh2_sftp_readlink -- Return the target of a symbolic link

Description

string ssh2_sftp_readlink ( resource sftp, string link )

Returns the target of a symbolic link.

Example 1. Reading a symbolic link

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?&#62;

See Also: readlink(), and ssh2_sftp_symlink()

Prev | Home | Next
ssh2_sftp_mkdir | Up | ssh2_sftp_realpath


ssh2_sftp_realpath

(PECL)

ssh2_sftp_realpath -- Resolve the realpath of a provided path string

Description

string ssh2_sftp_realpath ( resource sftp, string filename )

Translates filename into the effective real path on the remote filesystem.

Example 1. Resolving a pathname

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?&#62;

See Also:
realpath(), and
ssh2_sftp_symlink()
ssh2_sftp_readlink()

Prev | Home | Next
ssh2_sftp_readlink | Up | ssh2_sftp_rename


ssh2_sftp_rename

(PECL)

ssh2_sftp_rename -- Rename a remote file

Description

bool ssh2_sftp_rename ( resource sftp, string from, string to )

Renames a file on the remote filesystem.

Example 1. Renaming a file via sftp

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?&#62;

See Also: rename()

Prev | Home | Next
ssh2_sftp_realpath | Up | ssh2_sftp_rmdir


ssh2_sftp_rmdir

(PECL)

ssh2_sftp_rmdir -- Remove a directory

Description

bool ssh2_sftp_rmdir ( resource sftp, string dirname )

Removes a directory from the remote file server. This function is similar to using rmdir() with the ssh2.sftp:// wrapper.

Example 1. Removing a directory on a remote server

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or:  rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?&#62;

See Also: rmdir(), and ssh2_sftp_mkdir()

Prev | Home | Next
ssh2_sftp_rename | Up | ssh2_sftp_stat


ssh2_sftp_stat

(PECL)

ssh2_sftp_stat -- Stat a file on a remote filesystem

Description

array ssh2_sftp_stat ( resource sftp, string path )

Stats a file on the remote filesystem following any symbolic links. This function is similar to using the stat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.

Example 1. Stating a file via SFTP

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_stat($sftp, '/path/to/file');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?&#62;

See Also:
ssh2_sftp_lstat(),
lstat(), and
stat()

Prev | Home | Next
ssh2_sftp_rmdir | Up | ssh2_sftp_symlink


ssh2_sftp_symlink

(PECL)

ssh2_sftp_symlink -- Create a symlink

Description

bool ssh2_sftp_symlink ( resource sftp, string target, string link )

Creates a symbolic link named link on the remote filesystem pointing to target.

Example 1. Creating a symbolic link

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?&#62;

See Also: symlink(), and ssh2_sftp_readlink()

Prev | Home | Next
ssh2_sftp_stat | Up | ssh2_sftp_unlink


ssh2_sftp_unlink

(PECL)

ssh2_sftp_unlink -- Delete a file

Description

bool ssh2_sftp_unlink ( resource sftp, string filename )

Deletes a file on the remote filesystem

Example 1. Deleting a file

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?&#62;

See Also: unlink()

Prev | Home | Next
ssh2_sftp_symlink | Up | ssh2_sftp


ssh2_sftp

(PECL)

ssh2_sftp -- Initialize SFTP subsystem

Description

resource ssh2_sftp ( resource session )

Request the SFTP subsystem from an already connected SSH2 server.

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.

Example 1. Opening a file via SFTP

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
?&#62;

See Also: ssh2_scp_send(), and ssh2_scp_recv()

Prev | Home | Next
ssh2_sftp_unlink | Up | ssh2_shell


ssh2_shell

(PECL)

ssh2_shell -- Request an interactive shell

Description

resource ssh2_shell ( resource session [, string term_type [, array env [, int width [, int height [, int width_height_type]]]]] )

Open a shell at the remote end and allocate a stream for it. term_type should correspond to one of the entries in the target system's /etc/termcap file and defaults to vanilla. env may be passed as an associative array of name/value pairs to set in the target environment.

width, and height define the width and height of the virtual terminal allocated for the shell process. width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Example 1. Executing a command

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
?&#62;

See Also:
ssh2_exec(),
ssh2_tunnel(), and
ssh2_fetch_stream()

Prev | Home | Next
ssh2_sftp | Up | ssh2_tunnel


ssh2_tunnel

(PECL)

ssh2_tunnel -- Open a tunnel through a remote server

Description

resource ssh2_tunnel ( resource session, string host, int port )

Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.

Example 1. Opening a tunnel to an arbitrary host

&#60;?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?&#62;

See Also: ssh2_connect(), and fsockopen()

Prev | Home | Next
ssh2_shell | Up | Statistics Functions


Stream Functions

PHP Manual
Prev Next

CLVIII. Stream Functions

Introduction

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Appendix M), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Chapter 44. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Appendix M for a list of PHP builtin wrappers. If no wrapper is specified, the function default is used (typically file://).

  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Appendix M for a description of targets for builtin streams.

Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Chapter 44. To access the list of currently registered filters, use stream_get_filters().

Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found with the list of built-in wrappers (See Appendix M).

In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:

void my_notifier ( int notification_code, int severity, string message, int message_code, int bytes_transferred, int bytes_max )

notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependent on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.

Installation

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.

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.

Constant | Description
STREAM_FILTER_READ * | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE * | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL * | This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON * | Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME * | Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL * | Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
STREAM_USE_PATH | Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT * | Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT * | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT * | Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND * | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN * | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE * | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED * | There is no more data available on the stream.
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + | Provides a ICMP socket.
STREAM_IPPROTO_IP + | Provides a IP socket.
STREAM_IPPROTO_RAW + | Provides a RAW socket.
STREAM_IPPROTO_TCP + | Provides a TCP socket.
STREAM_IPPROTO_UDP + | Provides a UDP socket.
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + | Unix system internal protocols.
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD | Used with stream_socket_shutdown() to disable further receptions. Added in PHP 5.2.1.
STREAM_SHUT_WR | Used with stream_socket_shutdown() to disable further transmissions. Added in PHP 5.2.1.
STREAM_SHUT_RDWR | Used with stream_socket_shutdown() to disable further receptions and transmissions. Added in PHP 5.2.1.

Note: The constants marked with * are just available since PHP 5.0.0.

Note: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.

Examples

Example 1. Using file_get_contents() to retrieve data from multiple sources

&#60;?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?&#62;

Example 2. Making a POST request to an https server

&#60;?php
/* Send POST request to https://secure.example.com/form_action.php
 * Include form elements named "foo" and "bar" with dummy values
 */

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&#38;bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, "$data\r\n");
fwrite($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
  $headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
  $body .= fgets($sock, 4096);

fclose($sock);
?&#62;

Example 3. Writing data to a compressed file

&#60;?php
/* Create a compressed file containing an arbitrarty string
 * File can be read back using compress.zlib stream or just
 * decompressed from the command line using 'gzip -d foo-bar.txt.gz'
 */
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?&#62;

Table of Contents
stream_bucket_append -- Append bucket to brigade
stream_bucket_make_writeable -- Return a bucket object from the brigade for operating on
stream_bucket_new -- Create a new bucket for use on the current stream
stream_bucket_prepend -- Prepend bucket to brigade
stream_context_create -- Create a streams context
stream_context_get_default -- Retreive the default streams context
stream_context_get_options -- Retrieve options for a stream/wrapper/context
stream_context_set_option -- Sets an option for a stream/wrapper/context
stream_context_set_params -- Set parameters for a stream/wrapper/context
stream_copy_to_stream -- Copies data from one stream to another
stream_encoding -- Set character set for stream encoding
stream_filter_append -- Attach a filter to a stream
stream_filter_prepend -- Attach a filter to a stream
stream_filter_register -- Register a stream filter implemented as a PHP class derived from php_user_filter
stream_filter_remove -- Remove a filter from a stream
stream_get_contents -- Reads remainder of a stream into a string
stream_get_filters -- Retrieve list of registered filters
stream_get_line -- Gets line from stream resource up to a given delimiter
stream_get_meta_data -- Retrieves header/meta data from streams/file pointers
stream_get_transports -- Retrieve list of registered socket transports
stream_get_wrappers -- Retrieve list of registered streams
stream_register_wrapper -- Alias of stream_wrapper_register()
stream_resolve_include_path -- Determine what file will be opened by calls to fopen() with a relative path
stream_select -- Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
stream_set_blocking -- Set blocking/non-blocking mode on a stream
stream_set_timeout -- Set timeout period on a stream
stream_set_write_buffer -- Sets file buffering on the given stream
stream_socket_accept -- Accept a connection on a socket created by stream_socket_server()
stream_socket_client -- Open Internet or Unix domain socket connection
stream_socket_enable_crypto -- Turns encryption on/off on an already connected socket
stream_socket_get_name -- Retrieve the name of the local or remote sockets
stream_socket_pair -- Creates a pair of connected, indistinguishable socket streams
stream_socket_recvfrom -- Receives data from a socket, connected or not
stream_socket_sendto -- Sends a message to a socket, whether it is connected or not
stream_socket_server -- Create an Internet or Unix domain server socket
stream_socket_shutdown -- Shutdown a full-duplex connection
stream_wrapper_register -- Register a URL wrapper implemented as a PHP class
stream_wrapper_restore -- Restores a previously unregistered built-in wrapper
stream_wrapper_unregister -- Unregister a URL wrapper

Prev | Home | Next
stats_variance | Up | stream_bucket_append


stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create -- Create a streams context

Description

resource stream_context_create ( [array options [, array params]] )

Creates and returns a stream context with any options supplied in options preset.

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value. It defaults to an empty array.

params must be an associative array in the format $arr['parameter'] = $value. Refer to stream_context_set_params() for a listing of standard stream parameters.

Note: The params argument was added to PHP 6.0.0.

Example 1. Using stream_context_create()

&#60;?php
$opts = array(
  'http'=&#62;array(
    'method'=&#62;"GET",
    'header'=&#62;"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?&#62;

See also stream_context_set_option(), and Listing of supported wrappers with context options (Appendix M).

Prev | Home | Next
stream_bucket_prepend | Up | stream_context_get_default


stream_context_get_default

(PHP 5 >= 5.1.0RC1)

stream_context_get_default -- Retreive the default streams context

Description

resource stream_context_get_default ( [array options] )

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Example 1. Using stream_context_get_default()

&#60;?php
$default_opts = array(
  'http'=&#62;array(
    'method'=&#62;"GET",
    'header'=&#62;"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=&#62;"tcp://10.54.1.39:8000"
  )
);

$alternate_opts = array(
  'http'=&#62;array(
    'method'=&#62;"POST",
    'header'=&#62;"Content-type: application/x-www-form-urlencoded\r\n" .
              "Content-length: " . strlen("baz=bomb"),
    'content'=&#62;"baz=bomb"
  )
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com', false, $alternate);

?&#62;

See also stream_context_create(), and Listing of supported wrappers with context options (Appendix M).

Prev | Home | Next
stream_context_create | Up | stream_context_get_options


stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5)

stream_context_get_options -- Retrieve options for a stream/wrapper/context

Description

array stream_context_get_options ( resource stream_or_context )

Returns an array of options on the specified stream or context.

Prev | Home | Next
stream_context_get_default | Up | stream_context_set_option


stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_option -- Sets an option for a stream/wrapper/context

Description

bool stream_context_set_option ( resource stream_or_context, string wrapper, string option, mixed value )

bool stream_context_set_option ( resource stream_or_context, array options )

Sets an option on the specified context. value is set to option for wrapper

Prev | Home | Next
stream_context_get_options | Up | stream_context_set_params


stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_params -- Set parameters for a stream/wrapper/context

Description

bool stream_context_set_params ( resource stream_or_context, array params )

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Table 1. Parameters

Parameters | Purpose
notification | Name of user-defined callback function to be called whenever a stream triggers a notification.
options | Array of options as in stream_context_create().

Prev | Home | Next
stream_context_set_option | Up | stream_copy_to_stream


stream_copy_to_stream

(PHP 5)

stream_copy_to_stream -- Copies data from one stream to another

Description

int stream_copy_to_stream ( resource source, resource dest [, int maxlength [, int offset]] )

Makes a copy of up to maxlength bytes of data from the current position (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.

Parameters

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Return Values

Returns the total count of bytes copied.

ChangeLog

Version | Description
5.1.0 | Added the offset parameter

Examples

Example 1. A stream_copy_to_stream() example

&#60;?php
$src = fopen('http://www.example.com', 'r');
$dest1 = fopen('first1k.txt', 'w');
$dest2 = fopen('remainder.txt', 'w');

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?&#62;

See Also

copy()

Prev | Home | Next
stream_context_set_params | Up | stream_encoding


stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_append -- Attach a filter to a stream

Description

resource stream_filter_append ( resource stream, string filtername [, int read_write [, mixed params]] )

Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Example 1. Controlling where filters are applied

&#60;?php
/* Open a test file for reading and writing */
$fp = fopen('test.txt', 'w+');

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?&#62;

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

See also
stream_filter_register(),
stream_filter_prepend(), and
stream_get_filters().

Prev | Home | Next
stream_encoding | Up | stream_filter_prepend


stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_prepend -- Attach a filter to a stream

Description

resource stream_filter_prepend ( resource stream, string filtername [, int read_write [, mixed params]] )

Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

See also stream_filter_register(), and stream_filter_append().

Prev | Home | Next
stream_filter_append | Up | stream_filter_register


stream_filter_register

(PHP 5)

stream_filter_register -- Register a stream filter implemented as a PHP class derived from php_user_filter

Description

bool stream_filter_register ( string filtername, string classname )

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions as defined below. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

stream_filter_register() will return FALSE if the filtername is already defined.

int filter ( resource in, resource out, int &consumed, bool closing )

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()). in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered. out is a resource pointing to a second bucket brigade into which your modified buckets should be placed. consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket. If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE The filter method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.

bool onCreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. Your implementation of this method should return FALSE on failure, or TRUE on success.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().

void onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialzed during onCreate this would be the time to destroy or dispose of them.

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

Example 1. Filter for capitalizing characters on foo-bar.txt stream

&#60;?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function filter($in, $out, &#38;$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket-&#62;data = strtoupper($bucket-&#62;data);
      $consumed += $bucket-&#62;datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?&#62;

The above example will output:

LINE1
WORD - 2
EASY AS 123

Example 2. Registering a generic filter class to match multiple filter names.

&#60;?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var $mode;

  function filter($in, $out, &#38;$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      if ($this-&#62;mode == 1) {
        $bucket-&#62;data = strtoupper($bucket-&#62;data);
      } elseif ($this-&#62;mode == 0) {
        $bucket-&#62;data = strtolower($bucket-&#62;data);
      }

      $consumed += $bucket-&#62;datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }

  function onCreate()
  {
    if ($this-&#62;filtername == 'str.toupper') {
      $this-&#62;mode = 1;
    } elseif ($this-&#62;filtername == 'str.tolower') {
      $this-&#62;mode = 0;
    } else {
      /* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      return false;
    }

    return true;
  }
}

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened
   We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?&#62;

The above example will output:

LINE1
WORD - 2
EASY AS 123

See also
stream_wrapper_register(),
stream_filter_prepend(), and
stream_filter_append().

Prev | Home | Next
stream_filter_prepend | Up | stream_filter_remove


stream_filter_remove

(PHP 5 >= 5.1.0RC1)

stream_filter_remove -- Remove a filter from a stream

Description

bool stream_filter_remove ( resource stream_filter )

Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.

Example 1. Dynamicly refiltering a stream

&#60;?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

$rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
fwrite($fp, "This is ");
stream_filter_remove($rot13_filter);
fwrite($fp, "a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

/* Expected Output
   ---------------

Guvf vf a test

 */
?&#62;

See also
stream_filter_register(),
stream_filter_append(), and
stream_filter_prepend().

Prev | Home | Next
stream_filter_register | Up | stream_get_contents


stream_get_contents

(PHP 5)

stream_get_contents -- Reads remainder of a stream into a string

Description

string stream_get_contents ( resource handle [, int maxlength [, int offset]] )

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Parameters

handle (resource)

A stream resource (e.g. returned from fopen())

maxlength (integer)

The maximum bytes to read. Defaults to -1 (read all the remaining buffer).

offset (integer)

Seek to the specified offset before reading. Added in PHP 5.1.0.

Return Values

Returns a string, or FALSE on failure.

Examples

Example 1. stream_get_contents() example

&#60;?php

if ($stream = fopen('http://www.example.com', 'r')) {
    // print all the page starting at the offset 10
    echo stream_get_contents($stream, -1, 10);

    fclose($stream);
}

if ($stream = fopen('http://www.example.net', 'r')) {
    // print the first 5 bytes
    echo stream_get_contents($stream, 5);

    fclose($stream);
}

?&#62;

See Also

fgets()
fread()
fpassthru()

Note: This function is binary-safe.

Prev | Home | Next
stream_filter_remove | Up | stream_get_filters


stream_get_filters

(PHP 5)

stream_get_filters -- Retrieve list of registered filters

Description

array stream_get_filters ( void )

Returns an indexed array containing the name of all stream filters available on the running system.

Example 1. Using stream_get_filters()

&#60;?php
$streamlist = stream_get_filters();
print_r($streamlist);
?&#62;

Output will be similar to the following. Note: there may be more or fewer filters in your version of PHP.

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

See also stream_filter_register(), and stream_get_wrappers().

Prev | Home | Next
stream_get_contents | Up | stream_get_line


stream_get_line

(PHP 5)

stream_get_line -- Gets line from stream resource up to a given delimiter

Description

string stream_get_line ( resource handle, int length [, string ending] )

Returns a string of up to length bytes read from the file pointed to by handle. Reading ends when length bytes have been read, when the string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

If an error occurs, returns FALSE.

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

See also fread(),
fgets(), and
fgetc().

Prev | Home | Next
stream_get_filters | Up | stream_get_meta_data


stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5)

stream_get_meta_data -- Retrieves header/meta data from streams/file pointers

Description

array stream_get_meta_data ( resource stream )

Returns information about an existing stream. The stream can be any stream created by fopen(), fsockopen() and pfsockopen(). The result array contains the following items:

  • timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().

  • blocked (bool) - TRUE if the stream is in blocking IO mode. See stream_set_blocking().

  • eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

  • unread_bytes (int) - the number of bytes currently contained in the PHP's own internal buffer.

    Note: You shouldn't use this value in a script.

The following items were added in PHP 4.3:

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Appendix M for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Appendix M for more information about wrappers and their wrapper data.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Documentation on filters can be found in the Filters appendix.

Note: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.

In PHP 4.3 and later, socket_get_status() is an alias for this function.

Note: This function does NOT work on sockets created by the Socket extension.

The following items were added in PHP 5.0:

  • mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)

  • seekable (bool) - whether the current stream can be seeked.

  • uri (string) - the URI/filename associated with this stream.

Prev | Home | Next
stream_get_line | Up | stream_get_transports


stream_get_transports

(PHP 5)

stream_get_transports -- Retrieve list of registered socket transports

Description

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Example 1. Using stream_get_transports()

&#60;?php
$xportlist = stream_get_transports();
print_r($xportlist);
?&#62;

Output will be similar to the following. Note: there may be more or fewer transports in your version of PHP.

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

See also stream_get_filters(), and stream_get_wrappers().

Prev | Home | Next
stream_get_meta_data | Up | stream_get_wrappers


stream_get_wrappers

(PHP 5)

stream_get_wrappers -- Retrieve list of registered streams

Description

array stream_get_wrappers ( void )

Returns an indexed array containing the name of all stream wrappers available on the running system.

Example 1. stream_get_wrappers() example

&#60;?php
print_r(stream_get_wrappers());
?&#62;

The above example will output something similar to:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Example 2. Checking for the existence of a stream wrapper

&#60;?php
// check for the existence of the bzip2 stream wrapper
if (in_array('compress.bzip2', stream_get_wrappers())) {
    echo 'compress.bzip2:// support enabled.';
} else {
    echo 'compress.bzip2:// support not enabled.';
}
?&#62;

See also stream_wrapper_register().

Prev | Home | Next
stream_get_transports | Up | stream_register_wrapper


stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5)

stream_register_wrapper -- Alias of stream_wrapper_register()

Description

This function is an alias of stream_wrapper_register(). This function is included for compatability with PHP 4.3.0 and PHP 4.3.1 only. stream_wrapper_register() should be used instead.

Prev | Home | Next
stream_get_wrappers | Up | stream_resolve_include_path


stream_select

(PHP 4 >= 4.3.0, PHP 5)

stream_select -- Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

Description

int stream_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec] )

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

The streams listed in the write array will be watched to see if a write will not block.

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Note: When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

The tv_sec and tv_usec together form the timeout parameter, tv_sec specifies the number of seconds while tv_usec the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If tv_sec and tv_usec are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams. If tv_sec is NULL stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

Warning

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

&#60;?php
/* Prepare the read array */
$read   = array($stream1, $stream2);
$write  = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
    /* Error handling */
} elseif ($num_changed_streams &#62; 0) {
    /* At least on one of the streams something interesting happened */
}
?&#62;

Note: Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

&#60;?php
$e = NULL;
stream_select($r, $w, $e, 0);
?&#62;

Note: Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:

&#60;?php
$e = NULL;
if (false === stream_select($r, $w, $e, 0)) {
    echo "stream_select() failed\n";
}
?&#62;

Note: If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Note: Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.

See also stream_set_blocking().

Prev | Home | Next
stream_resolve_include_path | Up | stream_set_blocking


stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5)

stream_set_blocking -- Set blocking/non-blocking mode on a stream

Description

bool stream_set_blocking ( resource stream, int mode )

If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

Returns TRUE on success or FALSE on failure.

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Note: Prior to PHP 4.3, this function only worked on socket based streams. Since PHP 4.3, this function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

See also stream_select().

Prev | Home | Next
stream_select | Up | stream_set_timeout


stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5)

stream_set_timeout -- Set timeout period on a stream

Description

bool stream_set_timeout ( resource stream, int seconds [, int microseconds] )

Sets the timeout value on stream, expressed in the sum of seconds and microseconds. Returns TRUE on success or FALSE on failure.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Example 1. stream_set_timeout() example

&#60;?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}
?&#62;

Note: As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.

Note: This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

See also fsockopen() and fopen().

Prev | Home | Next
stream_set_blocking | Up | stream_set_write_buffer


stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5)

stream_set_write_buffer -- Sets file buffering on the given stream

Description

int stream_set_write_buffer ( resource stream, int buffer )

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. stream_set_write_buffer() sets the buffering for write operations on the given filepointer stream to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

The function returns 0 on success, or EOF if the request cannot be honored.

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

Example 1. stream_set_write_buffer() example

&#60;?php
$fp = fopen($file, "w");
if ($fp) {
  stream_set_write_buffer($fp, 0);
  fwrite($fp, $output);
  fclose($fp);
}
?&#62;

See also fopen() and fwrite().

Prev | Home | Next
stream_set_timeout | Up | stream_socket_accept


stream_socket_accept

(PHP 5)

stream_socket_accept -- Accept a connection on a socket created by stream_socket_server()

Description

resource stream_socket_accept ( resource server_socket [, float timeout [, string &peername]] )

Accept a connection on a socket previously created by stream_socket_server(). If timeout is specified, the default socket accept timeout will be overridden with the time specified in seconds. The name (address) of the client which connected will be passed back in peername if included and available from the selected transport.

peername can also be determined later using stream_socket_get_name().

If the call fails, it will return FALSE.

Warning

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

See also stream_socket_server(),
stream_socket_get_name(),
stream_set_blocking(),
stream_set_timeout(),
fgets(),
fgetss(), fwrite(),
fclose(), feof(), and
the Curl extension.

Prev | Home | Next
stream_set_write_buffer | Up | stream_socket_client


stream_socket_client

(PHP 5)

stream_socket_client -- Open Internet or Unix domain socket connection

Description

resource stream_socket_client ( string remote_socket [, int &errno [, string &errstr [, float timeout [, int flags [, resource context]]]]] )

Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem. The optional timeout can be used to set a timeout in seconds for the connect system call. flags is a bitmask field which may be set to any combination of connection flags. Currently the selection of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

Note: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to stream_socket_client() only applies while connecting the socket.

stream_socket_client() returns a
stream resource which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendix O for a list of built in transports.

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Example 1. stream_socket_client() Example

&#60;?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)&#60;br /&#62;\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?&#62;
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Example 2. Using UDP connection

&#60;?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr&#60;br /&#62;\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?&#62;

Warning

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1) you must enclose the IP in square brackets. For example, tcp://[fe80::1]:80.

See also stream_socket_server(),
stream_set_blocking(),
stream_set_timeout(),
stream_select(),
fgets(),
fgetss(), fwrite(),
fclose(), feof(), and
the Curl extension.

Prev | Home | Next
stream_socket_accept | Up | stream_socket_enable_crypto


stream_socket_enable_crypto

(PHP 5 >= 5.1.0RC1)

stream_socket_enable_crypto -- Turns encryption on/off on an already connected socket

Description

mixed stream_socket_enable_crypto ( resource stream, bool enable [, int crypto_type [, resource session_stream]] )

When called with the crypto_type parameter, stream_socket_enable_crypto() will setup encryption on the stream using the specified method.

Valid values for crypto_type

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT

  • STREAM_CRYPTO_METHOD_TLS_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv2_SERVER

  • STREAM_CRYPTO_METHOD_SSLv3_SERVER

  • STREAM_CRYPTO_METHOD_SSLv23_SERVER

  • STREAM_CRYPTO_METHOD_TLS_SERVER

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

If this stream should be seeded with settings from an already established crypto enabled stream, pass that stream's resource variable in the fourth parameter.

Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

Example 1. stream_socket_enable_crypto() Example

&#60;?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
  die("Unable to connect: $errstr ($errno)");
}
/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");
/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);
while ($motd = fgets($fp)) {
  echo $motd;
}
fclose($fp);
?&#62;

Reference CX, OpenSSL Functions, and Appendix O

Prev | Home | Next
stream_socket_client | Up | stream_socket_get_name


stream_socket_get_name

(PHP 5)

stream_socket_get_name -- Retrieve the name of the local or remote sockets

Description

string stream_socket_get_name ( resource handle, bool want_peer )

Returns the local or remote name of a given socket connection. If want_peer is set to TRUE the remote socket name will be returned, if it is set to FALSE the local socket name will be returned.

See also stream_socket_accept().

Prev | Home | Next
stream_socket_enable_crypto | Up | stream_socket_pair


stream_socket_pair

(PHP 5 >= 5.1.0RC1)

stream_socket_pair -- Creates a pair of connected, indistinguishable socket streams

Description

array stream_socket_pair ( int domain, int type, int protocol )

stream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).

Parameters

domain

The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM

protocol

The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP

Note: Please consult the Streams constant list for further details on each constant.

Return Values

Returns an array with the two socket resources on success, or FALSE on failure.

Examples

Example 1. A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.

&#60;?php

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid     = pcntl_fork();

if ($pid == -1) {
     die('could not fork');

} else if ($pid) {
     /* parent */
    fclose($sockets[0]);

    fwrite($sockets[1], "child PID: $pid\n");
    echo fgets($sockets[1]);

    fclose($sockets[1]);

} else {
    /* child */
    fclose($sockets[1]);

    fwrite($sockets[0], "message from child\n");
    echo fgets($sockets[0]);

    fclose($sockets[0]);
}

?&#62;

The above example will output something similar to:

child PID: 1378
message from child

Prev | Home | Next
stream_socket_get_name | Up | stream_socket_recvfrom


stream_socket_recvfrom

(PHP 5)

stream_socket_recvfrom -- Receives data from a socket, connected or not

Description

string stream_socket_recvfrom ( resource socket, int length [, int flags [, string &address]] )

The function stream_socket_recvfrom() accepts data from a remote socket up to length bytes. If address is provided it will be populated with the address of the remote socket.

The value of flags can be any combination of the following:

Table 1. possible values for flags

STREAM_OOB | Process OOB (out-of-band) data.
STREAM_PEEK | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

Example 1. stream_socket_recvfrom() Example

&#60;?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't comsume it. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?&#62;

Note: If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

Note: Calls to stream_socket_recvfrom() on socket-based streams, after calls to buffer-based stream functions (like fread() or stream_get_line()) read data directly from the socket and bypass the stream buffer.

See also
stream_socket_sendto(),
stream_socket_client(), and
stream_socket_server().

Prev | Home | Next
stream_socket_pair | Up | stream_socket_sendto


stream_socket_sendto

(PHP 5)

stream_socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int stream_socket_sendto ( resource socket, string data [, int flags [, string address]] )

The function stream_socket_sendto() sends the data specified by data through the socket specified by socket. The address specified when the socket stream was created will be used unless an alternate address is specified in address.

The value of flags can be any combination of the following:

Table 1. possible values for flags

STREAM_OOB Process OOB (out-of-band) data.

Example 1. stream_socket_sendto() Example

&#60;?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?&#62;

See also
stream_socket_recvfrom(),
stream_socket_client(), and
stream_socket_server().

Prev | Home | Next
stream_socket_recvfrom | Up | stream_socket_server


stream_socket_server

(PHP 5)

stream_socket_server -- Create an Internet or Unix domain server socket

Description

resource stream_socket_server ( string local_socket [, int &errno [, string &errstr [, int flags [, resource context]]]] )

Creates a stream or datagram socket on the specified local_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem. flags is a bitmask field which may be set to any combination of socket creation flags. The default value of flags is STREAM_SERVER_BIND | STREAM_SERVER_LISTEN.

Note: For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendix O for a list of bulitin transports.

Example 1. Using TCP server sockets

&#60;?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)&#60;br /&#62;\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
    fclose($conn);
  }
  fclose($socket);
}
?&#62;

The example below shows how to act as a time server which can respond to time queries as shown in an example on stream_socket_client().

Note: Most systems require root access to create a server socket on a port below 1024.

Example 2. Using UDP server sockets

&#60;?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    die("$errstr ($errno)");
}

do {
    $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
    echo "$peer\n";
    stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);

?&#62;

Note: When specifying a numerical IPv6 address (e.g. fe80::1) you must enclose the IP in square brackets. For example, tcp://[fe80::1]:80.

See also stream_socket_client(),
stream_set_blocking(),
stream_set_timeout(),
fgets(),
fgetss(), fwrite(),
fclose(), feof(), and
the Curl extension.

Prev | Home | Next
stream_socket_sendto | Up | stream_socket_shutdown


stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5)

stream_wrapper_register -- Register a URL wrapper implemented as a PHP class

Description

bool stream_wrapper_register ( string protocol, string classname )

stream_wrapper_register() allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

To implement a wrapper, you need to define a class with a number of member functions, as defined below. When someone fopens your stream, PHP will create an instance of classname and then call methods on that instance. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

Note: As of PHP 5.0.0 the instance of classname will be populated with a context property referencing a Context Resource which may be accessed with stream_context_get_options(). If no context was passed to the stream creation function, context will be set to NULL.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

bool stream_open ( string path, string mode, int options, string opened_path )

This method is called immediately after your stream object is created. path specifies the URL that was passed to fopen() and that this object is expected to retrieve. You can use parse_url() to break it apart.

mode is the mode used to open the file, as detailed for fopen(). You are responsible for checking that mode is valid for the path requested.

options holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_USE_PATH | If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

If the path is opened successfully, and STREAM_USE_PATH is set in options, you should set opened_path to the full path of the file/resource that was actually opened.

If the requested resource was opened successfully, you should return TRUE, otherwise you should return FALSE

void stream_close ( void )

This method is called when the stream is closed, using fclose(). You must release any resources that were locked or allocated by the stream.

string stream_read ( int count )

This method is called in response to fread() and fgets() calls on the stream. You must return up-to count bytes of data from the current read/write position as a string. If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string. You must also update the read/write position of the stream by the number of bytes that were successfully read.

int stream_write ( string data )

This method is called in response to fwrite() calls on the stream. You should store data into the underlying storage used by your stream. If there is not enough room, try to store as many bytes as possible. You should return the number of bytes that were successfully stored in the stream, or 0 if none could be stored. You must also update the read/write position of the stream by the number of bytes that were successfully written.

bool stream_eof ( void )

This method is called in response to feof() calls on the stream. You should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

int stream_tell ( void )

This method is called in response to ftell() calls on the stream. You should return the current read/write position of the stream.

bool stream_seek ( int offset, int whence )

This method is called in response to fseek() calls on the stream. You should update the read/write position of the stream according to offset and whence. See fseek() for more information about these parameters. Return TRUE if the position was updated, FALSE otherwise.

bool stream_flush ( void )

This method is called in response to fflush() calls on the stream. If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now. Return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

array stream_stat ( void )

This method is called in response to fstat() calls on the stream and should return an array containing the same values as appropriate for the stream.

bool unlink ( string path )

This method is called in response to unlink() calls on URL paths associated with the wrapper and should attempt to delete the item specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support unlinking.

Note: Userspace wrapper unlink method is not supported prior to PHP 5.0.0.

bool rename ( string path_from, string path_to )

This method is called in response to rename() calls on URL paths associated with the wrapper and should attempt to rename the item specified by path_from to the specification given by path_to. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support renaming.

Note: Userspace wrapper rename method is not supported prior to PHP 5.0.0.

bool mkdir ( string path, int mode, int options )

This method is called in response to mkdir() calls on URL paths associated with the wrapper and should attempt to create the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support creating directories. Posible values for options include STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE.

Note: Userspace wrapper mkdir method is not supported prior to PHP 5.0.0.

bool rmdir ( string path, int options )

This method is called in response to rmdir() calls on URL paths associated with the wrapper and should attempt to remove the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support removing directories. Possible values for options include STREAM_REPORT_ERRORS.

Note: Userspace wrapper rmdir method is not supported prior to PHP 5.0.0.

bool dir_opendir ( string path, int options )

This method is called immediately when your stream object is created for examining directory contents with opendir(). path specifies the URL that was passed to opendir() and that this object is expected to explore. You can use parse_url() to break it apart.

array url_stat ( string path, int flags )

This method is called in response to stat() calls on the URL paths associated with the wrapper and should return as many elements in common with the system function as possible. Unknown or unavailable values should be set to a rational value (usually 0).

flags holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_URL_STAT_LINK | For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET | If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

string dir_readdir ( void )

This method is called in response to readdir() and should return a string representing the next filename in the location opened by dir_opendir().

bool dir_rewinddir ( void )

This method is called in response to rewinddir() and should reset the output generated by dir_readdir(). i.e.: The next call to dir_readdir() should return the first entry in the location returned by dir_opendir().

bool dir_closedir ( void )

This method is called in response to closedir(). You should release any resources which were locked or allocated during the opening and use of the directory stream.

The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].

Example 1. A Stream for reading/writing global variables

&#60;?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &#38;$opened_path)
    {
        $url = parse_url($path);
        $this-&#62;varname = $url["host"];
        $this-&#62;position = 0;

        return true;
    }

    function stream_read($count)
    {
        $ret = substr($GLOBALS[$this-&#62;varname], $this-&#62;position, $count);
        $this-&#62;position += strlen($ret);
        return $ret;
    }

    function stream_write($data)
    {
        $left = substr($GLOBALS[$this-&#62;varname], 0, $this-&#62;position);
        $right = substr($GLOBALS[$this-&#62;varname], $this-&#62;position + strlen($data));
        $GLOBALS[$this-&#62;varname] = $left . $data . $right;
        $this-&#62;position += strlen($data);
        return strlen($data);
    }

    function stream_tell()
    {
        return $this-&#62;position;
    }

    function stream_eof()
    {
        return $this-&#62;position &#62;= strlen($GLOBALS[$this-&#62;varname]);
    }

    function stream_seek($offset, $whence)
    {
        switch ($whence) {
            case SEEK_SET:
                if ($offset &#60; strlen($GLOBALS[$this-&#62;varname]) &#38;&#38; $offset &#62;= 0) {
                     $this-&#62;position = $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_CUR:
                if ($offset &#62;= 0) {
                     $this-&#62;position += $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_END:
                if (strlen($GLOBALS[$this-&#62;varname]) + $offset &#62;= 0) {
                     $this-&#62;position = strlen($GLOBALS[$this-&#62;varname]) + $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            default:
                return false;
        }
    }
}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?&#62;

Prev | Home | Next
stream_socket_shutdown | Up | stream_wrapper_restore


stream_wrapper_restore

(PHP 5 >= 5.1.0RC1)

stream_wrapper_restore -- Restores a previously unregistered built-in wrapper

Description

bool stream_wrapper_restore ( string protocol )

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

Prev | Home | Next
stream_wrapper_register | Up | stream_wrapper_unregister


stream_wrapper_unregister

(PHP 5 >= 5.1.0RC1)

stream_wrapper_unregister -- Unregister a URL wrapper

Description

bool stream_wrapper_unregister ( string protocol )

stream_wrapper_unregister() allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

Prev | Home | Next
stream_wrapper_restore | Up | String Functions


String Functions

PHP Manual
Prev Next

CLIX. String Functions

Introduction

These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.

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.

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.

CRYPT_SALT_LENGTH integer

CRYPT_STD_DES integer

CRYPT_EXT_DES integer

CRYPT_MD5 integer

CRYPT_BLOWFISH integer

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

See Also

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

Table of Contents
addcslashes -- Quote string with slashes in a C style
addslashes -- Quote string with slashes
bin2hex -- Convert binary data into hexadecimal representation
chop -- Alias of rtrim()
chr -- Return a specific character
chunk_split -- Split a string into smaller chunks
convert_cyr_string -- Convert from one Cyrillic character set to another
convert_uudecode -- Decode a uuencoded string
convert_uuencode -- Uuencode a string
count_chars -- Return information about characters used in a string
crc32 -- Calculates the crc32 polynomial of a string
crypt -- One-way string encryption (hashing)
echo -- Output one or more strings
explode -- Split a string by string
fprintf -- Write a formatted string to a stream
get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()
hebrev -- Convert logical Hebrew text to visual text
hebrevc -- Convert logical Hebrew text to visual text with newline conversion
html_entity_decode -- Convert all HTML entities to their applicable characters
htmlentities -- Convert all applicable characters to HTML entities
htmlspecialchars_decode -- Convert special HTML entities back to characters
htmlspecialchars -- Convert special characters to HTML entities
implode -- Join array elements with a string
join -- Alias of implode()
levenshtein -- Calculate Levenshtein distance between two strings
localeconv -- Get numeric formatting information
ltrim -- Strip whitespace (or other characters) from the beginning of a string
md5_file -- Calculates the md5 hash of a given file
md5 -- Calculate the md5 hash of a string
metaphone -- Calculate the metaphone key of a string
money_format -- Formats a number as a currency string
nl_langinfo -- Query language and locale information
nl2br -- Inserts HTML line breaks before all newlines in a string
number_format -- Format a number with grouped thousands
ord -- Return ASCII value of character
parse_str -- Parses the string into variables
print -- Output a string
printf -- Output a formatted string
quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string
quotemeta -- Quote meta characters
rtrim -- Strip whitespace (or other characters) from the end of a string
setlocale -- Set locale information
sha1_file -- Calculate the sha1 hash of a file
sha1 -- Calculate the sha1 hash of a string
similar_text -- Calculate the similarity between two strings
soundex -- Calculate the soundex key of a string
sprintf -- Return a formatted string
sscanf -- Parses input from a string according to a format
str_getcsv -- Parse a CSV string into an array
str_ireplace -- Case-insensitive version of str_replace().
str_pad -- Pad a string to a certain length with another string
str_repeat -- Repeat a string
str_replace -- Replace all occurrences of the search string with the replacement string
str_rot13 -- Perform the rot13 transform on a string
str_shuffle -- Randomly shuffles a string
str_split -- Convert a string to an array
str_word_count -- Return information about words used in a string
strcasecmp -- Binary safe case-insensitive string comparison
strchr -- Alias of strstr()
strcmp -- Binary safe string comparison
strcoll -- Locale based string comparison
strcspn -- Find length of initial segment not matching mask
strip_tags -- Strip HTML and PHP tags from a string
stripcslashes -- Un-quote string quoted with addcslashes()
stripos -- Find position of first occurrence of a case-insensitive string
stripslashes -- Un-quote string quoted with addslashes()
stristr -- Case-insensitive strstr()
strlen -- Get string length
strnatcasecmp -- Case insensitive string comparisons using a "natural order" algorithm
strnatcmp -- String comparisons using a "natural order" algorithm
strncasecmp -- Binary safe case-insensitive string comparison of the first n characters
strncmp -- Binary safe string comparison of the first n characters
strpbrk -- Search a string for any of a set of characters
strpos -- Find position of first occurrence of a string
strrchr -- Find the last occurrence of a character in a string
strrev -- Reverse a string
strripos -- Find position of last occurrence of a case-insensitive string in a string
strrpos -- Find position of last occurrence of a char in a string
strspn -- Find length of initial segment matching mask
strstr -- Find first occurrence of a string
strtok -- Tokenize string
strtolower -- Make a string lowercase
strtoupper -- Make a string uppercase
strtr -- Translate certain characters
substr_compare -- Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters
substr_count -- Count the number of substring occurrences
substr_replace -- Replace text within a portion of a string
substr -- Return part of a string
trim -- Strip whitespace (or other characters) from the beginning and end of a string
ucfirst -- Make a string's first character uppercase
ucwords -- Uppercase the first character of each word in a string
vfprintf -- Write a formatted string to a stream
vprintf -- Output a formatted string
vsprintf -- Return a formatted string
wordwrap -- Wraps a string to a given number of characters using a string break character

Prev | Home | Next
stream_wrapper_unregister | Up | addcslashes


addcslashes

(PHP 4, PHP 5)

addcslashes -- Quote string with slashes in a C style

Description

string addcslashes ( string str, string charlist )

Returns a string with backslashes before characters that are listed in charlist parameter. If charlist contains characters \n, \r etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation.

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

Example 1. addcslashes() example

&#60;?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?&#62;

When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.

&#60;?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_` and any tabs, line
// feeds, carriage returns, etc.
?&#62;

Also, if the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character.

&#60;?php
echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']
?&#62;

See also stripcslashes(),
stripslashes(),
addslashes(),
htmlspecialchars(), and
quotemeta().

Prev | Home | Next
String Functions | Up | addslashes


addslashes

(PHP 3, PHP 4, PHP 5)

addslashes -- Quote string with slashes

Description

string addslashes ( string str )

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\'reilly. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Example 1. An addslashes() example

&#60;?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?&#62;

See also stripslashes(),
stripcslashes(),
addcslashes(),
htmlspecialchars(),
quotemeta(), and
get_magic_quotes_gpc().

Prev | Home | Next
addcslashes | Up | bin2hex


bin2hex

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

bin2hex -- Convert binary data into hexadecimal representation

Description

string bin2hex ( string str )

Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

See also pack() and unpack().

Prev | Home | Next
addslashes | Up | chop


chop

(PHP 3, PHP 4, PHP 5)

chop -- Alias of rtrim()

Description

This function is an alias of: rtrim().

Note: chop() is different than the Perl chop() function, which removes the last character in the string.

Prev | Home | Next
bin2hex | Up | chr


chr

(PHP 3, PHP 4, PHP 5)

chr -- Return a specific character

Description

string chr ( int ascii )

Returns a one-character string containing the character specified by ascii.

Example 1. chr() example

&#60;?php
$str = "The string ends in escape: ";
$str .= chr(27); /* add an escape character at the end of $str */

/* Often this is more useful */

$str = sprintf("The string ends in escape: %c", 27);
?&#62;

You can find an ASCII-table over here: http://www.asciitable.com.

This function complements ord(). See also sprintf() with a format string of %c.

Prev | Home | Next
chop | Up | chunk_split


chunk_split

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

chunk_split -- Split a string into smaller chunks

Description

string chunk_split ( string body [, int chunklen [, string end]] )

Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end (defaults to "\r\n") every chunklen characters (defaults to 76). It returns the new string leaving the original string untouched.

Example 1. chunk_split() example

&#60;?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?&#62;

See also str_split(),
explode(), split(),
wordwrap() and
RFC 2045.

Prev | Home | Next
chr | Up | convert_cyr_string


convert_cyr_string

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

convert_cyr_string -- Convert from one Cyrillic character set to another

Description

string convert_cyr_string ( string str, string from, string to )

This function returns the given string converted from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:

  • k - koi8-r

  • w - windows-1251

  • i - iso8859-5

  • a - x-cp866

  • d - x-cp866

  • m - x-mac-cyrillic

Note: This function is binary-safe.

Prev | Home | Next
chunk_split | Up | convert_uudecode


convert_uudecode

(PHP 5)

convert_uudecode -- Decode a uuencoded string

Description

string convert_uudecode ( string data )

convert_uudecode() decodes a uuencoded string.

Example 1. convert_uudecode() example

&#60;?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?&#62;

See also convert_uuencode().

Prev | Home | Next
convert_cyr_string | Up | convert_uuencode


convert_uuencode

(PHP 5)

convert_uuencode -- Uuencode a string

Description

string convert_uuencode ( string data )

convert_uuencode() encodes a string using the uuencode algorithm.

Uuencode translates all strings (including binary's ones) into printable characters, making them safe for network transmissions. Uuencoded data is about 35% larger than the original.

Example 1. convert_uuencode() example

&#60;?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?&#62;

See also convert_uudecode() and base64_encode().

Prev | Home | Next
convert_uudecode | Up | count_chars


count_chars

(PHP 4, PHP 5)

count_chars -- Return information about characters used in a string

Description

mixed count_chars ( string string [, int mode] )

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. The optional parameter mode defaults to 0. Depending on mode count_chars() returns one of the following:

  • 0 - an array with the byte-value as key and the frequency of every byte as value.

  • 1 - same as 0 but only byte-values with a frequency greater than zero are listed.

  • 2 - same as 0 but only byte-values with a frequency equal to zero are listed.

  • 3 - a string containing all used byte-values is returned.

  • 4 - a string containing all not used byte-values is returned.

Example 1. count_chars() example

&#60;?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i =&#62; $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?&#62;

The above example will output:

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.

See also strpos() and substr_count().

Prev | Home | Next
convert_uuencode | Up | crc32


crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 -- Calculates the crc32 polynomial of a string

Description

int crc32 ( string str )

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

This second example shows how to print a converted checksum with the printf() function:

Example 1. Displaying a crc32 checksum

&#60;?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?&#62;

See also md5() and sha1().

Prev | Home | Next
count_chars | Up | crypt


crypt

(PHP 3, PHP 4, PHP 5)

crypt -- One-way string encryption (hashing)

Description

string crypt ( string str [, string salt] )

crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.

If the salt argument is not provided, one will be randomly generated by PHP each time you call this function.

Some operating systems support more than one type of encryption. In fact, sometimes the standard DES-based encryption is replaced by an MD5-based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard two character salt by default, unless the default encryption type on the system is MD5, in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular two character salt applies to your system or the longer twelve character salt is applicable.

If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function repeatedly, this may impact both appearance and security.

The standard DES-based encryption crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

On systems where the crypt() function supports multiple encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based encryption with a two character salt

  • CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt

  • CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$

  • CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$ or $2a$

Note: There is no decrypt function, since crypt() uses a one-way algorithm.

Example 1. crypt() examples

&#60;?php
$password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?&#62;

Example 2. Using crypt() with htpasswd

&#60;?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?&#62;

Example 3. Using crypt() with different encryption types

&#60;?php
if (CRYPT_STD_DES == 1) {
    echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}

if (CRYPT_EXT_DES == 1) {
    echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}

if (CRYPT_MD5 == 1) {
    echo 'MD5:          ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}

if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish:     ' . crypt('rasmuslerdorf', '$2a$07$rasmuslerd...........$') . "\n";
}
?&#62;

The above example will output something similar to:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$rasmuslerd............nIdrcHdxcUxWomQX9j6kvERCFjTg7Ra

See also md5() and the Mcrypt extension.

Prev | Home | Next
crc32 | Up | echo


echo

(PHP 3, PHP 4, PHP 5)

echo -- Output one or more strings

Description

void echo ( string arg1 [, string ...] )

Outputs all parameters.

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

Example 1. echo() examples

&#60;?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" =&#62; "foo");

echo "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Some people prefer passing multiple parameters to echo over concatenation.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

echo &#60;&#60;&#60;END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;

// Because echo does not behave like a function, the following code is invalid.
($some_var) ? echo 'true' : echo 'false';

// However, the following examples will work:
($some_var) ? print 'true' : print 'false'; // print is also a construct, but
                                            // it behaves like a function, so
                                            // it may be used in this context.
echo $some_var ? 'true': 'false'; // changing the statement around
?&#62;

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.

I have &#60;?=$foo?&#62; foo.

For a short discussion about the differences between print() and echo(), see this FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also
print(),
printf(), and
flush().

Prev | Home | Next
crypt | Up | explode


explode

(PHP 3, PHP 4, PHP 5)

explode -- Split a string by string

Description

array explode ( string delimiter, string string [, int limit] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string, then explode() will return an array containing string.

If the limit parameter is negative, all components except the last -limit are returned. This feature was added in PHP 5.1.0.

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument.

Note: The limit parameter was added in PHP 4.0.1

Example 1. explode() examples

&#60;?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?&#62;

Example 2. limit parameter examples

&#60;?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?&#62;

The above example will output:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Note: This function is binary-safe.

See also
preg_split(),
str_split(),
strtok(), and
implode().

Prev | Home | Next
echo | Up | fprintf


fprintf

(PHP 5)

fprintf -- Write a formatted string to a stream

Description

int fprintf ( resource handle, string format [, mixed args [, mixed ...]] )

Write a string produced according to format to the stream resource specified by handle. format is described in the documentation for sprintf().

Returns the length of the outputted string.

See also: printf(),
sprintf(),
sscanf(), fscanf(),
vsprintf(), and
number_format().

Examples

Example 1. fprintf(): zero-padded integers

&#60;?php
if (!($fp = fopen('date.txt', 'w')))
    return;

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// will write the formatted ISO date to date.txt
?&#62;

Example 2. fprintf(): formatting currency

&#60;?php
if (!($fp = fopen('currency.txt', 'w')))
    return;

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// will write "123.10" to currency.txt

echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote
?&#62;

Prev | Home | Next
explode | Up | get_html_translation_table


get_html_translation_table

(PHP 4, PHP 5)

get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()

Description

array get_html_translation_table ( [int table [, int quote_style]] )

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. Default value for table is HTML_SPECIALCHARS. And as in the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().

Note: Special characters can be encoded in several ways. E.g. " can be encoded as &quot;, &#34; or &#x22. get_html_translation_table() returns only the most common form for them.

Example 1. Translation Table Example

&#60;?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo &#38; &#60;Frau&#62; &#38; Krämer";
$encoded = strtr($str, $trans);
?&#62;
The $encoded variable will now contain: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".

See also htmlspecialchars(),
htmlentities(), and
html_entity_decode().

Prev | Home | Next
fprintf | Up | hebrev


hebrev

(PHP 3, PHP 4, PHP 5)

hebrev -- Convert logical Hebrew text to visual text

Description

string hebrev ( string hebrew_text [, int max_chars_per_line] )

The optional parameter max_chars_per_line indicates maximum number of characters per line that will be returned. The function tries to avoid breaking words.

See also hebrevc()

Prev | Home | Next
get_html_translation_table | Up | hebrevc


hebrevc

(PHP 3, PHP 4, PHP 5)

hebrevc -- Convert logical Hebrew text to visual text with newline conversion

Description

string hebrevc ( string hebrew_text [, int max_chars_per_line] )

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n". The optional parameter max_chars_per_line indicates maximum number of characters per line that will be returned. The function tries to avoid breaking words.

See also hebrev()

Prev | Home | Next
hebrev | Up | html_entity_decode


html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode -- Convert all HTML entities to their applicable characters

Description

string html_entity_decode ( string string [, int quote_style [, string charset]] )

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities to their applicable characters from string.

The optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Table 1. Available quote_style constants

Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.

The ISO-8859-1 character set is used as default for the optional third charset. This defines the character set used in conversion.

Following character sets are supported in PHP 4.3.0 and later.

Table 2. Supported charsets

Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1(ISO-8859-1).
UTF-8 |  | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS |  | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese

Note: Any other character sets are not recognized and ISO-8859-1 will be used instead.

Note: This function doesn't support multi-byte character sets in PHP < 5.

Example 1. Decoding HTML entities

&#60;?php
$orig = "I'll \"walk\" the &#60;b&#62;dog&#60;/b&#62; now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &#38;quot;walk&#38;quot; the &#38;lt;b&#38;gt;dog&#38;lt;/b&#38;gt; now

echo $b; // I'll "walk" the &#60;b&#62;dog&#60;/b&#62; now

// For users prior to PHP 4.3.0 you may do this:
function unhtmlentities($string)
{
    // replace numeric entities
    $string = preg_replace('~&#38;#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
    $string = preg_replace('~&#38;#([0-9]+);~e', 'chr("\\1")', $string);
    // replace literal entities
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}

$c = unhtmlentities($a);

echo $c; // I'll "walk" the &#60;b&#62;dog&#60;/b&#62; now

?&#62;

Note: You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

See also htmlentities(),
htmlspecialchars(),
get_html_translation_table(),
and urldecode().

Prev | Home | Next
hebrevc | Up | htmlentities


htmlentities

(PHP 3, PHP 4, PHP 5)

htmlentities -- Convert all applicable characters to HTML entities

Description

string htmlentities ( string string [, int quote_style [, string charset]] )

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

Like htmlspecialchars(), the optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Table 1. Available quote_style constants

Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.

Support for the optional quote parameter was added in PHP 4.0.3.

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Support for this argument was added in PHP 4.1.0. Presently, the ISO-8859-1 character set is used as the default.

Following character sets are supported in PHP 4.3.0 and later.

Table 2. Supported charsets

Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1(ISO-8859-1).
UTF-8 |  | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS |  | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese

Note: Any other character sets are not recognized and ISO-8859-1 will be used instead.

If you're wanting to decode instead (the reverse) you can use html_entity_decode().

Example 1. A htmlentities() example

&#60;?php
$str = "A 'quote' is &#60;b&#62;bold&#60;/b&#62;";

// Outputs: A 'quote' is &#38;lt;b&#38;gt;bold&#38;lt;/b&#38;gt;
echo htmlentities($str);

// Outputs: A &#38;#039;quote&#38;#039; is &#38;lt;b&#38;gt;bold&#38;lt;/b&#38;gt;
echo htmlentities($str, ENT_QUOTES);
?&#62;

See also html_entity_decode(),
get_html_translation_table(),
htmlspecialchars(), nl2br(),
and urlencode().

Prev | Home | Next
html_entity_decode | Up | htmlspecialchars_decode


htmlspecialchars_decode

(PHP 5 >= 5.1.0RC1)

htmlspecialchars_decode -- Convert special HTML entities back to characters

Description

string htmlspecialchars_decode ( string string [, int quote_style] )

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.

Parameters

string

The string to decode

quote_style

The quote style. One of the following constants:

Table 1. quote_style constants

Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone (default)
ENT_QUOTES | Will convert both double and single quotes
ENT_NOQUOTES | Will leave both double and single quotes unconverted

Return Values

Returns the decoded string.

Examples

Example 1. A htmlspecialchars_decode() example

&#60;?php
$str = '&#60;p&#62;this -&#38;gt; &#38;quot;&#60;/p&#62;';

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?&#62;

The above example will output:

<p>this -> "</p>
<p>this -> &quot;</p>

See Also

htmlspecialchars()
html_entity_decode()
get_html_translation_table()

Prev | Home | Next
htmlentities | Up | htmlspecialchars


htmlspecialchars

(PHP 3, PHP 4, PHP 5)

htmlspecialchars -- Convert special characters to HTML entities

Description

string htmlspecialchars ( string string [, int quote_style [, string charset]] )

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'

  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

  • '<' (less than) becomes '&lt;'

  • '>' (greater than) becomes '&gt;'

Example 1. htmlspecialchars() example

&#60;?php
$new = htmlspecialchars("&#60;a href='test'&#62;Test&#60;/a&#62;", ENT_QUOTES);
echo $new; // &#38;lt;a href=&#38;#039;test&#38;#039;&#38;gt;Test&#38;lt;/a&#38;gt;
?&#62;

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

The third argument charset defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added in PHP 4.1.0.

Following character sets are supported in PHP 4.3.0 and later.

Table 1. Supported charsets

Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1(ISO-8859-1).
UTF-8 |  | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS |  | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese

Note: Any other character sets are not recognized and ISO-8859-1 will be used instead.

See also get_html_translation_table(),
htmlspecialchars_decode(),
strip_tags(),
htmlentities(), and nl2br().

Prev | Home | Next
htmlspecialchars_decode | Up | implode


implode

(PHP 3, PHP 4, PHP 5)

implode -- Join array elements with a string

Description

string implode ( string glue, array pieces )

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Example 1. implode() example

&#60;?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?&#62;

Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Note: As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string(''). This is not the preferred usage of implode(). We recommend to always use two parameters for compatibility with older versions.

Note: This function is binary-safe.

See also explode(), and split().

Prev | Home | Next
htmlspecialchars | Up | join


join

(PHP 3, PHP 4, PHP 5)

join -- Alias of implode()

Description

This function is an alias of: implode().

Prev | Home | Next
implode | Up | levenshtein


levenshtein

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.1, PHP 5)

levenshtein -- Calculate Levenshtein distance between two strings

Description

int levenshtein ( string str1, string str2 [, int cost_ins, int cost_rep, int cost_del] )

This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.

A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.

Example 1. levenshtein() example

&#60;?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev &#60;= $shortest || $shortest &#60; 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?&#62;

The above example will output:

Input word: carrrot
Did you mean: carrot?

See also soundex(),
similar_text(), and
metaphone().

Prev | Home | Next
join | Up | localeconv


localeconv

(PHP 4 >= 4.0.5, PHP 5)

localeconv -- Get numeric formatting information

Description

array localeconv ( void )

Returns an associative array containing localized numeric and monetary formatting information.

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array element | Description
decimal_point | Decimal point character
thousands_sep | Thousands separator
grouping | Array containing numeric groupings
int_curr_symbol | International currency symbol (i.e. USD)
currency_symbol | Local currency symbol (i.e. $)
mon_decimal_point | Monetary decimal point character
mon_thousands_sep | Monetary thousands separator
mon_grouping | Array containing monetary groupings
positive_sign | Sign for positive values
negative_sign | Sign for negative values
int_frac_digits | International fractional digits
frac_digits | Local fractional digits
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn

0 - Parentheses surround the quantity and currency_symbol
1 - The sign string precedes the quantity and currency_symbol
2 - The sign string succeeds the quantity and currency_symbol
3 - The sign string immediately precedes the currency_symbol
4 - The sign string immediately succeeds the currency_symbol

n_sign_posn

0 - Parentheses surround the quantity and currency_symbol
1 - The sign string precedes the quantity and currency_symbol
2 - The sign string succeeds the quantity and currency_symbol
3 - The sign string immediately precedes the currency_symbol
4 - The sign string immediately succeeds the currency_symbol

The n_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.

The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

Example 1. localeconv() example

&#60;?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?&#62;

The above example will output:

Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => €
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 1
    [p_sep_by_space] => 1
    [n_cs_precedes] => 1
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 2
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

See also setlocale().

Prev | Home | Next
levenshtein | Up | ltrim


ltrim

(PHP 3, PHP 4, PHP 5)

ltrim -- Strip whitespace (or other characters) from the beginning of a string

Description

string ltrim ( string str [, string charlist] )

Note: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Example 1. Usage example of ltrim()

&#60;?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?&#62;

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

See also trim() and rtrim().

Prev | Home | Next
localeconv | Up | md5_file


md5_file

(PHP 4 >= 4.2.0, PHP 5)

md5_file -- Calculates the md5 hash of a given file

Description

string md5_file ( string filename [, bool raw_output] )

Calculates the MD5 hash of the file specified by the filename parameter using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.

Parameters

filename

The filename

raw_output

When TRUE, returns the digest in raw binary format with a length of 16. Defaults to FALSE.

Return Values

Returns a string on success, FALSE otherwise.

ChangeLog

Version | Description
5.0.0 | Added the raw_output parameter
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')

See Also

md5()
sha1_file()
crc32()

Prev | Home | Next
ltrim | Up | md5


md5

(PHP 3, PHP 4, PHP 5)

md5 -- Calculate the md5 hash of a string

Description

string md5 ( string str [, bool raw_output] )

Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Note: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Example 1. A md5() example

&#60;?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
    exit;
}
?&#62;

See also crc32(), md5_file(), and sha1().

Prev | Home | Next
md5_file | Up | metaphone


metaphone

(PHP 4, PHP 5)

metaphone -- Calculate the metaphone key of a string

Description

string metaphone ( string str [, int phones] )

Calculates the metaphone key of str.

Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

Metaphone was developed by Lawrence Philips <lphilips at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

Prev | Home | Next
md5 | Up | money_format


money_format

(PHP 4 >= 4.3.0, PHP 5)

money_format -- Formats a number as a currency string

Description

string money_format ( string format, float number )

money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.

Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

The format specification consists of the following sequence:

  • a % character

  • optional flags

  • optional field width

  • optional left precision

  • optional right precision

  • a required conversion character

Flags. One or more of the optional flags below can be used:

=f

The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space.

^

Disable the use of grouping characters (as defined by the current locale).

+ or (

Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.

!

Suppress the currency symbol from the output string.

-

If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).

Field width.

w

A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).

Left precision.

#n

The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.

If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.

To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.

Right precision .

.p

A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.

Conversion characters .

i

The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).

n

The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: DM1.234,56).

%

Returns the % character.

Note: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.

Characters before and after the formatting string will be returned unchanged.

Example 1. money_format() Example

We will use different locales and format specifications to illustrate the use of this function.

&#60;?php

$number = 1234.56;

// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// L. 1.234,56

// Using a negative number
$number = -1234.5672;

// US national format, using () for negative numbers
// and 10 digits for left precision
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// Similar format as above, adding the use of 2 digits of right
// precision and '*' as a fill character
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)

// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, withouth grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// DEM 1234,56****

// Let's add some blurb before and after the conversion specification
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is  GBP 1,234.56 (after a 10% discount)

?&#62;

See also: setlocale(),
number_format(), sprintf(),
printf() and sscanf().

Prev | Home | Next
metaphone | Up | nl_langinfo


nl_langinfo

(PHP 4 >= 4.1.0, PHP 5)

nl_langinfo -- Query language and locale information

Description

string nl_langinfo ( int item )

nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element.

If item is not valid, FALSE will be returned.

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

Table 1. nl_langinfo Constants

Constant | Description
LC_TIME Category Constants
ABDAY_(1-7) | Abbreviated name of n-th day of the week.
DAY_(1-7) | Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12) | Abbreviated name of the n-th month of the year.
MON_(1-12) | Name of the n-th month of the year.
AM_STR | String for Ante meridian.
PM_STR | String for Post meridian.
D_T_FMT | String that can be used as the format string for strftime() to represent time and date.
D_FMT | String that can be used as the format string for strftime() to represent date.
T_FMT | String that can be used as the format string for strftime() to represent time.
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERA | Alternate era.
ERA_YEAR | Year in alternate era format.
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()).
ERA_D_FMT | Date in alternate era format (string can be used in strftime()).
ERA_T_FMT | Time in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOL | International currency symbol.
CURRENCY_SYMBOL | Local currency symbol.
CRNCYSTR | Same value as CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Decimal point character.
MON_THOUSANDS_SEP | Thousands separator (groups of three digits).
MON_GROUPING | Like 'grouping' element.
POSITIVE_SIGN | Sign for positive values.
NEGATIVE_SIGN | Sign for negative values.
INT_FRAC_DIGITS | International fractional digits.
FRAC_DIGITS | Local fractional digits.
P_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN

  • Returns 0 if parentheses surround the quantity and currency_symbol.

  • Returns 1 if the sign string precedes the quantity and currency_symbol.

  • Returns 2 if the sign string follows the quantity and currency_symbol.

  • Returns 3 if the sign string immediately precedes the currency_symbol.

  • Returns 4 if the sign string immediately follows the currency_symbol.

N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINT | Decimal point character.
RADIXCHAR | Same value as DECIMAL_POINT.
THOUSANDS_SEP | Separator character for thousands (groups of three digits).
THOUSEP | Same value as THOUSANDS_SEP.
GROUPING
LC_MESSAGES Category Constants
YESEXPR | Regex string for matching 'yes' input.
NOEXPR | Regex string for matching 'no' input.
YESSTR | Output string for 'yes'.
NOSTR | Output string for 'no'.
LC_CTYPE Category Constants
CODESET | Return a string with the name of the character encoding.

Note: This function is not implemented on Windows platforms.

See also setlocale() and localeconv().

Prev | Home | Next
money_format | Up | nl2br


nl2br

(PHP 3, PHP 4, PHP 5)

nl2br -- Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string )

Returns string with '<br />' inserted before all newlines.

Note: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.

Example 1. using nl2br()

&#60;?php
echo nl2br("foo isn't\n bar");
?&#62;

this will output :

foo isn't<br />
 bar

See also htmlspecialchars(),
htmlentities(),
wordwrap(), and
str_replace().

Prev | Home | Next
nl_langinfo | Up | number_format


number_format

(PHP 3, PHP 4, PHP 5)

number_format -- Format a number with grouped thousands

Description

string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Only the first character of thousands_sep is used. For example, if you use bar as thousands_sep on the number 1000, number_format() will return 1b000.

Example 1. number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :

&#60;?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?&#62;

See also: money_format(), sprintf(), printf() and sscanf().

Prev | Home | Next
nl2br | Up | ord


ord

(PHP 3, PHP 4, PHP 5)

ord -- Return ASCII value of character

Description

int ord ( string string )

Returns the ASCII value of the first character of string. This function complements chr().

Example 1. ord() example

&#60;?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?&#62;

You can find an ASCII-table over here: http://www.asciitable.com.

See also chr().

Prev | Home | Next
number_format | Up | parse_str


parse_str

(PHP 3, PHP 4, PHP 5)

parse_str -- Parses the string into variables

Description

void parse_str ( string str [, array &arr] )

Parses str as if it were the query string passed via a URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as array elements instead.

Note: Support for the optional second parameter was added in PHP 4.0.3.

Note: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from outside of PHP.

Note: The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

Example 1. Using parse_str()

&#60;?php
$str = "first=value&#38;arr[]=foo+bar&#38;arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?&#62;

See also parse_url(), pathinfo(),
http_build_query(),
get_magic_quotes_gpc(), and urldecode().

Prev | Home | Next
ord | Up | print


print

(PHP 3, PHP 4, PHP 5)

print -- Output a string

Description

int print ( string arg )

Outputs arg. Returns 1, always.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

Example 1. print() examples

&#60;?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// You can use variables inside of a print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" =&#62; "foo");

print "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
print 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just print variables
print $foo;          // foobar

print &#60;&#60;&#60;END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?&#62;

For a short discussion about the differences between print() and echo(), see this FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also echo(), printf(), and flush().

Prev | Home | Next
parse_str | Up | printf


printf

(PHP 3, PHP 4, PHP 5)

printf -- Output a formatted string

Description

int printf ( string format [, mixed args [, mixed ...]] )

Produces output according to format, which is described in the documentation for sprintf().

Returns the length of the outputted string.

See also
print(),
sprintf(),
vprintf(),
sscanf(),
fscanf(), and
flush().

Prev | Home | Next
print | Up | quoted_printable_decode


quoted_printable_decode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string

Description

string quoted_printable_decode ( string str )

This function returns an 8-bit binary string corresponding to the decoded quoted printable string (according to RFC2045, section 6.7, not RFC2821, section 4.5.2, so additional periods are not stripped from the beginning of line). This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

Prev | Home | Next
printf | Up | quotemeta


quotemeta

(PHP 3, PHP 4, PHP 5)

quotemeta -- Quote meta characters

Description

string quotemeta ( string str )

Returns a version of str with a backslash character (\) before every character that is among these:

. \ + * ? [ ^ ] ( $ )

Note: This function is binary-safe.

See also addslashes(),
addcslashes(),
htmlentities(),
htmlspecialchars(),
nl2br(),
stripslashes(), and
stripcslashes().

Prev | Home | Next
quoted_printable_decode | Up | rtrim


rtrim

(PHP 3, PHP 4, PHP 5)

rtrim -- Strip whitespace (or other characters) from the end of a string

Description

string rtrim ( string str [, string charlist] )

Note: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Example 1. Usage example of rtrim()

&#60;?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?&#62;

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

See also trim() and ltrim().

Prev | Home | Next
quotemeta | Up | setlocale


setlocale

(PHP 3, PHP 4, PHP 5)

setlocale -- Set locale information

Description

string setlocale ( int category, string locale [, string ...] )

string setlocale ( int category, array locale )

category is a named constant (or string) specifying the category of the functions affected by the locale setting:

  • LC_ALL for all of the below

  • LC_COLLATE for string comparison, see strcoll()

  • LC_CTYPE for character classification and conversion, for example strtoupper()

  • LC_MONETARY for localeconv()

  • LC_NUMERIC for decimal separator (See also localeconv())

  • LC_TIME for date and time formatting with strftime()

  • LC_MESSAGES for system responses (available if PHP was compiled with libintl)

Note: As of PHP 4.2.0, passing category as a string is deprecated, use the above constants instead. Passing them as a string (within quotes) will result in a warning message.

If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".

If locale is "0", the locale setting is not affected, only the current setting is returned.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

Note: Passing multiple locales is not available before PHP 4.3.0

Setlocale returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message. Category/locale names can be found in RFC 1766 and ISO 639. Different systems have different naming schemes for locales.

Note: The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Warning

The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server api like IIS or Apache on Windows you may experience sudden changes of locale settings while a script is running although the script itself never called setlocale() itself. This happens due to other scripts running in different threads of the same process at the same time changing the processwide locale using setlocale().

Tip: Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp and supported country/region strings at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. Windows systems support the three letter codes for country/region specified by ISO 3166-Alpha-3, which can be found at this Unicode website.

Example 1. setlocale() Examples

&#60;?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?&#62;

Example 2. setlocale() Examples for Windows

&#60;?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?&#62;

Prev | Home | Next
rtrim | Up | sha1_file


sha1_file

(PHP 4 >= 4.3.0, PHP 5)

sha1_file -- Calculate the sha1 hash of a file

Description

string sha1_file ( string filename [, bool raw_output] )

Calculates the sha1 hash of filename using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number.

Parameters

filename

The filename

raw_output

When TRUE, returns the digest in raw binary format with a length of 20. Defaults to FALSE.

Return Values

Returns a string on success, FALSE otherwise.

ChangeLog

Version | Description
5.0.0 | Added the raw_output parameter
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')

See Also

sha1()
md5_file()
crc32()

Prev | Home | Next
setlocale | Up | sha1


sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 -- Calculate the sha1 hash of a string

Description

string sha1 ( string str [, bool raw_output] )

Calculates the sha1 hash of str using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20.

Note: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Example 1. A sha1() example

&#60;?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
    exit;
}
?&#62;

See also sha1_file(),
crc32(), and
md5()

Prev | Home | Next
sha1_file | Up | similar_text


similar_text

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

similar_text -- Calculate the similarity between two strings

Description

int similar_text ( string first, string second [, float &percent] )

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.

See also levenshtein(), and soundex().

Prev | Home | Next
sha1 | Up | soundex


soundex

(PHP 3, PHP 4, PHP 5)

soundex -- Calculate the soundex key of a string

Description

string soundex ( string str )

Calculates the soundex key of str.

Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.

This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Example 1. Soundex Examples

&#60;?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?&#62;

See also
levenshtein(),
metaphone(), and
similar_text().

Prev | Home | Next
similar_text | Up | sprintf


sprintf

(PHP 3, PHP 4, PHP 5)

sprintf -- Return a formatted string

Description

string sprintf ( string format [, mixed args [, mixed ...]] )

Returns a string produced according to the formatting string format.

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.

  2. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

  3. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

  4. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  5. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string.

  6. A type specifier that says what type the argument data should be treated as. Possible types:

    % - a literal percent character. No argument is required.
    b - the argument is treated as an integer, and presented as a binary number.
    c - the argument is treated as an integer, and presented as the character with that ASCII value.
    d - the argument is treated as an integer, and presented as a (signed) decimal number.
    e - the argument is treated as scientific notation (e.g. 1.2e+2).
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number (locale aware).
    F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

As of PHP 4.0.6 the format string supports argument numbering/swapping. Here is an example:

Example 1. Argument swapping

&#60;?php
$format = 'There are %d monkeys in the %s';
printf($format, $num, $location);
?&#62;
This might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

Example 2. Argument swapping

&#60;?php
$format = 'The %s contains %d monkeys';
printf($format, $num, $location);
?&#62;
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Example 3. Argument swapping

&#60;?php
$format = 'The %2$s contains %1$d monkeys';
printf($format, $num, $location);
?&#62;
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Example 4. Argument swapping

&#60;?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?&#62;

See also printf(),
sscanf(), fscanf(),
vsprintf(), and
number_format().

Examples

Example 5. printf(): various examples

&#60;?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// notice the double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n); // binary representation
printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
printf("%%d = '%d'\n", $n); // standard integer representation
printf("%%e = '%e'\n", $n); // scientific notation
printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
printf("%%f = '%f'\n", $n); // floating point representation
printf("%%o = '%o'\n", $n); // octal representation
printf("%%s = '%s'\n", $n); // string representation
printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)

printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer
?&#62;

The printout of this program would be:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Example 6. printf(): string specifiers

&#60;?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // standard string output
printf("[%10s]\n",    $s); // right-justification with spaces
printf("[%-10s]\n",   $s); // left-justification with spaces
printf("[%010s]\n",   $s); // zero-padding works on strings too
printf("[%'#10s]\n",  $s); // use the custom padding character '#'
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
?&#62;

The printout of this program would be:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Example 7. sprintf(): zero-padded integers

&#60;?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?&#62;

Example 8. sprintf(): formatting currency

&#60;?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?&#62;

Example 9. sprintf(): scientific notation

&#60;?php
$number = 362525200;

echo sprintf("%.3e", $number); // outputs 3.63e+8
?&#62;

Prev | Home | Next
soundex | Up | sscanf


sscanf

(PHP 4 >= 4.0.1, PHP 5)

sscanf -- Parses input from a string according to a format

Description

mixed sscanf ( string str, string format [, mixed &...] )

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it 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 string. This means that even a tab \t in the format string can match a single space character in the input string.

Example 1. sscanf() Example

&#60;?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?&#62;
If optional parameters are passed, the function will return the number of assigned values.

Example 2. sscanf() - using optional parameters

&#60;?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "&#60;author id='$id'&#62;
    &#60;firstname&#62;$first&#60;/firstname&#62;
    &#60;surname&#62;$last&#60;/surname&#62;
&#60;/author&#62;\n";
?&#62;

See also fscanf(), printf(), and sprintf().

Prev | Home | Next
sprintf | Up | str_getcsv


str_ireplace

(PHP 5)

str_ireplace -- Case-insensitive version of str_replace().

Description

mixed str_ireplace ( mixed search, mixed replace, mixed subject [, int &count] )

This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of eregi_replace() or preg_replace() with the i modifier.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.

Example 1. str_ireplace() example

&#60;?php
$bodytag = str_ireplace("%body%", "black", "&#60;body text=%BODY%&#62;");
?&#62;

This function is binary safe.

Note: As of PHP 5.0.0 the number of matched and replaced needles will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also:
str_replace(),
preg_replace(), and
strtr().

Prev | Home | Next
str_getcsv | Up | str_pad


str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad -- Pad a string to a certain length with another string

Description

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]] )

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

Example 1. str_pad() example

&#60;?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?&#62;

Note: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

Prev | Home | Next
str_ireplace | Up | str_repeat


str_repeat

(PHP 4, PHP 5)

str_repeat -- Repeat a string

Description

string str_repeat ( string input, int multiplier )

Returns input repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Example 1. str_repeat() example

&#60;?php
echo str_repeat("-=", 10);
?&#62;

The above example will output:

-=-=-=-=-=-=-=-=-=-=

See also for, str_pad(), and substr_count().

Prev | Home | Next
str_pad | Up | str_replace


str_replace

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

str_replace -- Replace all occurrences of the search string with the replacement string

Description

mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count] )

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

As of PHP 4.0.5, every parameter in str_replace() can be an array.

Warning

In PHP versions prior to 4.3.3 a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimick the original behavior.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

Example 1. str_replace() examples

&#60;?php
// Provides: &#60;body text='black'&#62;
$bodytag = str_replace("%body%", "black", "&#60;body text='%body%'&#62;");

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2

// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '&#60;br /&#62;';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

?&#62;

Note: This function is binary-safe.

Note: As of PHP 5.0.0 the number of matched and replaced needles (search) will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also
str_ireplace(),
substr_replace(),
preg_replace(), and
strtr().

Prev | Home | Next
str_repeat | Up | str_rot13


str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 -- Perform the rot13 transform on a string

Description

string str_rot13 ( string str )

This function performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.

Example 1. str_rot13() example

&#60;?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?&#62;

Note: The behaviour of this function was buggy until PHP 4.3.0. Before this, the str was also modified, as if passed by reference.

Prev | Home | Next
str_replace | Up | str_shuffle


str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle -- Randomly shuffles a string

Description

string str_shuffle ( string str )

str_shuffle() shuffles a string. One permutation of all possible is created.

Example 1. str_shuffle() example

&#60;?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?&#62;

See also shuffle() and rand().

Prev | Home | Next
str_rot13 | Up | str_split


str_split

(PHP 5)

str_split -- Convert a string to an array

Description

array str_split ( string string [, int split_length] )

Converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.

FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.

Example 1. Example uses of str_split()

&#60;?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?&#62;

Output may look like:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

See also chunk_split(),
preg_split(),
explode(),
count_chars(),
str_word_count(), and
for.

Prev | Home | Next
str_shuffle | Up | str_word_count


str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count -- Return information about words used in a string

Description

mixed str_word_count ( string string [, int format [, string charlist]] )

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

Parameters

string

The string

format

Specify the return value of this function. The current supported values are:

  • 0 - returns the number of words found

  • 1 - returns an array containing all the words found inside the string

  • 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

charlist

A list of additional characters which will be considered as 'word'

Return Values

Returns an array or an integer, depending on the format chosen.

ChangeLog

Version | Description
5.1.0 | Added the charlist parameter

Examples

Example 1. A str_word_count() example

&#60;?php

$str = "Hello fri3nd, you're
       looking          good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?&#62;

The above example will output:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

See Also

explode()
preg_split()
split()
count_chars()
substr_count()

Prev | Home | Next
str_split | Up | strcasecmp


strcasecmp

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

strcasecmp -- Binary safe case-insensitive string comparison

Description

int strcasecmp ( string str1, string str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Example 1. strcasecmp() example

&#60;?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?&#62;

See also
preg_match(),
strcmp(),
substr(),
stristr(),
strncasecmp(), and
strstr().

Prev | Home | Next
str_word_count | Up | strchr


strchr

(PHP 3, PHP 4, PHP 5)

strchr -- Alias of strstr()

Description

This function is an alias of: strstr().

Prev | Home | Next
strcasecmp | Up | strcmp


strcmp

(PHP 3, PHP 4, PHP 5)

strcmp -- Binary safe string comparison

Description

int strcmp ( string str1, string str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also preg_match(),
strcasecmp(),
substr(),
stristr(),
strncasecmp(),
strncmp(), and
strstr().

Prev | Home | Next
strchr | Up | strcoll


strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll -- Locale based string comparison

Description

int strcoll ( string str1, string str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

Note: strcoll() was added in PHP 4.0.5, but was not enabled for win32 until 4.2.3.

See also preg_match(), strcmp(),
strcasecmp(), substr(),
stristr(), strncasecmp(),
strncmp(), strstr(), and
setlocale().

Prev | Home | Next
strcmp | Up | strcspn


strcspn

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

strcspn -- Find length of initial segment not matching mask

Description

int strcspn ( string str1, string str2 [, int start [, int length]] )

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

As of PHP 4.3.0, strcspn() accepts two optional integer parameters that can be used to define the start position and the length of the string to examine.

Note: This function is binary-safe.

See also strspn().

Prev | Home | Next
strcoll | Up | strip_tags


strip_tags

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

strip_tags -- Strip HTML and PHP tags from a string

Description

string strip_tags ( string str [, string allowable_tags] )

This function tries to return a string with all HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

You can use the optional second parameter to specify tags which should not be stripped.

Note: allowable_tags was added in PHP 3.0.13 and PHP 4.0.0.

Since PHP 4.3.0, HTML comments are also stripped. This is hardcoded and can not be changed with allowable_tags.

Warning

Because strip_tags() does not actually validate the HTML, partial, or broken tags can result in the removal of more text/data than expected.

Warning

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

Example 1. strip_tags() example

&#60;?php
$text = '&#60;p&#62;Test paragraph.&#60;/p&#62;&#60;!-- Comment --&#62; Other text';
echo strip_tags($text);
echo "\n";

// Allow &#60;p&#62;
echo strip_tags($text, '&#60;p&#62;');
?&#62;

The above example will output:

Test paragraph. Other text
<p>Test paragraph.</p> Other text

strip_tags() has been binary safe since PHP 5.0.0

See also htmlspecialchars().

Prev | Home | Next
strcspn | Up | stripcslashes


stripcslashes

(PHP 4, PHP 5)

stripcslashes -- Un-quote string quoted with addcslashes()

Description

string stripcslashes ( string str )

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

See also addcslashes().

Prev | Home | Next
strip_tags | Up | stripos


stripos

(PHP 5)

stripos -- Find position of first occurrence of a case-insensitive string

Description

int stripos ( string haystack, string needle [, int offset] )

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.

Note that the needle may be a string of one or more characters.

If needle is not found, stripos() will return boolean 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.

Example 1. stripos() examples

&#60;?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Nope, 'a' is certainly not in 'xyz'
if ($pos1 === false) {
    echo "The string '$findme' was not found in the string '$mystring1'";
}

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' is the 0th (first) character.
if ($pos2 !== false) {
    echo "We found '$findme' in '$mystring2' at position $pos2";
}
?&#62;

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack.

Note: This function is binary-safe.

See also strpos(), strrpos(),
strrchr(), substr(),
stristr(), strstr(),
strripos() and str_ireplace().

Prev | Home | Next
stripcslashes | Up | stripslashes


stripslashes

(PHP 3, PHP 4, PHP 5)

stripslashes -- Un-quote string quoted with addslashes()

Description

string stripslashes ( string str )

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Example 1. A stripslashes() example

&#60;?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?&#62;

Note: stripslashes() is not recursive. If you want to apply this function to a mutli-dimensional array, you need to use a recursive function.

Example 2. Using stripslashes() on an array

&#60;?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);

// Output
print_r($array);
?&#62;

The above example will output:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

For more information about "magic quotes", see get_magic_quotes_gpc().

See also addslashes() and get_magic_quotes_gpc().

Prev | Home | Next
stripos | Up | stristr


stristr

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

stristr -- Case-insensitive strstr()

Description

string stristr ( string haystack, string needle )

Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Example 1. stristr() example

&#60;?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e');
// outputs ER@EXAMPLE.com
?&#62;

Example 2. Testing if a string is found or not

&#60;?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?&#62;

Example 3. Using a non "string" needle

&#60;?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?&#62;

Note: This function is binary-safe.

See also
strstr(),
strrchr(),
substr(), and
preg_match().

Prev | Home | Next
stripslashes | Up | strlen


strlen

(PHP 3, PHP 4, PHP 5)

strlen -- Get string length

Description

int strlen ( string string )

Returns the length of the given string.

Parameters

string

The string being measured for length.

Return Values

The length of the string on success, and 0 if the string is empty.

Examples

Example 1. A strlen() example

&#60;?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?&#62;

See Also

count()
mb_strlen()

Prev | Home | Next
stristr | Up | strnatcasecmp


strnatcasecmp

(PHP 4, PHP 5)

strnatcasecmp -- Case insensitive string comparisons using a "natural order" algorithm

Description

int strnatcasecmp ( string str1, string str2 )

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more information see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also preg_match(),
strcasecmp(),
substr(),
stristr(),
strcmp(),
strncmp(),
strncasecmp(),
strnatcmp(), and
strstr().

Prev | Home | Next
strlen | Up | strnatcmp


strnatcmp

(PHP 4, PHP 5)

strnatcmp -- String comparisons using a "natural order" algorithm

Description

int strnatcmp ( string str1, string str2 )

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

&#60;?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?&#62;

The code above will generate the following output:

Standard string comparison
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order string comparison
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)

For more information see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also preg_match(),
strcasecmp(), substr(),
stristr(), strcmp(),
strncmp(), strncasecmp(),
strnatcasecmp(), strstr(),
natsort() and natcasesort().

Prev | Home | Next
strnatcasecmp | Up | strncasecmp


strncasecmp

(PHP 4 >= 4.0.2, PHP 5)

strncasecmp -- Binary safe case-insensitive string comparison of the first n characters

Description

int strncasecmp ( string str1, string str2, int len )

This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also preg_match(),
strcasecmp(),
strcmp(),
substr(),
stristr(), and
strstr().

Prev | Home | Next
strnatcmp | Up | strncmp


strncmp

(PHP 4, PHP 5)

strncmp -- Binary safe string comparison of the first n characters

Description

int strncmp ( string str1, string str2, int len )

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also preg_match(),
strncasecmp(),
strcasecmp(), substr(),
stristr(), strcmp(), and
strstr().

Prev | Home | Next
strncasecmp | Up | strpbrk


strpbrk

(PHP 5)

strpbrk -- Search a string for any of a set of characters

Description

string strpbrk ( string haystack, string char_list )

strpbrk() searches the haystack string for a char_list, and returns a string starting from the character found (or FALSE if it is not found).

Note: The char_list parameter is case sensitive.

Example 1. strpbrk() example

&#60;?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?&#62;

Prev | Home | Next
strncmp | Up | strpos


strpos

(PHP 3, PHP 4, PHP 5)

strpos -- Find position of first occurrence of a string

Description

int strpos ( string haystack, mixed needle [, int offset] )

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used.

If needle is not found, strpos() will return boolean 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: This function is binary-safe.

Example 1. strpos() examples

&#60;?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?&#62;

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack.

See also strrpos(),
stripos(),
strripos(),
strrchr(),
substr(),
stristr(), and
strstr().

Prev | Home | Next
strpbrk | Up | strrchr


strrchr

(PHP 3, PHP 4, PHP 5)

strrchr -- Find the last occurrence of a character in a string

Description

string strrchr ( string haystack, string needle )

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Returns FALSE if needle is not found.

If needle contains more than one character, only the first is used. This behavior is different from that of strchr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Example 1. strrchr() example

&#60;?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?&#62;

strrchr() has been binary safe since PHP 4.3.0

See also strstr(), substr(), and stristr().

Prev | Home | Next
strpos | Up | strrev


strrev

(PHP 3, PHP 4, PHP 5)

strrev -- Reverse a string

Description

string strrev ( string string )

Returns string, reversed.

Example 1. Reversing a string with strrev()

&#60;?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?&#62;

Prev | Home | Next
strrchr | Up | strripos


strripos

(PHP 5)

strripos -- Find position of last occurrence of a case-insensitive string in a string

Description

int strripos ( string haystack, string needle [, int offset] )

Returns the numeric position of the last occurrence of needle in the haystack string. Unlike strrpos(), strripos() is case-insensitive. Also note that string positions start at 0, and not 1.

Note that the needle may be a string of one or more characters.

If needle is not found, FALSE is returned.

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 simple strripos() example

&#60;?php
$haystack = 'ababcd';
$needle   = 'aB';

$pos      = strripos($haystack, $needle);

if ($pos === false) {
    echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
    echo "Congratulations!\n";
    echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?&#62;

Outputs:

Congratulations!
   We found the last (aB) in (ababcd) at position (2)

The offset parameter may be specified to begin searching an arbitrary number of characters into the string.

Negative offset values will start the search at offset characters from the start of the string.

See also strrpos(),
strrchr(),
substr(), stripos() and
stristr().

Prev | Home | Next
strrev | Up | strrpos


strrpos

(PHP 3, PHP 4, PHP 5)

strrpos -- Find position of last occurrence of a char in a string

Description

int strrpos ( string haystack, string needle [, int offset] )

Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character in PHP 4. If a string is passed as the needle, then only the first character of that string will be used.

If needle is not found, returns FALSE.

It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

&#60;?php

// in PHP 4.0.0 and newer:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0.0:
$pos = strrpos($mystring, "b");
if (is_bool($pos) &#38;&#38; !$pos) {
    // not found...
}
?&#62;

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Note: As of PHP 5.0.0 offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.

Note: The needle may be a string of more than one character as of PHP 5.0.0.

See also strpos(),
strripos(),
strrchr(),
substr(),
stristr(), and
strstr().

Prev | Home | Next
strripos | Up | strspn


strspn

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

strspn -- Find length of initial segment matching mask

Description

int strspn ( string str1, string str2 [, int start [, int length]] )

Returns the length of the initial segment of str1 which consists entirely of characters in str2.

The line of code:

&#60;?php
$var = strspn("42 is the answer, what is the question ...", "1234567890");
?&#62;

will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".

As of PHP 4.3.0, strspn() accepts two optional integer parameters that can be used to define the start position and the length of the string to examine.

&#60;?php
echo strspn("foo", "o", 1, 2); // 2
?&#62;

Note: This function is binary-safe.

See also strcspn().

Prev | Home | Next
strrpos | Up | strstr


strstr

(PHP 3, PHP 4, PHP 5)

strstr -- Find first occurrence of a string

Description

string strstr ( string haystack, string needle )

Returns part of haystack string from the first occurrence of needle to the end of haystack.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Note: This function is case-sensitive. For case-insensitive searches, use stristr().

Example 1. strstr() example

&#60;?php
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?&#62;

Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

strstr() has been binary safe since PHP 4.3.0

See also preg_match(),
stristr(), strpos(),
strrchr(), and substr().

Prev | Home | Next
strspn | Up | strtok


strtok

(PHP 3, PHP 4, PHP 5)

strtok -- Tokenize string

Description

string strtok ( string str, string token )

strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

Example 1. strtok() example

&#60;?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok&#60;br /&#62;";
    $tok = strtok(" \n\t");
}
?&#62;

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

Example 2. Old strtok() behavior

&#60;?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?&#62;

Output:

string(0) ""
    string(9) "something"

Example 3. New strtok() behavior

&#60;?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?&#62;

Output:

string(9) "something"
    bool(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.

See also split() and explode().

Prev | Home | Next
strstr | Up | strtolower


strtolower

(PHP 3, PHP 4, PHP 5)

strtolower -- Make a string lowercase

Description

string strtolower ( string str )

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Example 1. strtolower() example

&#60;?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?&#62;

Note: This function is binary-safe.

See also strtoupper(), ucfirst(), ucwords() and mb_strtolower().

Prev | Home | Next
strtok | Up | strtoupper


strtoupper

(PHP 3, PHP 4, PHP 5)

strtoupper -- Make a string uppercase

Description

string strtoupper ( string string )

Returns string with all alphabetic characters converted to uppercase.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Example 1. strtoupper() example

&#60;?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?&#62;

Note: This function is binary-safe.

See also strtolower(), ucfirst(), ucwords() and mb_strtoupper().

Prev | Home | Next
strtolower | Up | strtr


strtr

(PHP 3, PHP 4, PHP 5)

strtr -- Translate certain characters

Description

string strtr ( string str, string from, string to )

string strtr ( string str, array replace_pairs )

This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to.

If from and to are different lengths, the extra characters in the longer of the two are ignored.

Example 1. strtr() example

&#60;?php
$addr = strtr($addr, "äåö", "aao");
?&#62;

strtr() may be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.

Example 2. strtr() example with two arguments

&#60;?php
$trans = array("hello" =&#62; "hi", "hi" =&#62; "hello");
echo strtr("hi all, I said hello", $trans);
?&#62;

This will show:

hello all, I said hi

Note: This optional to and from parameters were added in PHP 4.0.0

See also ereg_replace().

Prev | Home | Next
strtoupper | Up | substr_compare


substr_compare

(PHP 5)

substr_compare -- Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters

Description

int substr_compare ( string main_str, string str, int offset [, int length [, bool case_insensitivity]] )

substr_compare() compares main_str from position offset with str up to length characters.

Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If length is equal or greater than length of main_str and length is set, substr_compare() prints warning and returns FALSE.

If case_insensitivity is TRUE, comparison is case insensitive.

Example 1. A substr_compare() example

&#60;?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?&#62;

Prev | Home | Next
strtr | Up | substr_count


substr_count

(PHP 4, PHP 5)

substr_count -- Count the number of substring occurrences

Description

int substr_count ( string haystack, string needle [, int offset [, int length]] )

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Note: This function doesn't count overlapped substrings. See the example below!

Parameters

haystack

The string to search in

needle

The substring to search for

offset

The offset where to start counting

length

The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length.

Return Values

This functions returns an integer.

ChangeLog

Version | Description
5.1.0 | Added the offset and the length parameters

Examples

Example 1. A substr_count() example

&#60;?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);

// generates a warning because 5+10 &#62; 14
echo substr_count($text, 'is', 5, 10);

// prints only 1, because it doesn't count overlapped subtrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?&#62;

See Also

count_chars()
strpos()
substr()
strstr()

Prev | Home | Next
substr_compare | Up | substr_replace


substr_replace

(PHP 4, PHP 5)

substr_replace -- Replace text within a portion of a string

Description

mixed substr_replace ( mixed string, string replacement, int start [, int length] )

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result string is returned. If string is an array then array is returned.

If start is positive, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.

Example 1. substr_replace() example

&#60;?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var&#60;hr /&#62;\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "&#60;br /&#62;\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "&#60;br /&#62;\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "&#60;br /&#62;\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "&#60;br /&#62;\n";
echo substr_replace($var, 'bob', -7, -1) . "&#60;br /&#62;\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "&#60;br /&#62;\n";
?&#62;

Note: This function is binary-safe.

See also str_replace() and substr().

Prev | Home | Next
substr_count | Up | substr


substr

(PHP 3, PHP 4, PHP 5)

substr -- Return part of a string

Description

string substr ( string string, int start [, int length] )

substr() returns the portion of string specified by the start and length parameters.

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

Example 1. Basic substr() usage

&#60;?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achived using "curly braces"
$string = 'abcdef';
echo $string{0};                 // a
echo $string{3};                 // d
echo $string{strlen($string)-1}; // f

?&#62;

If start is negative, the returned string will start at the start'th character from the end of string.

Example 2. Using a negative start

&#60;?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?&#62;

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than or equal to start characters long, FALSE will be returned.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

Example 3. Using a negative length

&#60;?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns ""
$rest = substr("abcdef", -3, -1); // returns "de"
?&#62;

See also strrchr(),
substr_replace(),
preg_match(),
trim(),
mb_substr() and
wordwrap().

Prev | Home | Next
substr_replace | Up | trim


trim

(PHP 3, PHP 4, PHP 5)

trim -- Strip whitespace (or other characters) from the beginning and end of a string

Description

string trim ( string str [, string charlist] )

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The string that will be trimmed.

charlist

Optionally, the stripped characters can also be specified using the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

The trimmed string.

ChangeLog

Version | Description
4.1.0 | The optional charlist parameter was added.

Examples

Example 1. Usage example of trim()

&#60;?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?&#62;

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"

Example 2. Trimming array values with trim()

&#60;?php
function trim_value(&#38;$value)
{
    $value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?&#62;

The above example will output:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

See Also

ltrim()
rtrim()

Prev | Home | Next
substr | Up | ucfirst


ucfirst

(PHP 3, PHP 4, PHP 5)

ucfirst -- Make a string's first character uppercase

Description

string ucfirst ( string str )

Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Example 1. ucfirst() example

&#60;?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?&#62;

See also strtolower(), strtoupper(), and ucwords().

Prev | Home | Next
trim | Up | ucwords


ucwords

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ucwords -- Uppercase the first character of each word in a string

Description

string ucwords ( string str )

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Example 1. ucwords() example

&#60;?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?&#62;

Note: This function is binary-safe.

See also strtoupper(), strtolower() and ucfirst().

Prev | Home | Next
ucfirst | Up | vfprintf


vfprintf

(PHP 5)

vfprintf -- Write a formatted string to a stream

Description

int vfprintf ( resource handle, string format, array args )

Write a string produced according to format to the stream resource specified by handle. format is described in the documentation for sprintf().

Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments.

Returns the length of the outputted string.

See also: printf(),
sprintf(),
sscanf(), fscanf(),
vsprintf(), and
number_format().

Examples

Example 1. vfprintf(): zero-padded integers

&#60;?php
if (!($fp = fopen('date.txt', 'w')))
    return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// will write the formatted ISO date to date.txt
?&#62;

Prev | Home | Next
ucwords | Up | vprintf


vprintf

(PHP 4 >= 4.1.0, PHP 5)

vprintf -- Output a formatted string

Description

int vprintf ( string format, array args )

Display array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.

Returns the length of the outputted string.

See also printf(), sprintf(), vsprintf()

Prev | Home | Next
vfprintf | Up | vsprintf


vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf -- Return a formatted string

Description

string vsprintf ( string format, array args )

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

See also sprintf() and vprintf()

Prev | Home | Next
vprintf | Up | wordwrap


wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap -- Wraps a string to a given number of characters using a string break character

Description

string wordwrap ( string str [, int width [, string break [, bool cut]]] )

Returns a string with str wrapped at the column number specified by the optional width parameter. The line is broken using the (optional) break parameter.

wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.

If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

Note: The optional cut parameter was added in PHP 4.0.3

Example 1. wordwrap() example

&#60;?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "&#60;br /&#62;\n");

echo $newtext;
?&#62;

This example would display:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example 2. wordwrap() example

&#60;?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", 1);

echo "$newtext\n";
?&#62;

This example would display:

A very
long
wooooooo
ooooord.

See also nl2br() and chunk_split().

Prev | Home | Next
vsprintf | Up | Shockwave Flash Functions


Shockwave Flash Functions

PHP Manual
Prev Next

CLX. Shockwave Flash Functions

Introduction

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Note: SWF support was added in PHP 4 RC2.

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Requirements

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.

Installation

Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.

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.

MOD_COLOR (integer)

MOD_MATRIX (integer)

TYPE_PUSHBUTTON (integer)

TYPE_MENUBUTTON (integer)

BSHitTest (float)

BSDown (float)

BSOver (float)

BSUp (float)

OverDowntoIdle (integer)

IdletoOverDown (integer)

OutDowntoIdle (integer)

OutDowntoOverDown (integer)

OverDowntoOutDown (integer)

OverUptoOverDown (integer)

OverUptoIdle (integer)

IdletoOverUp (integer)

ButtonEnter (integer)

ButtonExit (integer)

MenuEnter (integer)

MenuExit (integer)

Examples

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Example 1. SWF example

&#60;?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i &#60; 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate(60*$p, 'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i &#60; 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?&#62;

Table of Contents
swf_actiongeturl -- Get a URL from a Shockwave Flash movie
swf_actiongotoframe -- Play a frame and then stop
swf_actiongotolabel -- Display a frame with the specified label
swf_actionnextframe -- Go forward one frame
swf_actionplay -- Start playing the flash movie from the current frame
swf_actionprevframe -- Go backwards one frame
swf_actionsettarget -- Set the context for actions
swf_actionstop -- Stop playing the flash movie at the current frame
swf_actiontogglequality -- Toggle between low and high quality
swf_actionwaitforframe -- Skip actions if a frame has not been loaded
swf_addbuttonrecord -- Controls location, appearance and active area of the current button
swf_addcolor -- Set the global add color to the rgba value specified
swf_closefile -- Close the current Shockwave Flash file
swf_definebitmap -- Define a bitmap
swf_definefont -- Defines a font
swf_defineline -- Define a line
swf_definepoly -- Define a polygon
swf_definerect -- Define a rectangle
swf_definetext -- Define a text string
swf_endbutton -- End the definition of the current button
swf_enddoaction -- End the current action
swf_endshape -- Completes the definition of the current shape
swf_endsymbol -- End the definition of a symbol
swf_fontsize -- Change the font size
swf_fontslant -- Set the font slant
swf_fonttracking -- Set the current font tracking
swf_getbitmapinfo -- Get information about a bitmap
swf_getfontinfo -- Gets font information
swf_getframe -- Get the frame number of the current frame
swf_labelframe -- Label the current frame
swf_lookat -- Define a viewing transformation
swf_modifyobject -- Modify an object
swf_mulcolor -- Sets the global multiply color to the rgba value specified
swf_nextid -- Returns the next free object id
swf_oncondition -- Describe a transition used to trigger an action list
swf_openfile -- Open a new Shockwave Flash file
swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewport
swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewport
swf_perspective -- Define a perspective projection transformation
swf_placeobject -- Place an object onto the screen
swf_polarview -- Define the viewer's position with polar coordinates
swf_popmatrix -- Restore a previous transformation matrix
swf_posround -- Enables or Disables the rounding of the translation when objects are placed or moved
swf_pushmatrix -- Push the current transformation matrix back unto the stack
swf_removeobject -- Remove an object
swf_rotate -- Rotate the current transformation
swf_scale -- Scale the current transformation
swf_setfont -- Change the current font
swf_setframe -- Switch to a specified frame
swf_shapearc -- Draw a circular arc
swf_shapecurveto3 -- Draw a cubic bezier curve
swf_shapecurveto -- Draw a quadratic bezier curve between two points
swf_shapefillbitmapclip -- Set current fill mode to clipped bitmap
swf_shapefillbitmaptile -- Set current fill mode to tiled bitmap
swf_shapefilloff -- Turns off filling
swf_shapefillsolid -- Set the current fill style to the specified color
swf_shapelinesolid -- Set the current line style
swf_shapelineto -- Draw a line
swf_shapemoveto -- Move the current position
swf_showframe -- Display the current frame
swf_startbutton -- Start the definition of a button
swf_startdoaction -- Start a description of an action list for the current frame
swf_startshape -- Start a complex shape
swf_startsymbol -- Define a symbol
swf_textwidth -- Get the width of a string
swf_translate -- Translate the current transformations
swf_viewport -- Select an area for future drawing

Prev | Home | Next
wordwrap | Up | swf_actiongeturl


swf_actiongeturl

(PHP 4, PECL)

swf_actiongeturl -- Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string url, string target )

Gets the URL specified by the parameter url with the given target.

Parameters

url

The URL, as a string.

target

The target, as a string.

Return Values

No value is returned.

Prev | Home | Next
Shockwave Flash Functions | Up | swf_actiongotoframe


swf_actiongotoframe

(PHP 4, PECL)

swf_actiongotoframe -- Play a frame and then stop

Description

void swf_actiongotoframe ( int framenumber )

The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.

Parameters

framenumber

The frame number.

Return Values

No value is returned.

Prev | Home | Next
swf_actiongeturl | Up | swf_actiongotolabel


swf_actiongotolabel

(PHP 4, PECL)

swf_actiongotolabel -- Display a frame with the specified label

Description

void swf_actiongotolabel ( string label )

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

Parameters

label

The frame label.

Return Values

No value is returned.

Prev | Home | Next
swf_actiongotoframe | Up | swf_actionnextframe


swf_actionnextframe

(PHP 4, PECL)

swf_actionnextframe -- Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

Return Values

No value is returned.

Prev | Home | Next
swf_actiongotolabel | Up | swf_actionplay


swf_actionplay

(PHP 4, PECL)

swf_actionplay -- Start playing the flash movie from the current frame

Description

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

Return Values

No value is returned.

Prev | Home | Next
swf_actionnextframe | Up | swf_actionprevframe


swf_actionprevframe

(PHP 4, PECL)

swf_actionprevframe -- Go backwards one frame

Description

void swf_actionprevframe ( void )

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
swf_actionplay | Up | swf_actionsettarget


swf_actionsettarget

(PHP 4, PECL)

swf_actionsettarget -- Set the context for actions

Description

void swf_actionsettarget ( string target )

Sets the context for all actions. You can use this to control other flash movies that are currently playing.

Parameters

target

The target, as a string.

Return Values

No value is returned.

Prev | Home | Next
swf_actionprevframe | Up | swf_actionstop


swf_actionstop

(PHP 4, PECL)

swf_actionstop -- Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

Return Values

No value is returned.

Prev | Home | Next
swf_actionsettarget | Up | swf_actiontogglequality


swf_actiontogglequality

(PHP 4, PECL)

swf_actiontogglequality -- Toggle between low and high quality

Description

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

Return Values

No value is returned.

Prev | Home | Next
swf_actionstop | Up | swf_actionwaitforframe


swf_actionwaitforframe

(PHP 4, PECL)

swf_actionwaitforframe -- Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int framenumber, int skipcount )

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

Parameters

framenumber

The frame number.

skipcount

The number of actions to skip.

Return Values

No value is returned.

Prev | Home | Next
swf_actiontogglequality | Up | swf_addbuttonrecord


swf_addbuttonrecord

(PHP 4, PECL)

swf_addbuttonrecord -- Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int states, int shapeid, int depth )

Allow you to define the specifics of using a button.

Parameters

states

Defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp.

shapeid

The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button.

depth

This parameter is the placement of the button in the current frame.

Return Values

No value is returned.

Examples

Example 1. swf_addbuttonrecord() example

&#60;?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?&#62;

Prev | Home | Next
swf_actionwaitforframe | Up | swf_addcolor


swf_addcolor

(PHP 4, PECL)

swf_addcolor -- Set the global add color to the rgba value specified

Description

void swf_addcolor ( float r, float g, float b, float a )

Sets the global add color to the specified color. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be add by the given values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

Prev | Home | Next
swf_addbuttonrecord | Up | swf_closefile


swf_closefile

(PHP 4, PECL)

swf_closefile -- Close the current Shockwave Flash file

Description

mixed swf_closefile ( [int return_file] )

Close a file that was opened by the swf_openfile() function.

Parameters

return_file

If set then the contents of the SWF file are returned from the function.

Return Values

If return_file is provided returns the SWF contents, otherwise returns NULL.

Examples

Example 1. Creating a simple flash file based on user input and outputting it and saving it in a database

&#60;?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);

    swf_definetext(11, $text, 1);

    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();

    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data)
{
    global $DBHOST,
           $DBUSER,
           $DBPASS;

    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?&#62;

Prev | Home | Next
swf_addcolor | Up | swf_definebitmap


swf_definebitmap

(PHP 4, PECL)

swf_definebitmap -- Define a bitmap

Description

void swf_definebitmap ( int objid, string image_name )

The swf_definebitmap() function defines a bitmap given an image.

Parameters

objid

An SWF object id.

image_name

A GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

Return Values

No value is returned.

Prev | Home | Next
swf_closefile | Up | swf_definefont


swf_definefont

(PHP 4, PECL)

swf_definefont -- Defines a font

Description

void swf_definefont ( int fontid, string fontname )

The swf_definefont() function defines a font parameter and gives it the specified id. It then sets the font given by fontname to the current font.

Parameters

fontid

The id to be given to the font.

fontname

The font so be set as current font.

Return Values

No value is returned.

Prev | Home | Next
swf_definebitmap | Up | swf_defineline


swf_defineline

(PHP 4, PECL)

swf_defineline -- Define a line

Description

void swf_defineline ( int objid, float x1, float y1, float x2, float y2, float width )

Defines a line.

Parameters

objid

The object id.

x1

x-coordinate of start point.

y1

y-coordinate of start point.

x2

x-coordinate of end point.

y2

y-coordinate of end point.

width

The line width.

Return Values

No value is returned.

Prev | Home | Next
swf_definefont | Up | swf_definepoly


swf_definepoly

(PHP 4, PECL)

swf_definepoly -- Define a polygon

Description

void swf_definepoly ( int objid, array coords, int npoints, float width )

Defines a polygon given an array of x, y coordinates.

Parameters

objid

The object id.

coords

An array of x, y coordinates.

npoints

The number of overall points that are contained in the array given by coords

width

The width of the polygon's border, if set to 0.0 the polygon is filled.

Return Values

No value is returned.

Prev | Home | Next
swf_defineline | Up | swf_definerect


swf_definerect

(PHP 4, PECL)

swf_definerect -- Define a rectangle

Description

void swf_definerect ( int objid, float x1, float y1, float x2, float y2, float width )

Defines a rectangle with an upper left hand coordinate and a lower right hand coordinate.

Parameters

objid

The object id.

x1

x-coordinate of upper left point.

y1

y-coordinate of upper left point.

x2

x-coordinate of lower right point.

y2

y-coordinate of lower right point.

width

Width of the rectangles border, if the width is 0.0 then the rectangle is filled.

Return Values

No value is returned.

Prev | Home | Next
swf_definepoly | Up | swf_definetext


swf_definetext

(PHP 4, PECL)

swf_definetext -- Define a text string

Description

void swf_definetext ( int objid, string str, int docenter )

Defines a text string using the current font and font size.

Parameters

objid

The object id.

str

The text, as a string.

docenter

The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

Return Values

No value is returned.

Prev | Home | Next
swf_definerect | Up | swf_endbutton


swf_endbutton

(PHP 4, PECL)

swf_endbutton -- End the definition of the current button

Description

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

Return Values

No value is returned.

Prev | Home | Next
swf_definetext | Up | swf_enddoaction


swf_enddoaction

(PHP 4, PECL)

swf_enddoaction -- End the current action

Description

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

Return Values

No value is returned.

Prev | Home | Next
swf_endbutton | Up | swf_endshape


swf_endshape

(PHP 4, PECL)

swf_endshape -- Completes the definition of the current shape

Description

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

Return Values

No value is returned.

Prev | Home | Next
swf_enddoaction | Up | swf_endsymbol


swf_endsymbol

(PHP 4, PECL)

swf_endsymbol -- End the definition of a symbol

Description

void swf_endsymbol ( void )

Ends the definition of a symbol that was started by the swf_startsymbol() function.

Return Values

No value is returned.

Prev | Home | Next
swf_endshape | Up | swf_fontsize


swf_fontsize

(PHP 4, PECL)

swf_fontsize -- Change the font size

Description

void swf_fontsize ( float size )

Changes the font size to the value given by the size parameter.

Parameters

size

The font size, as an integer.

Return Values

No value is returned.

Prev | Home | Next
swf_endsymbol | Up | swf_fontslant


swf_fontslant

(PHP 4, PECL)

swf_fontslant -- Set the font slant

Description

void swf_fontslant ( float slant )

Set the current font slant to the angle indicated by the slant parameter.

Parameters

slant

Positive values create a forward slant, negative values create a negative slant.

Return Values

No value is returned.

Prev | Home | Next
swf_fontsize | Up | swf_fonttracking


swf_fonttracking

(PHP 4, PECL)

swf_fonttracking -- Set the current font tracking

Description

void swf_fonttracking ( float tracking )

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

Parameters

tracking

The font tracking.

Return Values

No value is returned.

Prev | Home | Next
swf_fontslant | Up | swf_getbitmapinfo


swf_getbitmapinfo

(PHP 4, PECL)

swf_getbitmapinfo -- Get information about a bitmap

Description

array swf_getbitmapinfo ( int bitmapid )

Returns information about a bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

Returns an array with the following elements:

  • "size" - The size in bytes of the bitmap.

  • "width" - The width in pixels of the bitmap.

  • "height" - The height in pixels of the bitmap.

Prev | Home | Next
swf_fonttracking | Up | swf_getfontinfo


swf_getfontinfo

(PHP 4, PECL)

swf_getfontinfo -- Gets font information

Description

array swf_getfontinfo ( void )

Gets information about the font by giving the height in pixels of a capital A and a lowercase x.

Return Values

Returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.

  • xheight - The height in pixels of a lowercase x.

Prev | Home | Next
swf_getbitmapinfo | Up | swf_getframe


swf_getframe

(PHP 4, PECL)

swf_getframe -- Get the frame number of the current frame

Description

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

Return Values

Returns the current frame number, as an integer.

Prev | Home | Next
swf_getfontinfo | Up | swf_labelframe


swf_labelframe

(PHP 4, PECL)

swf_labelframe -- Label the current frame

Description

void swf_labelframe ( string name )

Labels the current frame with the given name.

Parameters

name

The frame label.

Return Values

No value is returned.

Prev | Home | Next
swf_getframe | Up | swf_lookat


swf_lookat

(PHP 4, PECL)

swf_lookat -- Define a viewing transformation

Description

void swf_lookat ( float view_x, float view_y, float view_z, float reference_x, float reference_y, float reference_z, float twist )

Defines a viewing transformation by giving the viewing position and the coordinates of a reference point in the scene.

Parameters

view_x

x-coordinate for the viewing position

view_y

y-coordinate for the viewing position

view_z

z-coordinate for the viewing position

reference_x

x-coordinate for the reference point

reference_y

y-coordinate for the reference point

reference_z

z-coordinate for the reference point

twist

Controls the rotation along with viewer's z axis.

Return Values

No value is returned.

Prev | Home | Next
swf_labelframe | Up | swf_modifyobject


swf_modifyobject

(PHP 4, PECL)

swf_modifyobject -- Modify an object

Description

void swf_modifyobject ( int depth, int how )

Updates the position and/or color of the object at the specified depth.

Parameters

depth

The depth, as an integer.

how

Determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both.

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

Return Values

No value is returned.

Prev | Home | Next
swf_lookat | Up | swf_mulcolor


swf_mulcolor

(PHP 4, PECL)

swf_mulcolor -- Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float r, float g, float b, float a )

Sets the global multiply color to the given one. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be multiplied by the given color values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

Prev | Home | Next
swf_modifyobject | Up | swf_nextid


swf_nextid

(PHP 4, PECL)

swf_nextid -- Returns the next free object id

Description

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

Return Values

Returns the id, as an integer.

Prev | Home | Next
swf_mulcolor | Up | swf_oncondition


swf_oncondition

(PHP 4, PECL)

swf_oncondition -- Describe a transition used to trigger an action list

Description

void swf_oncondition ( int transition )

The swf_oncondition() function describes a transition that will trigger an action list.

Parameters

transition

There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • IdletoOverDown

  • OutDowntoIdle

  • MenuEnter (IdletoOverUp|IdletoOverDown)

  • MenuExit (OverUptoIdle|OverDowntoIdle)

For TYPE_PUSHBUTTON there are the following options:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • OverDowntoOutDown

  • OutDowntoOverDown

  • OutDowntoIdle

  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)

  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

Return Values

No value is returned.

Prev | Home | Next
swf_nextid | Up | swf_openfile


swf_openfile

(PHP 4, PECL)

swf_openfile -- Open a new Shockwave Flash file

Description

void swf_openfile ( string filename, float width, float height, float framerate, float r, float g, float b )

Opens a new file. This must be the first function you call, otherwise your script will not work.

Parameters

filename

The path to the SWF file. If you want to send your output to the screen, set this to php://stdout.

width

The movie width

height

The movie height

framerate

The frame rate.

r

Red value for the background.

g

Green value for the background.

b

Blue value for the background.

Return Values

No value is returned.

ChangeLog

Version | Description
4.0.1 | Support for php://stdout was added.

Prev | Home | Next
swf_oncondition | Up | swf_ortho2


swf_ortho2

(PHP 4, PECL)

swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float xmin, float xmax, float ymin, float ymax )

Defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie.

If a perspective transformation is desired, swf_perspective() can be used.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

Prev | Home | Next
swf_openfile | Up | swf_ortho


swf_ortho

(PHP 4 >= 4.0.1, PECL)

swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float xmin, float xmax, float ymin, float ymax, float zmin, float zmax )

Defines an orthographic mapping of user coordinates onto the current viewport.

Parameters

xmin

xmax

ymin

ymax

zmin

zmax

Return Values

No value is returned.

Prev | Home | Next
swf_ortho2 | Up | swf_perspective


swf_perspective

(PHP 4, PECL)

swf_perspective -- Define a perspective projection transformation

Description

void swf_perspective ( float fovy, float aspect, float near, float far )

Defines a perspective projection transformation.

Note: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

Parameters

fovy

A field-of-view angle in the y direction.

aspect

The aspect ratio of the viewport that is being drawn onto.

near

The near clipping plane.

far

The far clipping plane.

Return Values

No value is returned.

Prev | Home | Next
swf_ortho | Up | swf_placeobject


swf_placeobject

(PHP 4, PECL)

swf_placeobject -- Place an object onto the screen

Description

void swf_placeobject ( int objid, int depth )

Places the object in the current frame at a specified depth.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Parameters

objid

The object id.

depth

Must be between 1 and 65535.

Return Values

No value is returned.

Prev | Home | Next
swf_perspective | Up | swf_polarview


swf_polarview

(PHP 4, PECL)

swf_polarview -- Define the viewer's position with polar coordinates

Description

void swf_polarview ( float dist, float azimuth, float incidence, float twist )

The swf_polarview() function defines the viewer's position in polar coordinates.

Parameters

dist

The distance between the viewpoint to the world space origin.

azimuth

Defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis.

incidence

Defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis.

twist

Specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

Return Values

No value is returned.

Prev | Home | Next
swf_placeobject | Up | swf_popmatrix


swf_popmatrix

(PHP 4, PECL)

swf_popmatrix -- Restore a previous transformation matrix

Description

void swf_popmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Return Values

No value is returned.

Prev | Home | Next
swf_polarview | Up | swf_posround


swf_posround

(PHP 4, PECL)

swf_posround -- Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int round )

Enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled.

Parameters

round

Whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

Return Values

No value is returned.

Prev | Home | Next
swf_popmatrix | Up | swf_pushmatrix


swf_pushmatrix

(PHP 4, PECL)

swf_pushmatrix -- Push the current transformation matrix back unto the stack

Description

void swf_pushmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Return Values

No value is returned.

Prev | Home | Next
swf_posround | Up | swf_removeobject


swf_removeobject

(PHP 4, PECL)

swf_removeobject -- Remove an object

Description

void swf_removeobject ( int depth )

Removes the object at the depth specified by depth.

Parameters

depth

The depth, as an integer.

Return Values

No value is returned.

Prev | Home | Next
swf_pushmatrix | Up | swf_rotate


swf_rotate

(PHP 4, PECL)

swf_rotate -- Rotate the current transformation

Description

void swf_rotate ( float angle, string axis )

Rotates the current transformation by a given angle around the given axis.

Parameters

angle

The rotation angle.

axis

The axis. Valid values axis are x (the x axis), y (the y axis) or z (the z axis).

Return Values

No value is returned.

Prev | Home | Next
swf_removeobject | Up | swf_scale


swf_scale

(PHP 4, PECL)

swf_scale -- Scale the current transformation

Description

void swf_scale ( float x, float y, float z )

The swf_scale() scales curve coordinates by the given value.

Parameters

x

x scale factor.

y

y scale factor.

z

z scale factor.

Return Values

No value is returned.

Prev | Home | Next
swf_rotate | Up | swf_setfont


swf_setfont

(PHP 4, PECL)

swf_setfont -- Change the current font

Description

void swf_setfont ( int fontid )

The swf_setfont() sets the current font to the value given by the fontid parameter.

Parameters

fontid

The font identifier.

Return Values

No value is returned.

Prev | Home | Next
swf_scale | Up | swf_setframe


swf_setframe

(PHP 4, PECL)

swf_setframe -- Switch to a specified frame

Description

void swf_setframe ( int framenumber )

Changes the active frame to the specified on.

Parameters

framenumber

The frame number to be set.

Return Values

No value is returned.

Prev | Home | Next
swf_setfont | Up | swf_shapearc


swf_shapearc

(PHP 4, PECL)

swf_shapearc -- Draw a circular arc

Description

void swf_shapearc ( float x, float y, float r, float ang1, float ang2 )

Draws a circular arc.

Parameters

x

x-coordinate of the center.

y

y-coordinate of the center.

r

The arc radius.

ang1

The start angle.

ang2

The end angle.

Return Values

No value is returned.

Prev | Home | Next
swf_setframe | Up | swf_shapecurveto3


swf_shapecurveto3

(PHP 4, PECL)

swf_shapecurveto3 -- Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float x1, float y1, float x2, float y2, float x3, float y3 )

Draw a cubic bezier curve using the given coordinates.

The current position is then set to the x3,y3 coordinate.

Parameters

x1

x-coordinate of the first off curve control point.

y1

y-coordinate of the first off curve control point.

x2

x-coordinate of the second off curve control point.

y2

y-coordinate of the second off curve control point.

x3

x-coordinate of the endpoint.

y3

y-coordinate of the endpoint.

Return Values

No value is returned.

Prev | Home | Next
swf_shapearc | Up | swf_shapecurveto


swf_shapecurveto

(PHP 4, PECL)

swf_shapecurveto -- Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float x1, float y1, float x2, float y2 )

Draws a quadratic bezier curve from the current location, though the two given points.

The current position is then set to the point defined by the x2 and y2 parameters.

Parameters

x1

x-coordinate of the first point.

y1

y-coordinate of the first point.

x2

x-coordinate of the second point.

y2

y-coordinate of the second point.

Return Values

No value is returned.

Prev | Home | Next
swf_shapecurveto3 | Up | swf_shapefillbitmapclip


swf_shapefillbitmapclip

(PHP 4, PECL)

swf_shapefillbitmapclip -- Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int bitmapid )

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

Prev | Home | Next
swf_shapecurveto | Up | swf_shapefillbitmaptile


swf_shapefillbitmaptile

(PHP 4, PECL)

swf_shapefillbitmaptile -- Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int bitmapid )

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

Prev | Home | Next
swf_shapefillbitmapclip | Up | swf_shapefilloff


swf_shapefilloff

(PHP 4, PECL)

swf_shapefilloff -- Turns off filling

Description

void swf_shapefilloff ( void )

Turns off filling for the current shape.

Return Values

No value is returned.

Prev | Home | Next
swf_shapefillbitmaptile | Up | swf_shapefillsolid


swf_shapefillsolid

(PHP 4, PECL)

swf_shapefillsolid -- Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float r, float g, float b, float a )

Sets the current fill style to solid, and then sets the fill color to the given color.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

Return Values

No value is returned.

Prev | Home | Next
swf_shapefilloff | Up | swf_shapelinesolid


swf_shapelinesolid

(PHP 4, PECL)

swf_shapelinesolid -- Set the current line style

Description

void swf_shapelinesolid ( float r, float g, float b, float a, float width )

Sets the current line style to the given color and width.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

width

The line width. If 0.0 is given then no lines are drawn.

Return Values

No value is returned.

Prev | Home | Next
swf_shapefillsolid | Up | swf_shapelineto


swf_shapelineto

(PHP 4, PECL)

swf_shapelineto -- Draw a line

Description

void swf_shapelineto ( float x, float y )

Draws a line to the x and y coordinates. The current position is then set to that point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

Prev | Home | Next
swf_shapelinesolid | Up | swf_shapemoveto


swf_shapemoveto

(PHP 4, PECL)

swf_shapemoveto -- Move the current position

Description

void swf_shapemoveto ( float x, float y )

Moves the current position to the given point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

Prev | Home | Next
swf_shapelineto | Up | swf_showframe


swf_showframe

(PHP 4, PECL)

swf_showframe -- Display the current frame

Description

void swf_showframe ( void )

Outputs the current frame.

Return Values

No value is returned.

Prev | Home | Next
swf_shapemoveto | Up | swf_startbutton


swf_startbutton

(PHP 4, PECL)

swf_startbutton -- Start the definition of a button

Description

void swf_startbutton ( int objid, int type )

Starts the definition of a button.

Parameters

objid

The object id.

type

Can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

Return Values

No value is returned.

Prev | Home | Next
swf_showframe | Up | swf_startdoaction


swf_startdoaction

(PHP 4, PECL)

swf_startdoaction -- Start a description of an action list for the current frame

Description

void swf_startdoaction ( void )

Starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

Return Values

No value is returned.

Prev | Home | Next
swf_startbutton | Up | swf_startshape


swf_startshape

(PHP 4, PECL)

swf_startshape -- Start a complex shape

Description

void swf_startshape ( int objid )

Starts a complex shape.

Parameters

objid

The object id.

Return Values

No value is returned.

Prev | Home | Next
swf_startdoaction | Up | swf_startsymbol


swf_startsymbol

(PHP 4, PECL)

swf_startsymbol -- Define a symbol

Description

void swf_startsymbol ( int objid )

Defines an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously.

Parameters

objid

The object id you want to define as a symbol.

Return Values

No value is returned.

Prev | Home | Next
swf_startshape | Up | swf_textwidth


swf_textwidth

(PHP 4, PECL)

swf_textwidth -- Get the width of a string

Description

float swf_textwidth ( string str )

Gives the width of the string in pixels, using the current font and font size.

Parameters

str

The string.

Return Values

Returns the line width, as a float.

Prev | Home | Next
swf_startsymbol | Up | swf_translate


swf_translate

(PHP 4, PECL)

swf_translate -- Translate the current transformations

Description

void swf_translate ( float x, float y, float z )

Translates the current transformation by the given values.

Parameters

x

x value.

y

y value.

z

z value.

Return Values

No value is returned.

Prev | Home | Next
swf_textwidth | Up | swf_viewport


swf_viewport

(PHP 4, PECL)

swf_viewport -- Select an area for future drawing

Description

void swf_viewport ( float xmin, float xmax, float ymin, float ymax )

Selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

Prev | Home | Next
swf_translate | Up | Swish-e bindings


Sybase Functions

PHP Manual
Prev Next

CLXII. Sybase Functions

Introduction

Requirements

Installation

To enable Sybase-DB support configure PHP --with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Sybase configuration options

Name | Default | Changeable | Changelog
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM |
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.compatability_mode | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

sybase.compatability_mode boolean

Compatibility mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatibility mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.

magic_quotes_sybase boolean

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

Note: Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Table 2. Sybase-CT configuration options

Name | Default | Changeable | Changelog
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is -1, or "forever".

For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

Predefined Constants

This extension has no constants defined.

Table of Contents
sybase_affected_rows -- Gets number of affected rows in last query
sybase_close -- Closes a Sybase connection
sybase_connect -- Opens a Sybase server connection
sybase_data_seek -- Moves internal row pointer
sybase_deadlock_retry_count -- Sets the deadlock retry count
sybase_fetch_array -- Fetch row as array
sybase_fetch_assoc -- Fetch a result row as an associative array
sybase_fetch_field -- Get field information from a result
sybase_fetch_object -- Fetch a row as an object
sybase_fetch_row -- Get a result row as an enumerated array
sybase_field_seek -- Sets field offset
sybase_free_result -- Frees result memory
sybase_get_last_message -- Returns the last message from the server
sybase_min_client_severity -- Sets minimum client severity
sybase_min_error_severity -- Sets minimum error severity
sybase_min_message_severity -- Sets minimum message severity
sybase_min_server_severity -- Sets minimum server severity
sybase_num_fields -- Gets the number of fields in a result set
sybase_num_rows -- Get number of rows in a result set
sybase_pconnect -- Open persistent Sybase connection
sybase_query -- Sends a Sybase query
sybase_result -- Get result data
sybase_select_db -- Selects a Sybase database
sybase_set_message_handler -- Sets the handler called when a server message is raised
sybase_unbuffered_query -- Send a Sybase query and do not block

Prev | Home | Next
SwishSearch->setStructure | Up | sybase_affected_rows


sybase_affected_rows

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sybase_affected_rows -- Gets number of affected rows in last query

Description

int sybase_affected_rows ( [resource link_identifier] )

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Example 1. Delete-Query

&#60;?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id &#60; 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?&#62;

The above example will output:

Records deleted: 10

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

See also sybase_num_rows().

Prev | Home | Next
Sybase Functions | Up | sybase_close


sybase_close

(PHP 3, PHP 4, PHP 5)

sybase_close -- Closes a Sybase connection

Description

bool sybase_close ( [resource link_identifier] )

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier. If the link identifier isn't specified, the last opened link is assumed.

Returns TRUE on success or FALSE on failure.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

See also sybase_connect() and sybase_pconnect().

Prev | Home | Next
sybase_affected_rows | Up | sybase_connect


sybase_connect

(PHP 3, PHP 4, PHP 5)

sybase_connect -- Opens a Sybase server connection

Description

resource sybase_connect ( [string servername [, string username [, string password [, string charset [, string appname]]]]] )

Returns a positive Sybase link identifier on success, or FALSE on failure.

sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().

Example 1. sybase_connect() example

&#60;?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?&#62;

See also sybase_pconnect() and sybase_close().

Prev | Home | Next
sybase_close | Up | sybase_data_seek


sybase_data_seek

(PHP 3, PHP 4, PHP 5)

sybase_data_seek -- Moves internal row pointer

Description

bool sybase_data_seek ( resource result_identifier, int row_number )

Returns TRUE on success or FALSE on failure.

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

See also sybase_fetch_row().

Prev | Home | Next
sybase_connect | Up | sybase_deadlock_retry_count


sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count -- Sets the deadlock retry count

Description

void sybase_deadlock_retry_count ( int retry_count )

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

Table 1. Values for retry_count

-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Prev | Home | Next
sybase_data_seek | Up | sybase_fetch_array


sybase_fetch_array

(PHP 3, PHP 4, PHP 5)

sybase_fetch_array -- Fetch row as array

Description

array sybase_fetch_array ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Note: When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Example 1. Identical fieldnames

&#60;?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?&#62;

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

array(4) {
  [0]=>
  int(1)
  ["person_id"]=>
  int(1)
  [1]=>
  int(1)
  ["person_id1"]=>
  int(1)
}

See also
sybase_fetch_row(),
sybase_fetch_assoc() and
sybase_fetch_object().

Prev | Home | Next
sybase_deadlock_retry_count | Up | sybase_fetch_assoc


sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc -- Fetch a result row as an associative array

Description

array sybase_fetch_assoc ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

See also
sybase_fetch_array(),
sybase_fetch_object() and
sybase_fetch_row().

Prev | Home | Next
sybase_fetch_array | Up | sybase_fetch_field


sybase_fetch_field

(PHP 3, PHP 4, PHP 5)

sybase_fetch_field -- Get field information from a result

Description

object sybase_fetch_field ( resource result [, int field_offset] )

Returns an object containing field information.

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.

  • column_source - the table from which the column was taken

  • max_length - maximum length of the column

  • numeric - 1 if the column is numeric

  • type - datatype of the column

See also sybase_field_seek().

Prev | Home | Next
sybase_fetch_assoc | Up | sybase_fetch_object


sybase_fetch_object

(PHP 3, PHP 4, PHP 5)

sybase_fetch_object -- Fetch a row as an object

Description

object sybase_fetch_object ( resource result [, mixed object] )

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Note: As of PHP 4.3.0, this function will no longer return numeric object members.

Old behaviour:

object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

Example 1. sybase_fetch_object() return as Foo

&#60;?php
    class Foo {
        var $foo, $bar, $baz;
    }

    // {...]
    $qrh= sybase_query('SELECT foo, bar, baz FROM example');
    $foo= sybase_fetch_object($qrh, 'Foo');
    $bar= sybase_fetch_object($qrh, new Foo());
    // {...]
?&#62;

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

See also sybase_fetch_array() and sybase_fetch_row().

Prev | Home | Next
sybase_fetch_field | Up | sybase_fetch_row


sybase_fetch_row

(PHP 3, PHP 4, PHP 5)

sybase_fetch_row -- Get a result row as an enumerated array

Description

array sybase_fetch_row ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Table 1. Data types

PHP | Sybase
string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL | NULL

See also
sybase_fetch_array(),
sybase_fetch_assoc(),
sybase_fetch_object(),
sybase_data_seek() and
sybase_result().

Prev | Home | Next
sybase_fetch_object | Up | sybase_field_seek


sybase_field_seek

(PHP 3, PHP 4, PHP 5)

sybase_field_seek -- Sets field offset

Description

bool sybase_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Returns TRUE on success or FALSE on failure.

See also sybase_fetch_field().

Prev | Home | Next
sybase_fetch_row | Up | sybase_free_result


sybase_free_result

(PHP 3, PHP 4, PHP 5)

sybase_free_result -- Frees result memory

Description

bool sybase_free_result ( resource result )

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

Prev | Home | Next
sybase_field_seek | Up | sybase_get_last_message


sybase_get_last_message

(PHP 3, PHP 4, PHP 5)

sybase_get_last_message -- Returns the last message from the server

Description

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

See also sybase_min_message_severity().

Prev | Home | Next
sybase_free_result | Up | sybase_min_client_severity


sybase_min_client_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_client_severity -- Sets minimum client severity

Description

void sybase_min_client_severity ( int severity )

sybase_min_client_severity() sets the minimum client severity level.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

See also sybase_min_server_severity().

Prev | Home | Next
sybase_get_last_message | Up | sybase_min_error_severity


sybase_min_error_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_error_severity -- Sets minimum error severity

Description

void sybase_min_error_severity ( int severity )

sybase_min_error_severity() sets the minimum error severity level.

Note: This function is only available using the DB library interface to Sybase, and not the CT library.

See also sybase_min_message_severity().

Prev | Home | Next
sybase_min_client_severity | Up | sybase_min_message_severity


sybase_min_message_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_message_severity -- Sets minimum message severity

Description

void sybase_min_message_severity ( int severity )

sybase_min_message_severity() sets the minimum message severity level.

Note: This function is only available using the DB library interface to Sybase, and not the CT library.

See also sybase_min_error_severity().

Prev | Home | Next
sybase_min_error_severity | Up | sybase_min_server_severity


sybase_min_server_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_server_severity -- Sets minimum server severity

Description

void sybase_min_server_severity ( int severity )

sybase_min_server_severity() sets the minimum server severity level.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

See also sybase_min_client_severity().

Prev | Home | Next
sybase_min_message_severity | Up | sybase_num_fields


sybase_num_fields

(PHP 3, PHP 4, PHP 5)

sybase_num_fields -- Gets the number of fields in a result set

Description

int sybase_num_fields ( resource result )

sybase_num_fields() returns the number of fields in a result set.

See also
sybase_query(),
sybase_fetch_field() and
sybase_num_rows().

Prev | Home | Next
sybase_min_server_severity | Up | sybase_num_rows


sybase_num_rows

(PHP 3, PHP 4, PHP 5)

sybase_num_rows -- Get number of rows in a result set

Description

int sybase_num_rows ( resource result )

sybase_num_rows() returns the number of rows in a result set.

See also
sybase_num_fields(),
sybase_query() and
sybase_fetch_row().

Prev | Home | Next
sybase_num_fields | Up | sybase_pconnect


sybase_pconnect

(PHP 3, PHP 4, PHP 5)

sybase_pconnect -- Open persistent Sybase connection

Description

resource sybase_pconnect ( [string servername [, string username [, string password [, string charset [, string appname]]]]] )

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

See also sybase_connect().

Prev | Home | Next
sybase_num_rows | Up | sybase_query


sybase_query

(PHP 3, PHP 4, PHP 5)

sybase_query -- Sends a Sybase query

Description

mixed sybase_query ( string query [, resource link_identifier] )

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

See also sybase_select_db() and sybase_connect().

Prev | Home | Next
sybase_pconnect | Up | sybase_result


sybase_result

(PHP 3, PHP 4, PHP 5)

sybase_result -- Get result data

Description

string sybase_result ( resource result, int row, mixed field )

Returns the contents of the cell at the row and offset in the specified Sybase result set.

sybase_result() returns the contents of one cell from a Sybase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
sybase_fetch_row(),
sybase_fetch_array() and
sybase_fetch_object().

Prev | Home | Next
sybase_query | Up | sybase_select_db


sybase_select_db

(PHP 3, PHP 4, PHP 5)

sybase_select_db -- Selects a Sybase database

Description

bool sybase_select_db ( string database_name [, resource link_identifier] )

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Returns TRUE on success or FALSE on failure.

Every subsequent call to sybase_query() will be made on the active database.

See also
sybase_connect(),
sybase_pconnect() and
sybase_query()

Prev | Home | Next
sybase_result | Up | sybase_set_message_handler


sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler -- Sets the handler called when a server message is raised

Description

bool sybase_set_message_handler ( callback handler [, resource connection] )

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

Returns TRUE on success or FALSE on failure.

Note: The connection parameter was added in PHP 4.3.5.

Example 1. sybase_set_message_handler() callback function

&#60;?php
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?&#62;

Example 2. sybase_set_message_handler() callback to a class

&#60;?php
    class Sybase {
        function handler($msgnumber, $severity, $state, $line, $text)
        {
            var_dump($msgnumber, $severity, $state, $line, $text);
        }
    }

    $sybase= new Sybase();
    sybase_set_message_handler(array($sybase, 'handler'));
?&#62;

Example 3. sybase_set_message_handler() unhandled messages

&#60;?php
    // Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        if (257 == $msgnumber) {
            return false;
        }
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?&#62;

Prev | Home | Next
sybase_select_db | Up | sybase_unbuffered_query


sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query -- Send a Sybase query and do not block

Description

resource sybase_unbuffered_query ( string query, resource link_identifier [, bool store_result] )

Returns a positive Sybase result identifier on success, or FALSE on error.

Note: This function is only available using the CT library interface to Sybase, and not the DB library.

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Note: If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Example 1. sybase_unbuffered_query() example

&#60;?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;

while ($row = sybase_fetch_row($q)) {
    echo $row[0], ' ', $row[1], '&#60;br /&#62;';
    if ($i++ &#62; 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?&#62;

See also sybase_query().

Prev | Home | Next
sybase_set_message_handler | Up | TCP Wrappers Functions


TCP Wrappers Functions

PHP Manual
Prev Next

CLXIII. TCP Wrappers Functions

Introduction

The TCP wrappers provides a classical unix mechanism which has been designed to check if the remote client is able to connect from the given IP address.

Installation

Tcpwrap is currently available through PECL http://pecl.php.net/package/tcpwrap.

If PEAR is available on your *nix-like system you can use the pear installer to install the tcpwrap extension, by the following command: pear -v install tcpwrap.

You can always download the tar.gz package and install tcpwrap by hand:

Example 1. tcpwrap install by hand

gunzip tcpwrap-xxx.tgz
tar -xvf tcpwrap-xxx.tar
cd tcpwrap-xxx
phpize
./configure && make && make install

Table of Contents
tcpwrap_check -- Performs a tcpwrap check

Prev | Home | Next
sybase_unbuffered_query | Up | tcpwrap_check


tcpwrap_check

(PECL)

tcpwrap_check -- Performs a tcpwrap check

Description

bool tcpwrap_check ( string daemon, string address [, string user [, bool nodns]] )

This function consults the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.

Parameters

daemon

The service name.

address

The client remote address. Can be either an IP address or a domain name.

user

An optional user name.

nodns

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.

Return Values

This function returns TRUE if access should be granted, FALSE otherwise.

Examples

Example 1. Deny all connections from localhost

If your /etc/hosts.deny file contains:

php: 127.0.0.1

And your code looks like:

&#60;?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
  die('You are not welcome here');
}
?&#62;

See Also

For more details please consult hosts_access(3) man page.

Prev | Home | Next
TCP Wrappers Functions | Up | Tidy Functions


Tidy Functions

PHP Manual
Prev Next

CLXIV. Tidy Functions

Introduction

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.

Requirements

To use Tidy, you will need libtidy installed, available on the tidy homepage http://tidy.sourceforge.net/.

Installation

Tidy is currently available for PHP 4.3.x and PHP 5 as a PECL extension from http://pecl.php.net/package/tidy.

Note: Tidy 1.0 is just for PHP 4.3.x, while Tidy 2.0 is just for PHP 5.

If PEAR is available on your *nix-like system you can use the pear installer to install the tidy extension, by the following command: pecl install tidy.

You can always download the tar.gz package and install tidy by hand:

Example 1. tidy install by hand in PHP 4.3.x

gunzip tidy-xxx.tgz
tar -xvf tidy-xxx.tar
cd tidy-xxx
phpize
./configure && make && make install

Windows users can download the extension dll from http://pecl4win.php.net/ext.php/php_tidy.dll.

In PHP 5 you need only to compile using the --with-tidy option.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Tidy Configuration Options

Name | Default | Changeable | Changelog
tidy.default_config | "" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
tidy.clean_output | "0" | PHP_INI_PERDIR | Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

tidy.default_config string

Default path for tidy config file.

tidy.clean_output boolean

Turns on/off the output repairing by Tidy.

Warning

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.

Resource Types

This extension has no resource types defined.

Predefined Classes

tidyNode

Methods

  • tidyNode::getParent - Returns the parent of the current node

  • tidyNode->hasChildren - Returns TRUE if the current node has children

  • tidyNode->hasSiblings - Returns TRUE if the current node has siblings

  • tidyNode->isAsp - Returns TRUE if the current node is ASP code

  • tidyNode->isComment - Returns TRUE if the current node is a comment

  • tidyNode->isHtml - Returns TRUE if the current node is HTML

  • tidyNode->isJste - Returns TRUE if the current node is JSTE

  • tidyNode->isPhp - Returns TRUE if the current node is PHP

  • tidyNode->isText - Returns TRUE if the current node is Text (no markup)

Properties

  • value - the value of the node (e.g. the html text)

  • name - the name of the tag (e.g. html, a, etc..)

  • type - the type of the node (one of the constants above, e.g. TIDY_NODETYPE_PHP)

  • line* - the line where the node starts

  • column* - the column where the node starts

  • proprietary* - TRUE if the node refers to a proprietary tag

  • id - the ID of the tag (one of the constants above, e.g. TIDY_TAG_FRAME)

  • attribute - an array with the attributes of the current node, or NULL if there aren't any

  • child - an array with the child tidyNodes, or NULL if there aren't any

Note: The properties marked with * are just available since PHP 5.1.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.

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a <a href="XX">link</a> tag. Each TIDY_ATTR_XXX represents a HTML atribute. For example TIDY_ATTR_HREF would represent the href atribute in the previous example.

The following constants are defined:

Table 2. tidy tag constants

constant
TIDY_TAG_UNKNOWN
TIDY_TAG_A
TIDY_TAG_ABBR
TIDY_TAG_ACRONYM
TIDY_TAG_ALIGN
TIDY_TAG_APPLET
TIDY_TAG_AREA
TIDY_TAG_B
TIDY_TAG_BASE
TIDY_TAG_BASEFONT
TIDY_TAG_BDO
TIDY_TAG_BGSOUND
TIDY_TAG_BIG
TIDY_TAG_BLINK
TIDY_TAG_BLOCKQUOTE
TIDY_TAG_BODY
TIDY_TAG_BR
TIDY_TAG_BUTTON
TIDY_TAG_CAPTION
TIDY_TAG_CENTER
TIDY_TAG_CITE
TIDY_TAG_CODE
TIDY_TAG_COL
TIDY_TAG_COLGROUP
TIDY_TAG_COMMENT
TIDY_TAG_DD
TIDY_TAG_DEL
TIDY_TAG_DFN
TIDY_TAG_DIR
TIDY_TAG_DIV
TIDY_TAG_DL
TIDY_TAG_DT
TIDY_TAG_EM
TIDY_TAG_EMBED
TIDY_TAG_FIELDSET
TIDY_TAG_FONT
TIDY_TAG_FORM
TIDY_TAG_FRAME
TIDY_TAG_FRAMESET
TIDY_TAG_H1
TIDY_TAG_H2
TIDY_TAG_H3
TIDY_TAG_H4
TIDY_TAG_H5
TIDY_TAG_H6
TIDY_TAG_HEAD
TIDY_TAG_HR
TIDY_TAG_HTML
TIDY_TAG_I
TIDY_TAG_IFRAME
TIDY_TAG_ILAYER
TIDY_TAG_IMG
TIDY_TAG_INPUT
TIDY_TAG_INS
TIDY_TAG_ISINDEX
TIDY_TAG_KBD
TIDY_TAG_KEYGEN
TIDY_TAG_LABEL
TIDY_TAG_LAYER
TIDY_TAG_LEGEND
TIDY_TAG_LI
TIDY_TAG_LINK
TIDY_TAG_LISTING
TIDY_TAG_MAP
TIDY_TAG_MARQUEE
TIDY_TAG_MENU
TIDY_TAG_META
TIDY_TAG_MULTICOL
TIDY_TAG_NOBR
TIDY_TAG_NOEMBED
TIDY_TAG_NOFRAMES
TIDY_TAG_NOLAYER
TIDY_TAG_NOSAVE
TIDY_TAG_NOSCRIPT
TIDY_TAG_OBJECT
TIDY_TAG_OL
TIDY_TAG_OPTGROUP
TIDY_TAG_OPTION
TIDY_TAG_P
TIDY_TAG_PARAM
TIDY_TAG_PLAINTEXT
TIDY_TAG_PRE
TIDY_TAG_Q
TIDY_TAG_RP
TIDY_TAG_RT
TIDY_TAG_RTC
TIDY_TAG_RUBY
TIDY_TAG_S
TIDY_TAG_SAMP
TIDY_TAG_SCRIPT
TIDY_TAG_SELECT
TIDY_TAG_SERVER
TIDY_TAG_SERVLET
TIDY_TAG_SMALL
TIDY_TAG_SPACER
TIDY_TAG_SPAN
TIDY_TAG_STRIKE
TIDY_TAG_STRONG
TIDY_TAG_STYLE
TIDY_TAG_SUB
TIDY_TAG_TABLE
TIDY_TAG_TBODY
TIDY_TAG_TD
TIDY_TAG_TEXTAREA
TIDY_TAG_TFOOT
TIDY_TAG_TH
TIDY_TAG_THEAD
TIDY_TAG_TITLE
TIDY_TAG_TR
TIDY_TAG_TR
TIDY_TAG_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

Table 3. tidy attribute constants

constant
TIDY_ATTR_UNKNOWN
TIDY_ATTR_ABBR
TIDY_ATTR_ACCEPT
TIDY_ATTR_ACCEPT_CHARSET
TIDY_ATTR_ACCESSKEY
TIDY_ATTR_ACTION
TIDY_ATTR_ADD_DATE
TIDY_ATTR_ALIGN
TIDY_ATTR_ALINK
TIDY_ATTR_ALT
TIDY_ATTR_ARCHIVE
TIDY_ATTR_AXIS
TIDY_ATTR_BACKGROUND
TIDY_ATTR_BGCOLOR
TIDY_ATTR_BGPROPERTIES
TIDY_ATTR_BORDER
TIDY_ATTR_BORDERCOLOR
TIDY_ATTR_BOTTOMMARGIN
TIDY_ATTR_CELLPADDING
TIDY_ATTR_CELLSPACING
TIDY_ATTR_CHAR
TIDY_ATTR_CHAROFF
TIDY_ATTR_CHARSET
TIDY_ATTR_CHECKED
TIDY_ATTR_CITE
TIDY_ATTR_CLASS
TIDY_ATTR_CLASSID
TIDY_ATTR_CLEAR
TIDY_ATTR_CODE
TIDY_ATTR_CODEBASE
TIDY_ATTR_CODETYPE
TIDY_ATTR_COLOR
TIDY_ATTR_COLS
TIDY_ATTR_COLSPAN
TIDY_ATTR_COMPACT
TIDY_ATTR_CONTENT
TIDY_ATTR_COORDS
TIDY_ATTR_DATA
TIDY_ATTR_DATAFLD
TIDY_ATTR_DATAPAGESIZE
TIDY_ATTR_DATASRC
TIDY_ATTR_DATETIME
TIDY_ATTR_DECLARE
TIDY_ATTR_DEFER
TIDY_ATTR_DIR
TIDY_ATTR_DISABLED
TIDY_ATTR_ENCODING
TIDY_ATTR_ENCTYPE
TIDY_ATTR_FACE
TIDY_ATTR_FOR
TIDY_ATTR_FRAME
TIDY_ATTR_FRAMEBORDER
TIDY_ATTR_FRAMESPACING
TIDY_ATTR_GRIDX
TIDY_ATTR_GRIDY
TIDY_ATTR_HEADERS
TIDY_ATTR_HEIGHT
TIDY_ATTR_HREF
TIDY_ATTR_HREFLANG
TIDY_ATTR_HSPACE
TIDY_ATTR_HTTP_EQUIV
TIDY_ATTR_ID
TIDY_ATTR_ISMAP
TIDY_ATTR_LABEL
TIDY_ATTR_LANG
TIDY_ATTR_LANGUAGE
TIDY_ATTR_LAST_MODIFIED
TIDY_ATTR_LAST_VISIT
TIDY_ATTR_LEFTMARGIN
TIDY_ATTR_LINK
TIDY_ATTR_LONGDESC
TIDY_ATTR_LOWSRC
TIDY_ATTR_MARGINHEIGHT
TIDY_ATTR_MARGINWIDTH
TIDY_ATTR_MAXLENGTH
TIDY_ATTR_MEDIA
TIDY_ATTR_METHOD
TIDY_ATTR_MULTIPLE
TIDY_ATTR_NAME
TIDY_ATTR_NOHREF
TIDY_ATTR_NORESIZE
TIDY_ATTR_NOSHADE
TIDY_ATTR_NOWRAP
TIDY_ATTR_OBJECT
TIDY_ATTR_OnAFTERUPDATE
TIDY_ATTR_OnBEFOREUNLOAD
TIDY_ATTR_OnBEFOREUPDATE
TIDY_ATTR_OnBLUR
TIDY_ATTR_OnCHANGE
TIDY_ATTR_OnCLICK
TIDY_ATTR_OnDATAAVAILABLE
TIDY_ATTR_OnDATASETCHANGED
TIDY_ATTR_OnDATASETCOMPLETE
TIDY_ATTR_OnDBLCLICK
TIDY_ATTR_OnERRORUPDATE
TIDY_ATTR_OnFOCUS
TIDY_ATTR_OnKEYDOWN
TIDY_ATTR_OnKEYPRESS
TIDY_ATTR_OnKEYUP
TIDY_ATTR_OnLOAD
TIDY_ATTR_OnMOUSEDOWN
TIDY_ATTR_OnMOUSEMOVE
TIDY_ATTR_OnMOUSEOUT
TIDY_ATTR_OnMOUSEOVER
TIDY_ATTR_OnMOUSEUP
TIDY_ATTR_OnRESET
TIDY_ATTR_OnROWENTER
TIDY_ATTR_OnROWEXIT
TIDY_ATTR_OnSELECT
TIDY_ATTR_OnSUBMIT
TIDY_ATTR_OnUNLOAD
TIDY_ATTR_PROFILE
TIDY_ATTR_PROMPT
TIDY_ATTR_RBSPAN
TIDY_ATTR_READONLY
TIDY_ATTR_REL
TIDY_ATTR_REV
TIDY_ATTR_RIGHTMARGIN
TIDY_ATTR_ROWS
TIDY_ATTR_ROWSPAN
TIDY_ATTR_RULES
TIDY_ATTR_SCHEME
TIDY_ATTR_SCOPE
TIDY_ATTR_SCROLLING
TIDY_ATTR_SELECTED
TIDY_ATTR_SHAPE
TIDY_ATTR_SHOWGRID
TIDY_ATTR_SHOWGRIDX
TIDY_ATTR_SHOWGRIDY
TIDY_ATTR_SIZE
TIDY_ATTR_SPAN
TIDY_ATTR_SRC
TIDY_ATTR_STANDBY
TIDY_ATTR_START
TIDY_ATTR_STYLE
TIDY_ATTR_SUMMARY
TIDY_ATTR_TABINDEX
TIDY_ATTR_TARGET
TIDY_ATTR_TEXT
TIDY_ATTR_TITLE
TIDY_ATTR_TOPMARGIN
TIDY_ATTR_TYPE
TIDY_ATTR_USEMAP
TIDY_ATTR_VALIGN
TIDY_ATTR_VALUE
TIDY_ATTR_VALUETYPE
TIDY_ATTR_VERSION
TIDY_ATTR_VLINK
TIDY_ATTR_VSPACE
TIDY_ATTR_WIDTH
TIDY_ATTR_WRAP
TIDY_ATTR_XML_LANG
TIDY_ATTR_XML_SPACE
TIDY_ATTR_XMLNS

Table 4. tidy nodetype constants

constant | description
TIDY_NODETYPE_ROOT | root node
TIDY_NODETYPE_DOCTYPE | doctype
TIDY_NODETYPE_COMMENT | HTML comment
TIDY_NODETYPE_PROCINS | Processing Instruction
TIDY_NODETYPE_TEXT | Text
TIDY_NODETYPE_START | start tag
TIDY_NODETYPE_END | end tag
TIDY_NODETYPE_STARTEND | empty tag
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | XML section
TIDY_NODETYPE_ASP | ASP code
TIDY_NODETYPE_JSTE | JSTE code
TIDY_NODETYPE_PHP | PHP code
TIDY_NODETYPE_XMLDECL | XML declaration

Examples

This simple example shows basic Tidy usage.

Example 2. Basic Tidy usage

&#60;?php
ob_start();
?&#62;
&#60;html&#62;a html document&#60;/html&#62;
&#60;?php
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         =&#62; true,
           'output-xhtml'   =&#62; true,
           'wrap'           =&#62; 200);

// Tidy
$tidy = new tidy;
$tidy-&#62;parseString($html, $config, 'utf8');
$tidy-&#62;cleanRepair();

// Output
echo $tidy;
?&#62;

Table of Contents
ob_tidyhandler -- ob_start callback function to repair the buffer
tidy_access_count -- Returns the Number of Tidy accessibility warnings encountered for specified document
tidy_clean_repair -- Execute configured cleanup and repair operations on parsed markup
tidy_config_count -- Returns the Number of Tidy configuration errors encountered for specified document
tidy::__construct -- Constructs a new tidy object
tidy_diagnose -- Run configured diagnostics on parsed and repaired markup
tidy_error_count -- Returns the Number of Tidy errors encountered for specified document
tidy_get_body -- Returns a tidyNode Object starting from the <body> tag of the tidy parse tree
tidy_get_config -- Get current Tidy configuration
tidy_get_error_buffer -- Return warnings and errors which occurred parsing the specified document
tidy_get_head -- Returns a tidyNode Object starting from the <head> tag of the tidy parse tree
tidy_get_html_ver -- Get the Detected HTML version for the specified document
tidy_get_html -- Returns a tidyNode Object starting from the <html> tag of the tidy parse tree
tidy_get_opt_doc -- Returns the documentation for the given option name
tidy_get_output -- Return a string representing the parsed tidy markup
tidy_get_release -- Get release date (version) for Tidy library
tidy_get_root -- Returns a tidyNode object representing the root of the tidy parse tree
tidy_get_status -- Get status of specified document
tidy_getopt -- Returns the value of the specified configuration option for the tidy document
tidy_is_xhtml -- Indicates if the document is a XHTML document
tidy_is_xml -- Indicates if the document is a generic (non HTML/XHTML) XML document
tidy_load_config -- Load an ASCII Tidy configuration file with the specified encoding
tidy_node->get_attr -- Return the attribute with the provided attribute id
tidy_node->get_nodes -- Return an array of nodes under this node with the specified id
tidy_node->next -- Returns the next sibling to this node
tidy_node->prev -- Returns the previous sibling to this node
tidy_parse_file -- Parse markup in file or URI
tidy_parse_string -- Parse a document stored in a string
tidy_repair_file -- Repair a file and return it as a string
tidy_repair_string -- Repair a string using an optionally provided configuration file
tidy_reset_config -- Restore Tidy configuration to default values
tidy_save_config -- Save current settings to named file
tidy_set_encoding -- Set the input/output character encoding for parsing markup
tidy_setopt -- Updates the configuration settings for the specified tidy document
tidy_warning_count -- Returns the Number of Tidy warnings encountered for specified document
tidyNode->hasChildren -- Returns true if this node has children
tidyNode->hasSiblings -- Returns true if this node has siblings
tidyNode->isAsp -- Returns true if this node is ASP
tidyNode->isComment -- Returns true if this node represents a comment
tidyNode->isHtml -- Returns true if this node is part of a HTML document
tidyNode->isJste -- Returns true if this node is JSTE
tidyNode->isPhp -- Returns true if this node is PHP
tidyNode->isText -- Returns true if this node represents text (no markup)
tidyNode::getParent -- returns the parent node of the current node

Prev | Home | Next
tcpwrap_check | Up | ob_tidyhandler


ob_tidyhandler

(PHP 5)

ob_tidyhandler -- ob_start callback function to repair the buffer

Description

string ob_tidyhandler ( string input [, int mode] )

ob_tidyhandler() is intended to be used as a callback function for ob_start() to repair the buffer.

Example 1. ob_tidyhandler() example

&#60;?php
ob_start('ob_tidyhandler');

echo '&#60;p&#62;test&#60;/i&#62;';
?&#62;

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See also ob_start().

Prev | Home | Next
Tidy Functions | Up | tidy_access_count


tidy_access_count

(PHP 5)

tidy_access_count -- Returns the Number of Tidy accessibility warnings encountered for specified document

Description

int tidy_access_count ( tidy object )

tidy_access_count() returns the number of accessibility warnings found for the specified document.

Note: Due to the design of the TidyLib, you must call tidy_diagnose() before tidy_access_count() or it will return always 0. You must also need to enable the accessibility-check option.

Example 1. tidy_access_count() example

&#60;?php

$html ='&#60;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"&#62;
&#60;html&#62;&#60;head&#62;&#60;title&#62;Title&#60;/title&#62;&#60;/head&#62;
&#60;body&#62;

&#60;p&#62;&#60;img src="img.png"&#62;&#60;/p&#62;

&#60;/body&#62;&#60;/html&#62;';

// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' =&#62; 3);

$tidy = new tidy();
$tidy-&#62;parseString($html, $config);
$tidy-&#62;CleanRepair();

/* Never forget to call this! */
$tidy-&#62;diagnose();

echo tidy_access_count($tidy); //5

?&#62;

See also tidy_error_count() and tidy_warning_count().

Prev | Home | Next
ob_tidyhandler | Up | tidy_clean_repair


tidy_clean_repair

(PHP 5)

tidy_clean_repair -- Execute configured cleanup and repair operations on parsed markup

Description

Procedural style:

bool tidy_clean_repair ( tidy object )

Object oriented style:

bool tidy->cleanRepair ( void )

This function cleans and repairs the given tidy object.

Example 1. tidy_clean_repair() example

&#60;?php
$html = '&#60;p&#62;test&#60;/I&#62;';

$tidy = tidy_parse_string($html);
tidy_clean_repair($tidy);

echo $tidy;
?&#62;

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See also tidy_repair_file() and tidy_repair_string().

Prev | Home | Next
tidy_access_count | Up | tidy_config_count


tidy_config_count

(PHP 5)

tidy_config_count -- Returns the Number of Tidy configuration errors encountered for specified document

Description

int tidy_config_count ( tidy object )

tidy_config_count() returns the number of errors encountered in the configuration of the specified tidy object.

Example 1. tidy_config_count() example

&#60;?php
$html = '&#60;p&#62;test&#60;/I&#62;';

$config = array('doctype' =&#62; 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?&#62;

Prev | Home | Next
tidy_clean_repair | Up | tidy::__construct


tidy::__construct

(no version information, might be only in CVS)

tidy::__construct -- Constructs a new tidy object

Description

tidy tidy::__construct ( [string filename [, mixed config [, string encoding [, bool use_include_path]]]] )

tidy::__construct() constructs a new tidy object.

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

The config parameter can be passed either as an array or as a string. If you pass it as a string, it means the name of the configuration file, otherwise it is interpreted as the options themselves. Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis.

Example 1. tidy::__construct() example

&#60;?php

$html = &#60;&#60;&#60; HTML

&#60;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&#62;

&#60;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&#62;
&#60;head&#62;&#60;title&#62;title&#60;/title&#62;&#60;/head&#62;
&#60;body&#62;
&#60;p&#62;paragraph &#60;bt /&#62;
text&#60;/p&#62;
&#60;/body&#62;&#60;/html&#62;

HTML;

$tidy = new tidy;
$tidy-&#62;parseString($html);

$tidy-&#62;CleanRepair();

if ($tidy-&#62;errorBuffer) {
    echo "The following errors were detected:\n";
    echo $tidy-&#62;errorBuffer;
}

?&#62;

The above example will output:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

See also tidy_parse_file() and tidy_parse_string().

Prev | Home | Next
tidy_config_count | Up | tidy_diagnose


tidy_diagnose

(PHP 5)

tidy_diagnose -- Run configured diagnostics on parsed and repaired markup

Description

Procedural style:

bool tidy_diagnose ( tidy object )

Object oriented style:

bool tidy->diagnose ( void )

tidy_diagnose() runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Returns TRUE on success or FALSE on failure.

Example 1. tidy_diagnose() example

&#60;?php

$html = &#60;&#60;&#60; HTML
&#60;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&#62;

&#60;p&#62;paragraph&#60;/p&#62;
HTML;

$tidy = tidy_parse_string($html);
$tidy-&#62;CleanRepair();

// note the difference between the two outputs
echo tidy_get_error_buffer($tidy) . "\n";

$tidy-&#62;diagnose();
echo tidy_get_error_buffer($tidy);

?&#62;

The above example will output:

line 5 column 1 - Warning: <p> isn't allowed in <head> elements
line 5 column 1 - Warning: inserting missing 'title' element

line 5 column 1 - Warning: <p> isn't allowed in <head> elements
line 5 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

See also tidy_get_error_buffer().

Prev | Home | Next
tidy::__construct | Up | tidy_error_count


tidy_error_count

(PHP 5)

tidy_error_count -- Returns the Number of Tidy errors encountered for specified document

Description

int tidy_error_count ( tidy object )

tidy_error_count() returns the number of Tidy errors encountered for the specified document.

Example 1. tidy_error_count() example

&#60;?php
$html = '&#60;p&#62;test&#60;/i&#62;
&#60;bogustag&#62;bogus&#60;/bogustag&#62;';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy-&#62;errorBuffer;
?&#62;

The above example will output:

1
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 8 - Warning: discarding unexpected </i>
line 2 column 1 - Error: <bogustag> is not recognized!
line 2 column 1 - Warning: discarding unexpected <bogustag>
line 2 column 16 - Warning: discarding unexpected </bogustag>
line 1 column 1 - Warning: inserting missing 'title' element

See also tidy_access_count() and tidy_warning_count().

Prev | Home | Next
tidy_diagnose | Up | tidy_get_body


tidy_get_body

(PHP 5)

tidy_get_body -- Returns a tidyNode Object starting from the <body> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_body ( tidy object )

Object oriented style:

tidyNode tidy->body ( void )

This function returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Example 1. tidy_get_body() example

&#60;?php
$html = '
&#60;html&#62;
  &#60;head&#62;
    &#60;title&#62;test&#60;/title&#62;
  &#60;/head&#62;
  &#60;body&#62;
    &#60;p&#62;paragraph&#60;/p&#62;
  &#60;/body&#62;
&#60;/html&#62;';

$tidy = tidy_parse_string($html);

$body = tidy_get_body($tidy);
echo $body-&#62;value;
?&#62;

The above example will output:

<body>
<p>paragraph</p>
</body>

Note: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_head() and tidy_get_html().

Prev | Home | Next
tidy_error_count | Up | tidy_get_config


tidy_get_config

(PHP 5)

tidy_get_config -- Get current Tidy configuration

Description

Procedural style:

array tidy_get_config ( tidy object )

Object oriented style:

array tidy->getConfig ( void )

tidy_get_config() returns an array with the configuration options in use by the given tidy object.

For an explanation about each option, visit http://tidy.sourceforge.net/docs/quickref.html.

Example 1. tidy_get_config() example

&#60;?php
$html = '&#60;p&#62;test&#60;/p&#62;';
$config = array('indent' =&#62; TRUE,
                'output-xhtml' =&#62; TRUE,
                'wrap' =&#62; 200);

$tidy = tidy_parse_string($html, $config);

print_r(tidy_get_config($tidy));
?&#62;

The above example will output:

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] =>
    [repeated-attributes] => 1
    [alt-text] =>
    [slide-style] =>
    [error-file] =>
    [output-file] =>
    [write-back] =>
    [markup] => 1
    [show-warnings] => 1
    [quiet] =>
    [indent] => 1
    [hide-endtags] =>
    [input-xml] =>
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] =>
    [add-xml-decl] =>
    [uppercase-tags] =>
    [uppercase-attributes] =>
    [bare] =>
    [clean] =>
    [logical-emphasis] =>
    [drop-proprietary-attributes] =>
    [drop-font-tags] =>
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] =>
    [split] =>
    [numeric-entities] =>
    [quote-marks] =>
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] =>
    [wrap-script-literals] =>
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] =>
    [assume-xml-procins] =>
    [add-xml-space] =>
    [enclose-text] =>
    [enclose-block-text] =>
    [keep-time] =>
    [word-2000] =>
    [tidy-mark] =>
    [gnu-emacs] =>
    [gnu-emacs-file] =>
    [literal-attributes] =>
    [show-body-only] =>
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] =>
    [indent-cdata] =>
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] =>
    [join-styles] => 1
    [escape-cdata] =>
    [language] =>
    [ncr] => 1
    [output-bom] => 2
    [replace-color] =>
    [css-prefix] =>
    [new-inline-tags] =>
    [new-blocklevel-tags] =>
    [new-empty-tags] =>
    [new-pre-tags] =>
    [accessibility-check] => 0
    [vertical-space] =>
    [punctuation-wrap] =>
    [merge-divs] => 1
)

See also tidy_reset_config() and tidy_save_config().

Prev | Home | Next
tidy_get_body | Up | tidy_get_error_buffer


tidy_get_error_buffer

(PHP 5)

tidy_get_error_buffer -- Return warnings and errors which occurred parsing the specified document

Description

Procedural style:

string tidy_get_error_buffer ( tidy object )

Object oriented style (property):

class tidy {

string errorBuffer

}

tidy_get_error_buffer() returns warnings and errors which occurred parsing the specified document.

Example 1. tidy_get_error_buffer() example

&#60;?php
$html = '&#60;p&#62;paragraph&#60;/p&#62;';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy-&#62;errorBuffer;
?&#62;

The above example will output:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

See also tidy_access_count(),
tidy_error_count() and
tidy_warning_count().

Prev | Home | Next
tidy_get_config | Up | tidy_get_head


tidy_get_head

(PHP 5)

tidy_get_head -- Returns a tidyNode Object starting from the <head> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_head ( tidy object )

Object oriented style:

tidyNode tidy->head ( void )

This function returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Example 1. tidy_get_head() example

&#60;?php
$html = '
&#60;html&#62;
  &#60;head&#62;
    &#60;title&#62;test&#60;/title&#62;
  &#60;/head&#62;
  &#60;body&#62;
    &#60;p&#62;paragraph&#60;/p&#62;
  &#60;/body&#62;
&#60;/html&#62;';

$tidy = tidy_parse_string($html);

$head = tidy_get_head($tidy);
echo $head-&#62;value;
?&#62;

The above example will output:

<head>
<title>test</title>
</head>

Note: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_html().

Prev | Home | Next
tidy_get_error_buffer | Up | tidy_get_html_ver


tidy_get_html_ver

(PHP 5)

tidy_get_html_ver -- Get the Detected HTML version for the specified document

Description

Procedural style:

int tidy_get_html_ver ( tidy object )

Object oriented style:

int tidy->getHtmlVer ( void )

tidy_get_html_ver() returns the detected HTML version for the specified tidy object.

Warning

This function is not yet implemented in the Tidylib itself, so it always return 0.

Prev | Home | Next
tidy_get_head | Up | tidy_get_html


tidy_get_html

(PHP 5)

tidy_get_html -- Returns a tidyNode Object starting from the <html> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_html ( tidy object )

Object oriented style:

tidyNode tidy->html ( void )

This function returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Example 1. tidy_get_html() example

&#60;?php
$html = '
&#60;html&#62;
  &#60;head&#62;
    &#60;title&#62;test&#60;/title&#62;
  &#60;/head&#62;
  &#60;body&#62;
    &#60;p&#62;paragraph&#60;/p&#62;
  &#60;/body&#62;
&#60;/html&#62;';

$tidy = tidy_parse_string($html);

$html = tidy_get_html($tidy);
echo $html-&#62;value;
?&#62;

The above example will output:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Note: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_head().

Prev | Home | Next
tidy_get_html_ver | Up | tidy_get_opt_doc


tidy_get_output

(PHP 5)

tidy_get_output -- Return a string representing the parsed tidy markup

Description

string tidy_get_output ( tidy object )

tidy_get_output() returns a string with the repaired html.

Example 1. tidy_get_output() example

&#60;?php

$html = '&#60;p&#62;paragraph&#60;/i&#62;';
$tidy = tidy_parse_string($html);

$tidy-&#62;CleanRepair();

echo tidy_get_output($tidy);
?&#62;

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Prev | Home | Next
tidy_get_opt_doc | Up | tidy_get_release


tidy_get_release

(PHP 5)

tidy_get_release -- Get release date (version) for Tidy library

Description

Procedural style:

string tidy_get_release ( void )

Object oriented style:

string tidy->getRelease ( void )

This function returns a string with the release date of the Tidy library.

Prev | Home | Next
tidy_get_output | Up | tidy_get_root


tidy_get_root

(PHP 5)

tidy_get_root -- Returns a tidyNode object representing the root of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_root ( tidy object )

Object oriented style:

tidyNode tidy->root ( void )

Returns a tidyNode object representing the root of the tidy parse tree.

Example 1. dump nodes

&#60;?php

$html = &#60;&#60;&#60; HTML
&#60;html&#62;&#60;body&#62;

&#60;p&#62;paragraph&#60;/p&#62;
&#60;br/&#62;

&#60;/body&#62;&#60;/html&#62;
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy-&#62;root(), 1);

function dump_nodes($node, $indent) {

    if($node-&#62;hasChildren()) {
        foreach($node-&#62;child as $child) {
            echo str_repeat('.', $indent*2) . ($child-&#62;name ? $child-&#62;name : '"'.$child-&#62;value.'"'). "\n";

            dump_nodes($child, $indent+1);
        }
    }
}
?&#62;

The above example will output:

..html
....head
......title
....body
......p
........"paragraph"
......br

Note: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

Prev | Home | Next
tidy_get_release | Up | tidy_get_status


tidy_get_status

(PHP 5)

tidy_get_status -- Get status of specified document

Description

Procedural style:

int tidy_get_status ( tidy object )

Object oriented style:

int tidy->getStatus ( void )

tidy_get_status() returns the status for the specified tidy object. It returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Example 1. tidy_get_status() example

&#60;?php
$html = '&#60;p&#62;paragraph&#60;/i&#62;';
$tidy = tidy_parse_string($html);

$html2 = '&#60;bogus&#62;test&#60;/bogus&#62;';
$tidy2 = tidy_parse_string($html2);

echo tidy_get_status($tidy); //1

echo tidy_get_status($tidy2); //2
?&#62;

Prev | Home | Next
tidy_get_root | Up | tidy_getopt


tidy_getopt

(PHP 5)

tidy_getopt -- Returns the value of the specified configuration option for the tidy document

Description

Procedural style:

mixed tidy_getopt ( tidy object, string option )

Object oriented style:

mixed tidy->getOpt ( string option )

tidy_getopt() returns the value of the specified option for the specified tidy object. The return type depends on the type of the specified option. You will find a list with each configuration option and their types at: http://tidy.sourceforge.net/docs/quickref.html.

Example 1. tidy_getopt() example

&#60;?php

$html ='&#60;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"&#62;
&#60;html&#62;&#60;head&#62;&#60;title&#62;Title&#60;/title&#62;&#60;/head&#62;
&#60;body&#62;

&#60;p&#62;&#60;img src="img.png"&#62;&#60;/p&#62;

&#60;/body&#62;&#60;/html&#62;';

$config = array('accessibility-check' =&#62; 3,
                'alt-text' =&#62; 'some text');

$tidy = new tidy();
$tidy-&#62;parseString($html, $config);

var_dump($tidy-&#62;getOpt('accessibility-check')); //integer
var_dump($tidy-&#62;getOpt('lower-literals')); //boolean
var_dump($tidy-&#62;getOpt('alt-text')); //string

?&#62;

The above example will output:

int(3)
bool(true)
string(9) "some text"

Prev | Home | Next
tidy_get_status | Up | tidy_is_xhtml


tidy_is_xhtml

(PHP 5)

tidy_is_xhtml -- Indicates if the document is a XHTML document

Description

Procedural style:

bool tidy_is_xhtml ( tidy object )

Object oriented style:

bool tidy->isXhtml ( void )

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

Prev | Home | Next
tidy_getopt | Up | tidy_is_xml


tidy_is_xml

(PHP 5)

tidy_is_xml -- Indicates if the document is a generic (non HTML/XHTML) XML document

Description

Procedural style:

bool tidy_is_xml ( tidy object )

Object oriented style:

bool tidy->isXml ( void )

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

Prev | Home | Next
tidy_is_xhtml | Up | tidy_load_config


tidy_load_config

(no version information, might be only in CVS)

tidy_load_config -- Load an ASCII Tidy configuration file with the specified encoding

Description

void tidy_load_config ( string filename, string encoding )

This function loads a Tidy configuration file, with the specified encoding.

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

Prev | Home | Next
tidy_is_xml | Up | tidy_node->get_attr


tidy_node->get_attr

(no version information, might be only in CVS)

tidy_node->get_attr -- Return the attribute with the provided attribute id

Description

tidy_attr tidy_node->get_attr ( int attrib_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
tidy_load_config | Up | tidy_node->get_nodes


tidy_node->get_nodes

(no version information, might be only in CVS)

tidy_node->get_nodes -- Return an array of nodes under this node with the specified id

Description

array tidy_node->get_nodes ( int node_id )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
tidy_node->get_attr | Up | tidy_node->next


tidy_node->next

(no version information, might be only in CVS)

tidy_node->next -- Returns the next sibling to this node

Description

tidy_node tidy_node->next ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
tidy_node->get_nodes | Up | tidy_node->prev


tidy_node->prev

(no version information, might be only in CVS)

tidy_node->prev -- Returns the previous sibling to this node

Description

tidy_node tidy_node->prev ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
tidy_node->next | Up | tidy_parse_file


tidy_parse_file

(PHP 5)

tidy_parse_file -- Parse markup in file or URI

Description

Procedural style:

tidy tidy_parse_file ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

Object oriented style:

bool tidy->parseFile ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

This function parses the given file.

The config parameter can be passed either as an array or as a string. If you pass it as a string, it means the name of the configuration file, otherwise it is interpreted as the options themselves. Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis.

Example 1. tidy_parse_file() example

&#60;?php
$tidy = tidy_parse_file('file.html');

$tidy-&#62;cleanRepair();

if(!empty($tidy-&#62;errorBuffer)) {
    echo "The following errors or warnings occured:\n";
    echo $tidy-&#62;errorBuffer;
}
?&#62;

Note: The optional parameters config and encoding were added in Tidy 2.0.

See also tidy_parse_string(),
tidy_repair_file() and
tidy_repair_string().

Prev | Home | Next
tidy_node->prev | Up | tidy_parse_string


tidy_parse_string

(PHP 5)

tidy_parse_string -- Parse a document stored in a string

Description

Procedural style:

tidy tidy_parse_string ( string input [, mixed config [, string encoding]] )

Object oriented style:

bool tidy->parseString ( string input [, mixed config [, string encoding]] )

tidy_parse_string() parses a document stored in a string.

The config parameter can be passed either as an array or as a string. If you pass it as a string, it means the name of the configuration file, otherwise it is interpreted as the options themselves. Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis.

Example 1. tidy_parse_string() example

&#60;?php
ob_start();
?&#62;

&#60;html&#62;
  &#60;head&#62;
   &#60;title&#62;test&#60;/title&#62;
  &#60;/head&#62;
  &#60;body&#62;
   &#60;p&#62;error&#60;br&#62;another line&#60;/i&#62;
  &#60;/body&#62;
&#60;/html&#62;

&#60;?php

$buffer = ob_get_clean();
$config = array('indent' =&#62; TRUE,
                'output-xhtml' =&#62; TRUE,
                'wrap' =&#62; 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy-&#62;cleanRepair();
echo $tidy;
?&#62;

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

Note: The optional parameters config and encoding were added in Tidy 2.0.

See also tidy_parse_file(),
tidy_repair_file() and
tidy_repair_string().

Prev | Home | Next
tidy_parse_file | Up | tidy_repair_file


tidy_repair_file

(PHP 5)

tidy_repair_file -- Repair a file and return it as a string

Description

string tidy_repair_file ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

This function repairs the given file and returns it as a string.

The config parameter can be passed either as an array or as a string. If you pass it as a string, it means the name of the configuration file, otherwise it is interpreted as the options themselves. Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis.

Example 1. tidy_repair_file() example

&#60;?php
$file = 'file.html';

$repaired = tidy_repair_file($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?&#62;

Note: The optional parameters config and encoding were added in Tidy 2.0.

See also tidy_parse_file(),
tidy_parse_string() and
tidy_repair_string().

Prev | Home | Next
tidy_parse_string | Up | tidy_repair_string


tidy_repair_string

(PHP 5)

tidy_repair_string -- Repair a string using an optionally provided configuration file

Description

string tidy_repair_string ( string data [, mixed config [, string encoding]] )

This function repairs the given string.

The config parameter can be passed either as an array or as a string. If you pass it as a string, it means the name of the configuration file, otherwise it is interpreted as the options themselves. Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis.

Example 1. tidy_repair_string() example

&#60;?php
ob_start();
?&#62;

&#60;html&#62;
  &#60;head&#62;
    &#60;title&#62;test&#60;/title&#62;
  &#60;/head&#62;
  &#60;body&#62;
    &#60;p&#62;error&#60;/i&#62;
  &#60;/body&#62;
&#60;/html&#62;

&#60;?php

$buffer = ob_get_clean();
$tidy = tidy_repair_string($buffer);

echo $tidy;
?&#62;

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

Note: The optional parameters config and encoding were added in Tidy 2.0.

See also tidy_parse_file(),
tidy_parse_string() and
tidy_repair_file().

Prev | Home | Next
tidy_repair_file | Up | tidy_reset_config


tidy_reset_config

(no version information, might be only in CVS)

tidy_reset_config -- Restore Tidy configuration to default values

Description

bool tidy_reset_config ( void )

This function restores the Tidy configuration to the default values.

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

Prev | Home | Next
tidy_repair_string | Up | tidy_save_config


tidy_save_config

(no version information, might be only in CVS)

tidy_save_config -- Save current settings to named file

Description

bool tidy_save_config ( string filename )

tidy_save_config() saves current settings to the specified file. Only non-default values are written.

See also tidy_get_config(),
tidy_getopt(),
tidy_reset_config() and
tidy_setopt().

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

Prev | Home | Next
tidy_reset_config | Up | tidy_set_encoding


tidy_set_encoding

(no version information, might be only in CVS)

tidy_set_encoding -- Set the input/output character encoding for parsing markup

Description

bool tidy_set_encoding ( string encoding )

Sets the encoding for input/output documents. Returns TRUE on success or FALSE on failure. Possible values for encoding are ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

Prev | Home | Next
tidy_save_config | Up | tidy_setopt


tidy_setopt

(no version information, might be only in CVS)

tidy_setopt -- Updates the configuration settings for the specified tidy document

Description

bool tidy_setopt ( string option, mixed value )

tidy_setopt() updates the specified option with a new value. You will find a list with each configuration option at: http://tidy.sourceforge.net/docs/quickref.html.

Example 1. tidy_setopt() example

&#60;?php
$html = '&#60;p&#62;test&#60;/i&#62;';

$tidy = tidy_parse_string($html);

tidy_setopt('indent', FALSE);
?&#62;

See also tidy_getopt(),
tidy_get_config(),
tidy_reset_config() and
tidy_save_config().

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

Prev | Home | Next
tidy_set_encoding | Up | tidy_warning_count


tidy_warning_count

(PHP 5)

tidy_warning_count -- Returns the Number of Tidy warnings encountered for specified document

Description

int tidy_warning_count ( tidy object )

tidy_warning_count() returns the number of Tidy warnings encountered for the specified document.

Example 1. tidy_warning_count() example

&#60;?php
$html = '&#60;p&#62;test&#60;/i&#62;
&#60;bogustag&#62;bogus&#60;/bogustag&#62;';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?&#62;

See also tidy_access_count() and tidy_error_count().

Prev | Home | Next
tidy_setopt | Up | tidyNode->hasChildren


tidyNode->hasChildren

(no version information, might be only in CVS)

tidyNode->hasChildren -- Returns true if this node has children

Description

bool tidyNode->hasChildren ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->has_children() in PHP 4/Tidy 1.

Prev | Home | Next
tidy_warning_count | Up | tidyNode->hasSiblings


tidyNode->hasSiblings

(no version information, might be only in CVS)

tidyNode->hasSiblings -- Returns true if this node has siblings

Description

bool tidyNode->hasSiblings ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->has_siblings() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->hasChildren | Up | tidyNode->isAsp


tidyNode->isAsp

(no version information, might be only in CVS)

tidyNode->isAsp -- Returns true if this node is ASP

Description

bool tidyNode->isAsp ( void )

This functions returns TRUE if the current node is ASP, or FALSE otherwise.

Note: This function was named tidy_node->is_asp() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->hasSiblings | Up | tidyNode->isComment


tidyNode->isComment

(no version information, might be only in CVS)

tidyNode->isComment -- Returns true if this node represents a comment

Description

bool tidyNode->isComment ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->is_comment() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->isAsp | Up | tidyNode->isHtml


tidyNode->isHtml

(no version information, might be only in CVS)

tidyNode->isHtml -- Returns true if this node is part of a HTML document

Description

bool tidyNode->isHtml ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->is_html() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->isComment | Up | tidyNode->isJste


tidyNode->isJste

(no version information, might be only in CVS)

tidyNode->isJste -- Returns true if this node is JSTE

Description

bool tidyNode->isJste ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->is_jste() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->isHtml | Up | tidyNode->isPhp


tidyNode->isPhp

(no version information, might be only in CVS)

tidyNode->isPhp -- Returns true if this node is PHP

Description

bool tidyNode->isPhp ( void )

Returns TRUE if the current node is PHP code, FALSE otherwise.

Example 1. get the PHP code from a mixed HTML/PHP document

&#60;?php

$html = &#60;&#60;&#60; HTML
&#60;html&#62;&#60;head&#62;
&#60;?php echo '&#60;title&#62;title&#60;/title&#62;'; ?&#62;
&#60;/head&#62;
&#60;body&#62;

&#60;?php
echo 'hello world!';
?&#62;

&#60;/body&#62;&#60;/html&#62;
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_php($tidy-&#62;html());

function get_php($node) {

    // check if the current node is PHP code
    if($node-&#62;isPhp()) {
        echo "\n\n# PHP node #" . ++$GLOBALS['num'] . "\n";
        echo $node-&#62;value;
    }

    // check if the current node has childrens
    if($node-&#62;hasChildren()) {
        foreach($node-&#62;child as $child) {
            get_php($child);
        }
    }
}

?&#62;

The above example will output:

# PHP node #1
<?php echo '<title>title</title>'; ?>

# PHP node #2
<?php
echo 'hello world!';
?>

Note: This function was named tidy_node->is_php() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->isJste | Up | tidyNode->isText


tidyNode->isText

(no version information, might be only in CVS)

tidyNode->isText -- Returns true if this node represents text (no markup)

Description

bool tidyNode->isText ( void )

Warning

This function is currently not documented; only the argument list is available.

Note: This function was named tidy_node->is_text() in PHP 4/Tidy 1.

Prev | Home | Next
tidyNode->isPhp | Up | tidyNode::getParent


Tokenizer Functions

PHP Manual
Prev Next

CLXV. Tokenizer Functions

Introduction

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzing or modification tools without having to deal with the language specification at the lexical level.

See also the appendix about tokens.

Requirements

No external libraries are needed to build this extension.

Installation

Beginning with PHP 4.3.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-tokenizer. You can disable tokenizer support with --disable-tokenizer.

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 tokenizer is available with PHP 4.3.0.

Predefined Constants

When the extension has either been compiled into PHP or dynamically loaded at runtime, the tokens listed in Appendix Q are defined as constants.

Examples

Here is a simple example PHP scripts using the tokenizer that will read in a PHP file, strip all comments from the source and print the pure code only.

Example 1. Strip comments with the tokenizer

&#60;?php
/*
 * T_ML_COMMENT does not exist in PHP 5.
 * The following three lines define it in order to
 * preserve backwards compatibility.
 *
 * The next two lines define the PHP 5 only T_DOC_COMMENT,
 * which we will mask as T_ML_COMMENT for PHP 4.
 */
if (!defined('T_ML_COMMENT')) {
    define('T_ML_COMMENT', T_COMMENT);
} else {
    define('T_DOC_COMMENT', T_ML_COMMENT);
}

$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach ($tokens as $token) {
    if (is_string($token)) {
        // simple 1-character token
        echo $token;
    } else {
        // token array
        list($id, $text) = $token;

        switch ($id) {
            case T_COMMENT:
            case T_ML_COMMENT: // we've defined this
            case T_DOC_COMMENT: // and this
                // no action on comments
                break;

            default:
                // anything else -&#62; output "as is"
                echo $text;
                break;
        }
    }
}
?&#62;
Table of Contents
token_get_all -- Split given source into PHP tokens
token_name -- Get the symbolic name of a given PHP token

Prev | Home | Next
tidyNode::getParent | Up | token_get_all


token_get_all

(PHP 4 >= 4.2.0, PHP 5)

token_get_all -- Split given source into PHP tokens

Description

array token_get_all ( string source )

token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner.

For a list of parser tokens, see Appendix Q, or use token_name() to translate a token value into its string representation.

Parameters

source

The PHP source to parse.

Return Values

An array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a two element array containing the token index in element 0, and the string content of the original token in element 1.

Examples

Example 1. token_get_all() examples

&#60;?php
$tokens = token_get_all('&#60;?php echo; ?&#62;'); /* =&#62; array(
                                                  array(T_OPEN_TAG, '&#60;?php'),
                                                  array(T_ECHO, 'echo'),
                                                  ';',
                                                  array(T_CLOSE_TAG, '?&#62;') ); */

/* Note in the following example that the string is parsed as T_INLINE_HTML
   rather than the otherwise expected T_COMMENT (T_ML_COMMENT in PHP &#60;5).
   This is because no open/close tags were used in the "code" provided.
   This would be equivalent to putting a comment outside of &#60;?php ?&#62; tags in a normal file. */
$tokens = token_get_all('/* comment */'); // =&#62; array(array(T_INLINE_HTML, '/* comment */'));
?&#62;

Prev | Home | Next
Tokenizer Functions | Up | token_name


token_name

(PHP 4 >= 4.2.0, PHP 5)

token_name -- Get the symbolic name of a given PHP token

Description

string token_name ( int token )

token_name() gets the symbolic name for a PHP token value.

Parameters

token

The token value.

Return Values

The symbolic name of the given token. The returned name returned matches the name of the matching token constant.

Examples

Example 1. token_name() example

&#60;?php
// 260 is the token value for the T_REQUIRE token
echo token_name(260);        // -&#62; "T_REQUIRE"

// a token constant maps to its own name
echo token_name(T_FUNCTION); // -&#62; "T_FUNCTION"
?&#62;

See Also

List of Parser Tokens

Prev | Home | Next
token_get_all | Up | Unicode Functions


ODBC Functions (Unified)

PHP Manual
Prev Next

CVI. ODBC Functions (Unified)

Introduction

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: Adabas D, IBM DB2, iODBC, Solid, and Sybase SQL Anywhere.

Note: There is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. The exception to this is iODBC. Building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. iODBC is maintained by OpenLink Software. More information on iODBC, as well as a HOWTO, is available at www.iodbc.org.

Requirements

To access any of the supported databases you need to have the required libraries installed.

Installation

--with-adabas[=DIR]

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

--with-sapdb[=DIR]

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

--with-solid[=DIR]

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

--with-ibm-db2[=DIR]

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

--with-empress[=DIR]

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

--with-empress-bcs[=DIR]

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

--with-birdstep[=DIR]

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

--with-custom-odbc[=DIR]

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

--with-iodbc[=DIR]

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

--with-esoob[=DIR]

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

--with-unixODBC[=DIR]

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

--with-openlink[=DIR]

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

--with-dbmaker[=DIR]

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

To disable unified ODBC support in PHP 3 add --disable-unified-odbc to your configure line. Only applicable if iODBC, Adabas, Solid, Velocis or a custom ODBC interface is enabled.

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. Unified ODBC Configuration Options

Name | Default | Changeable | Changelog
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |

Note: Entries marked with * are not implemented yet.

For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

odbc.default_db string

ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_user string

User name to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_pw string

Password to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

odbc.defaultbinmode integer

Handling of binary data.

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.

ODBC_TYPE (integer)

ODBC_BINMODE_PASSTHRU (integer)

ODBC_BINMODE_RETURN (integer)

ODBC_BINMODE_CONVERT (integer)

SQL_ODBC_CURSORS (integer)

SQL_CUR_USE_DRIVER (integer)

SQL_CUR_USE_IF_NEEDED (integer)

SQL_CUR_USE_ODBC (integer)

SQL_CONCURRENCY (integer)

SQL_CONCUR_READ_ONLY (integer)

SQL_CONCUR_LOCK (integer)

SQL_CONCUR_ROWVER (integer)

SQL_CONCUR_VALUES (integer)

SQL_CURSOR_TYPE (integer)

SQL_CURSOR_FORWARD_ONLY (integer)

SQL_CURSOR_KEYSET_DRIVEN (integer)

SQL_CURSOR_DYNAMIC (integer)

SQL_CURSOR_STATIC (integer)

SQL_KEYSET_SIZE (integer)

SQL_CHAR (integer)

SQL_VARCHAR (integer)

SQL_LONGVARCHAR (integer)

SQL_DECIMAL (integer)

SQL_NUMERIC (integer)

SQL_BIT (integer)

SQL_TINYINT (integer)

SQL_SMALLINT (integer)

SQL_INTEGER (integer)

SQL_BIGINT (integer)

SQL_REAL (integer)

SQL_FLOAT (integer)

SQL_DOUBLE (integer)

SQL_BINARY (integer)

SQL_VARBINARY (integer)

SQL_LONGVARBINARY (integer)

SQL_DATE (integer)

SQL_TIME (integer)

SQL_TIMESTAMP (integer)

SQL_TYPE_DATE (integer)

SQL_TYPE_TIME (integer)

SQL_TYPE_TIMESTAMP (integer)

SQL_BEST_ROWID (integer)

SQL_ROWVER (integer)

SQL_SCOPE_CURROW (integer)

SQL_SCOPE_TRANSACTION (integer)

SQL_SCOPE_SESSION (integer)

SQL_NO_NULLS (integer)

SQL_NULLABLE (integer)

SQL_INDEX_UNIQUE (integer)

SQL_INDEX_ALL (integer)

SQL_ENSURE (integer)

SQL_QUICK (integer)

Table of Contents
odbc_autocommit -- Toggle autocommit behaviour
odbc_binmode -- Handling of binary column data
odbc_close_all -- Close all ODBC connections
odbc_close -- Close an ODBC connection
odbc_columnprivileges -- Returns a result identifier that can be used to fetch a list of columns and associated privileges
odbc_columns -- Lists the column names in specified tables
odbc_commit -- Commit an ODBC transaction
odbc_connect -- Connect to a datasource
odbc_cursor -- Get cursorname
odbc_data_source -- Returns information about a current connection
odbc_do -- Synonym for odbc_exec()
odbc_error -- Get the last error code
odbc_errormsg -- Get the last error message
odbc_exec -- Prepare and execute a SQL statement
odbc_execute -- Execute a prepared statement
odbc_fetch_array -- Fetch a result row as an associative array
odbc_fetch_into -- Fetch one result row into array
odbc_fetch_object -- Fetch a result row as an object
odbc_fetch_row -- Fetch a row
odbc_field_len -- Get the length (precision) of a field
odbc_field_name -- Get the columnname
odbc_field_num -- Return column number
odbc_field_precision -- Synonym for odbc_field_len()
odbc_field_scale -- Get the scale of a field
odbc_field_type -- Datatype of a field
odbc_foreignkeys -- Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table
odbc_free_result -- Free resources associated with a result
odbc_gettypeinfo -- Returns a result identifier containing information about data types supported by the data source
odbc_longreadlen -- Handling of LONG columns
odbc_next_result -- Checks if multiple results are available
odbc_num_fields -- Number of columns in a result
odbc_num_rows -- Number of rows in a result
odbc_pconnect -- Open a persistent database connection
odbc_prepare -- Prepares a statement for execution
odbc_primarykeys -- Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table
odbc_procedurecolumns -- Retrieve information about parameters to procedures
odbc_procedures -- Get the list of procedures stored in a specific data source
odbc_result_all -- Print result as HTML table
odbc_result -- Get result data
odbc_rollback -- Rollback a transaction
odbc_setoption -- Adjust ODBC settings
odbc_specialcolumns -- Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction
odbc_statistics -- Retrieve statistics about a table
odbc_tableprivileges -- Lists tables and the privileges associated with each table
odbc_tables -- Get the list of table names stored in a specific data source

Prev | Home | Next
ociwritetemporarylob | Up | odbc_autocommit


odbc_autocommit

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_autocommit -- Toggle autocommit behaviour

Description

mixed odbc_autocommit ( resource connection_id [, bool OnOff] )

Without the OnOff parameter, this function returns auto-commit status for connection_id. Non-zero is returned if auto-commit is on, 0 if it is off, or FALSE if an error occurs.

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled. Returns TRUE on success, FALSE on failure.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

See also odbc_commit() and odbc_rollback().

Prev | Home | Next
ODBC Functions (Unified) | Up | odbc_binmode


odbc_binmode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_binmode -- Handling of binary column data

Description

bool odbc_binmode ( resource result_id, int mode )

(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data

  • ODBC_BINMODE_RETURN: Return as is

  • ODBC_BINMODE_CONVERT: Convert to char and return

When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".

Table 1. LONGVARBINARY handling

binmode | longreadlen | result
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_RETURN | 0 | passthru
ODBC_BINMODE_CONVERT | 0 | passthru
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_PASSTHRU | >0 | passthru
ODBC_BINMODE_RETURN | >0 | return as is
ODBC_BINMODE_CONVERT | >0 | return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

If result_id is 0, the settings apply as default for new results.

Note: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()

Prev | Home | Next
odbc_autocommit | Up | odbc_close_all


odbc_close_all

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_close_all -- Close all ODBC connections

Description

void odbc_close_all ( void )

odbc_close_all() will close down all connections to database server(s).

Note: This function will fail if there are open transactions on a connection. This connection will remain open in this case.

Prev | Home | Next
odbc_binmode | Up | odbc_close


odbc_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_close -- Close an ODBC connection

Description

void odbc_close ( resource connection_id )

odbc_close() will close down the connection to the database server associated with the given connection identifier.

Note: This function will fail if there are open transactions on this connection. The connection will remain open in this case.

Prev | Home | Next
odbc_close_all | Up | odbc_columnprivileges


odbc_columnprivileges

(PHP 4, PHP 5)

odbc_columnprivileges -- Returns a result identifier that can be used to fetch a list of columns and associated privileges

Description

resource odbc_columnprivileges ( resource connection_id, string qualifier, string owner, string table_name, string column_name )

Lists columns and associated privileges for the given table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

Prev | Home | Next
odbc_close | Up | odbc_columns


odbc_columns

(PHP 4, PHP 5)

odbc_columns -- Lists the column names in specified tables

Description

resource odbc_columns ( resource connection_id [, string qualifier [, string schema [, string table_name [, string column_name]]]] )

Lists all columns in the requested range. Returns an ODBC result identifier containing the information or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_SCHEM

  • TABLE_NAME

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

The schema, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

See also odbc_columnprivileges() to retrieve associated privileges.

Prev | Home | Next
odbc_columnprivileges | Up | odbc_commit


odbc_commit

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_commit -- Commit an ODBC transaction

Description

bool odbc_commit ( resource connection_id )

odbc_commit() commits all pending transactions on the connection_id connection. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
odbc_columns | Up | odbc_connect


odbc_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_connect -- Connect to a datasource

Description

resource odbc_connect ( string dsn, string user, string password [, int cursor_type] )

Returns an ODBC connection id or 0 (FALSE) on error.

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials. The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED

  • SQL_CUR_USE_ODBC

  • SQL_CUR_USE_DRIVER

  • SQL_CUR_DEFAULT

For persistent connections see odbc_pconnect().

Prev | Home | Next
odbc_commit | Up | odbc_cursor


odbc_cursor

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_cursor -- Get cursorname

Description

string odbc_cursor ( resource result_id )

odbc_cursor will return a cursorname for the given result_id.

Prev | Home | Next
odbc_connect | Up | odbc_data_source


odbc_data_source

(PHP 4 >= 4.3.0, PHP 5)

odbc_data_source -- Returns information about a current connection

Description

array odbc_data_source ( resource connection_id, int fetch_type )

Returns FALSE on error, and an array upon success.

This function will return the list of available DNS (after calling it several times). The connection_id is required to be a valid ODBC connection. The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

Prev | Home | Next
odbc_cursor | Up | odbc_do


odbc_do

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_do -- Synonym for odbc_exec()

Description

resource odbc_do ( resource conn_id, string query )

odbc_do() will execute a query on the given connection.

Prev | Home | Next
odbc_data_source | Up | odbc_error


odbc_error

(PHP 4 >= 4.0.5, PHP 5)

odbc_error -- Get the last error code

Description

string odbc_error ( [resource connection_id] )

Returns a six-digit ODBC state, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

See also: odbc_errormsg() and odbc_exec().

Prev | Home | Next
odbc_do | Up | odbc_errormsg


odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5)

odbc_errormsg -- Get the last error message

Description

string odbc_errormsg ( [resource connection_id] )

Returns a string containing the last ODBC error message, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

See also: odbc_error() and odbc_exec().

Prev | Home | Next
odbc_error | Up | odbc_exec


odbc_exec

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_exec -- Prepare and execute a SQL statement

Description

resource odbc_exec ( resource connection_id, string query_string [, int flags] )

Returns FALSE on error. Returns an ODBC result identifier if the SQL command was executed successfully.

odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().

See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.

Prev | Home | Next
odbc_errormsg | Up | odbc_execute


odbc_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_execute -- Execute a prepared statement

Description

bool odbc_execute ( resource result_id [, array parameters_array] )

Executes a statement prepared with odbc_prepare().Returns TRUE on success or FALSE on failure. The array parameters_array only needs to be given if you really have parameters in your statement.

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function.

Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

Note: As of PHP 4.1.1, this file reading functionality has the following restrictions:

  • File reading is not subject to any safe mode or open-basedir restrictions. This is fixed in PHP 4.2.0.

  • Remote files are not supported.

  • If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

Prev | Home | Next
odbc_exec | Up | odbc_fetch_array


odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_array -- Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource result [, int rownumber] )

Fetch an associative array from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ChangeLog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

odbc_fetch_row()
odbc_fetch_object()
odbc_num_rows()

Prev | Home | Next
odbc_execute | Up | odbc_fetch_into


odbc_fetch_into

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_fetch_into -- Fetch one result row into array

Description

int odbc_fetch_into ( resource result_id, array &result_array [, int rownumber] )

bool odbc_fetch_into ( resource result_id [, int rownumber, array &result_array] )

Returns the number of columns in the result; FALSE on error. result_array must be passed by reference, but it can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

As of PHP 4.0.5 the result_array does not need to be passed by reference any longer.

As of PHP 4.0.6 the rownumber cannot be passed as a constant, but rather as a variable.

As of PHP 4.2.0 the result_array and rownumber have been swapped. This allows the rownumber to be a constant again. This change will also be the last one to this function.

Example 1. odbc_fetch_into() pre 4.0.6 example

&#60;?php
$rc = odbc_fetch_into($res_id, $my_array);
?&#62;

or

&#60;?php
$rc = odbc_fetch_into($res_id, $row, $my_array);

$rc = odbc_fetch_into($res_id, 1, $my_array);
?&#62;

Example 2. odbc_fetch_into() 4.0.6 example

&#60;?php
$rc = odbc_fetch_into($res_id, $my_array);
?&#62;

or

&#60;?php
$row = 1;
$rc = odbc_fetch_into($res_id, $row, $my_array);
?&#62;

Example 3. odbc_fetch_into() 4.2.0 example

&#60;?php
$rc = odbc_fetch_into($res_id, $my_array);
?&#62;

or

&#60;?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?&#62;

Prev | Home | Next
odbc_fetch_array | Up | odbc_fetch_object


odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_object -- Fetch a result row as an object

Description

object odbc_fetch_object ( resource result [, int rownumber] )

Fetch an object from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

ChangeLog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

odbc_fetch_row()
odbc_fetch_array()
odbc_num_rows()

Prev | Home | Next
odbc_fetch_into | Up | odbc_fetch_row


odbc_fetch_row

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_fetch_row -- Fetch a row

Description

bool odbc_fetch_row ( resource result_id [, int row_number] )

If odbc_fetch_row() was successful (there was a row), TRUE is returned. If there are no more rows, FALSE is returned.

odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

Prev | Home | Next
odbc_fetch_object | Up | odbc_field_len


odbc_field_len

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_len -- Get the length (precision) of a field

Description

int odbc_field_len ( resource result_id, int field_number )

odbc_field_len() will return the length of the field referenced by number in the given ODBC result identifier. Field numbering starts at 1.

See also: odbc_field_scale() to get the scale of a floating point number.

Prev | Home | Next
odbc_fetch_row | Up | odbc_field_name


odbc_field_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_name -- Get the columnname

Description

string odbc_field_name ( resource result_id, int field_number )

odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

Prev | Home | Next
odbc_field_len | Up | odbc_field_num


odbc_field_num

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_num -- Return column number

Description

int odbc_field_num ( resource result_id, string field_name )

odbc_field_num() will return the number of the column slot that corresponds to the named field in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

Prev | Home | Next
odbc_field_name | Up | odbc_field_precision


odbc_field_precision

(PHP 4, PHP 5)

odbc_field_precision -- Synonym for odbc_field_len()

Description

int odbc_field_precision ( resource result_id, int field_number )

odbc_field_precision() will return the precision of the field referenced by number in the given ODBC result identifier.

See also: odbc_field_scale() to get the scale of a floating point number.

Prev | Home | Next
odbc_field_num | Up | odbc_field_scale


odbc_field_scale

(PHP 4, PHP 5)

odbc_field_scale -- Get the scale of a field

Description

int odbc_field_scale ( resource result_id, int field_number )

odbc_field_scale() will return the scale of the field referenced by number in the given ODBC result identifier.

Prev | Home | Next
odbc_field_precision | Up | odbc_field_type


odbc_field_type

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_type -- Datatype of a field

Description

string odbc_field_type ( resource result_id, int field_number )

odbc_field_type() will return the SQL type of the field referenced by number in the given ODBC result identifier. Field numbering starts at 1.

Prev | Home | Next
odbc_field_scale | Up | odbc_foreignkeys


odbc_foreignkeys

(PHP 4, PHP 5)

odbc_foreignkeys -- Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Description

resource odbc_foreignkeys ( resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table )

odbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PKTABLE_QUALIFIER

  • PKTABLE_OWNER

  • PKTABLE_NAME

  • PKCOLUMN_NAME

  • FKTABLE_QUALIFIER

  • FKTABLE_OWNER

  • FKTABLE_NAME

  • FKCOLUMN_NAME

  • KEY_SEQ

  • UPDATE_RULE

  • DELETE_RULE

  • FK_NAME

  • PK_NAME

If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.

Prev | Home | Next
odbc_field_type | Up | odbc_free_result


odbc_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_free_result -- Free resources associated with a result

Description

bool odbc_free_result ( resource result_id )

Always returns TRUE.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call odbc_free_result(), and the memory associated with result_id will be freed.

Note: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

Prev | Home | Next
odbc_foreignkeys | Up | odbc_gettypeinfo


odbc_gettypeinfo

(PHP 4, PHP 5)

odbc_gettypeinfo -- Returns a result identifier containing information about data types supported by the data source

Description

resource odbc_gettypeinfo ( resource connection_id [, int data_type] )

Retrieves information about data types supported by the data source. Returns an ODBC result identifier or FALSE on failure. The optional argument data_type can be used to restrict the information to a single data type.

The result set has the following columns:

  • TYPE_NAME

  • DATA_TYPE

  • PRECISION

  • LITERAL_PREFIX

  • LITERAL_SUFFIX

  • CREATE_PARAMS

  • NULLABLE

  • CASE_SENSITIVE

  • SEARCHABLE

  • UNSIGNED_ATTRIBUTE

  • MONEY

  • AUTO_INCREMENT

  • LOCAL_TYPE_NAME

  • MINIMUM_SCALE

  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

Prev | Home | Next
odbc_free_result | Up | odbc_longreadlen


odbc_longreadlen

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_longreadlen -- Handling of LONG columns

Description

bool odbc_longreadlen ( resource result_id, int length )

(ODBC SQL types affected: LONG, LONGVARBINARY) The number of bytes returned to PHP is controlled by the parameter length. If it is set to 0, Long column data is passed through to the client.

Note: Handling of LONGVARBINARY columns is also affected by odbc_binmode().

Prev | Home | Next
odbc_gettypeinfo | Up | odbc_next_result


odbc_next_result

(PHP 4 >= 4.0.5, PHP 5)

odbc_next_result -- Checks if multiple results are available

Description

bool odbc_next_result ( resource result_id )

odbc_next_result() returns TRUE if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

This function returns FALSE on error.

The argument is a valid result identifier returned by odbc_exec().

Example 1. odbc_next_result()

&#60;?php
$r_Connection = odbc_connect($dsn, $username, $password);

$s_SQL = &#60;&#60;&#60;END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;

$r_Results = odbc_exec($r_Connection, $s_SQL);

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);

echo "Get second results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);

echo "Get third results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);

echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?&#62;

The above example will output:

Dump first result set array(1) {
  ["A"]=>
  string(1) "A"
}
bool(false)
Get second results set bool(true)
Dump second result set array(1) {
  ["B"]=>
  string(1) "B"
}
bool(false)
Get third results set bool(true)
Dump third result set array(1) {
  ["C"]=>
  string(1) "C"
}
bool(false)
Try for a fourth result set bool(false)

Prev | Home | Next
odbc_longreadlen | Up | odbc_num_fields


odbc_num_fields

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_num_fields -- Number of columns in a result

Description

int odbc_num_fields ( resource result_id )

odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().

Prev | Home | Next
odbc_next_result | Up | odbc_num_rows


odbc_num_rows

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_num_rows -- Number of rows in a result

Description

int odbc_num_rows ( resource result_id )

odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

Prev | Home | Next
odbc_num_fields | Up | odbc_pconnect


odbc_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_pconnect -- Open a persistent database connection

Description

resource odbc_pconnect ( string dsn, string user, string password [, int cursor_type] )

Returns an ODBC connection id or 0 (FALSE) on error. This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

Note: Persistent connections have no effect if PHP is used as a CGI program.

For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.

Prev | Home | Next
odbc_num_rows | Up | odbc_prepare


odbc_prepare

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_prepare -- Prepares a statement for execution

Description

resource odbc_prepare ( resource connection_id, string query_string )

Returns FALSE on error.

Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

In the following code, $res will only be valid if all three parameters to myproc are IN parameters:

&#60;?php
$a = 1;
$b = 2;
$c = 3;
$stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$res = odbc_execute($stmt, array($a, $b, $c));
?&#62;
If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

Prev | Home | Next
odbc_pconnect | Up | odbc_primarykeys


odbc_primarykeys

(PHP 4, PHP 5)

odbc_primarykeys -- Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table

Description

resource odbc_primarykeys ( resource connection_id, string qualifier, string owner, string table )

Returns the column names that comprise the primary key for a table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • COLUMN_NAME

  • KEY_SEQ

  • PK_NAME

Prev | Home | Next
odbc_prepare | Up | odbc_procedurecolumns


odbc_procedurecolumns

(PHP 4, PHP 5)

odbc_procedurecolumns -- Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource connection_id [, string qualifier, string owner, string proc, string column] )

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • COLUMN_NAME

  • COLUMN_TYPE

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.

The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Prev | Home | Next
odbc_primarykeys | Up | odbc_procedures


odbc_procedures

(PHP 4, PHP 5)

odbc_procedures -- Get the list of procedures stored in a specific data source

Description

resource odbc_procedures ( resource connection_id [, string qualifier, string owner, string name] )

Lists all procedures in the requested range. Returns an ODBC result identifier containing the information or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • NUM_INPUT_PARAMS

  • NUM_OUTPUT_PARAMS

  • NUM_RESULT_SETS

  • REMARKS

  • PROCEDURE_TYPE

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Prev | Home | Next
odbc_procedurecolumns | Up | odbc_result_all


odbc_result_all

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_result_all -- Print result as HTML table

Description

int odbc_result_all ( resource result_id [, string format] )

Returns the number of rows in the result or FALSE on error.

odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.

Prev | Home | Next
odbc_procedures | Up | odbc_result


odbc_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_result -- Get result data

Description

mixed odbc_result ( resource result_id, mixed field )

Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.

field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. For example:

&#60;?php
$item_3 = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?&#62;

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

Prev | Home | Next
odbc_result_all | Up | odbc_rollback


odbc_rollback

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_rollback -- Rollback a transaction

Description

bool odbc_rollback ( resource connection_id )

Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.

Prev | Home | Next
odbc_result | Up | odbc_setoption


odbc_setoption

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_setoption -- Adjust ODBC settings

Description

bool odbc_setoption ( resource id, int function, int option, int param )

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

Returns TRUE on success or FALSE on failure.

id is a connection id or result id on which to change the settings.For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

Function is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

Parameter option is the option to set.

Parameter param is the value for the given option.

Example 1. ODBC Setoption Examples

&#60;?php
// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?&#62;

Prev | Home | Next
odbc_rollback | Up | odbc_specialcolumns


odbc_specialcolumns

(PHP 4, PHP 5)

odbc_specialcolumns -- Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction

Description

resource odbc_specialcolumns ( resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable )

When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table.

When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • PSEUDO_COLUMN

The result set is ordered by SCOPE.

Prev | Home | Next
odbc_setoption | Up | odbc_statistics


odbc_statistics

(PHP 4, PHP 5)

odbc_statistics -- Retrieve statistics about a table

Description

resource odbc_statistics ( resource connection_id, string qualifier, string owner, string table_name, int unique, int accuracy )

Get statistics about a table and its indexes. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • NON_UNIQUE

  • INDEX_QUALIFIER

  • INDEX_NAME

  • TYPE

  • SEQ_IN_INDEX

  • COLUMN_NAME

  • COLLATION

  • CARDINALITY

  • PAGES

  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.

Prev | Home | Next
odbc_specialcolumns | Up | odbc_tableprivileges


odbc_tableprivileges

(PHP 4, PHP 5)

odbc_tableprivileges -- Lists tables and the privileges associated with each table

Description

resource odbc_tableprivileges ( resource connection_id, string qualifier, string owner, string name )

Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Prev | Home | Next
odbc_statistics | Up | odbc_tables


odbc_tables

(PHP 3 >= 3.0.17, PHP 4, PHP 5)

odbc_tables -- Get the list of table names stored in a specific data source

Description

resource odbc_tables ( resource connection_id [, string qualifier [, string owner [, string name [, string types]]]] )

Lists all tables in the requested range. Returns an ODBC result identifier containing the information or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • TABLE_TYPE

  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:

  • If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)

  • If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)

  • If table_type is a single percent character (%) and qualifier, owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

See also odbc_tableprivileges() to retrieve associated privileges.

Prev | Home | Next
odbc_tableprivileges | Up | ODBC and DB2 Functions (PDO_ODBC)


URL Functions

PHP Manual
Prev Next

CLXVII. URL Functions

Introduction

Dealing with URL strings: encoding, decoding and parsing.

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 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 are meant to be used with parse_url() and are available since PHP 5.1.2.

PHP_URL_SCHEME (integer)

PHP_URL_HOST (integer)

PHP_URL_PORT (integer)

PHP_URL_USER (integer)

PHP_URL_PASS (integer)

PHP_URL_PATH (integer)

PHP_URL_QUERY (integer)

PHP_URL_FRAGMENT (integer)

Table of Contents
base64_decode -- Decodes data encoded with MIME base64
base64_encode -- Encodes data with MIME base64
get_headers -- Fetches all the headers sent by the server in response to a HTTP request
get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array
http_build_query -- Generate URL-encoded query string
parse_url -- Parse a URL and return its components
rawurldecode -- Decode URL-encoded strings
rawurlencode -- URL-encode according to RFC 1738
urldecode -- Decodes URL-encoded string
urlencode -- URL-encodes string

Prev | Home | Next
unicode_semantics | Up | base64_decode


base64_decode

(PHP 3, PHP 4, PHP 5)

base64_decode -- Decodes data encoded with MIME base64

Description

string base64_decode ( string data )

Decodes a base64 encoded data.

Parameters

data

The decoded data.

Return Values

Returns the original data or FALSE on failure. The returned data may be binary.

Examples

Example 1. base64_decode() example

&#60;?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?&#62;

The above example will output:

This is an encoded string

See Also

base64_encode()
RFC 2045 section 6.8

Prev | Home | Next
URL Functions | Up | base64_encode


base64_encode

(PHP 3, PHP 4, PHP 5)

base64_encode -- Encodes data with MIME base64

Description

string base64_encode ( string data )

Encodes the given data with base64.

This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

Parameters

data

The data to encode.

Return Values

The encoded data, as a string.

Examples

Example 1. base64_encode() example

&#60;?php
$str = 'This is an encoded string';
echo base64_encode($str);
?&#62;

The above example will output:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See Also

base64_decode()
chunk_split()
convert_uuencode()
RFC 2045 section 6.8

Prev | Home | Next
base64_decode | Up | get_headers


get_headers

(PHP 5)

get_headers -- Fetches all the headers sent by the server in response to a HTTP request

Description

array get_headers ( string url [, int format] )

get_headers() returns an array with the headers sent by the server in response to a HTTP request.

Parameters

url

The target URL.

format

If the optional format parameter is set to 1, get_headers() parses the response and sets the array's keys.

Return Values

Returns an indexed or associative array with the headers, or FALSE on failure.

ChangeLog

Version | Description
5.1.3 | This function now uses the default stream context, which can be set/changed with the stream_context_get_default() function.

Examples

Example 1. get_headers() example

&#60;?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?&#62;

The above example will output something similar to:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Prev | Home | Next
base64_encode | Up | get_meta_tags


get_meta_tags

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array

Description

array get_meta_tags ( string filename [, bool use_include_path] )

Opens filename and parses it line by line for <meta> tags in the file. The parsing stops at </head>.

Parameters

filename

The path to the HTML file, as a string. This can be a local file or an URL.

Example 1. What get_meta_tags() parses

<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).

use_include_path

Setting use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

Return Values

Returns an array with all the parsed meta tags.

The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.

ChangeLog

Version | Description
4.0.5 | Support for unquoted HTML attributes was added.

Examples

Example 2. What get_meta_tags() returns

&#60;?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?&#62;

See Also

htmlentities()
urlencode()

Prev | Home | Next
get_headers | Up | http_build_query


http_build_query

(PHP 5)

http_build_query -- Generate URL-encoded query string

Description

string http_build_query ( array formdata [, string numeric_prefix [, string arg_separator]] )

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

formdata

May be an array or object containing properties.

The array form may be a simple one-dimensional structure, or an array of arrays (who in turn may contain other arrays).

numeric_prefix

If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

arg_separator

arg_separator.output is used to separate arguments, unless this parameter is specified, and is then used.

Return Values

Returns a URL-encoded string.

ChangeLog

Version | Description
5.1.2 | The arg_separator parameter was added.

Examples

Example 1. Simple usage of http_build_query()

&#60;?php
$data = array('foo'=&#62;'bar',
              'baz'=&#62;'boom',
              'cow'=&#62;'milk',
              'php'=&#62;'hypertext processor');

echo http_build_query($data); // foo=bar&#38;baz=boom&#38;cow=milk&#38;php=hypertext+processor
echo http_build_query($data, '', '&#38;amp;'); // foo=bar&#38;amp;baz=boom&#38;amp;cow=milk&#38;amp;php=hypertext+processor

?&#62;

Example 2. http_build_query() with numerically index elements.

&#60;?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' =&#62; 'milk', 'php' =&#62;'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?&#62;

The above example will output:

0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor

Example 3. http_build_query() with complex arrays

&#60;?php
$data = array('user'=&#62;array('name'=&#62;'Bob Smith',
                            'age'=&#62;47,
                            'sex'=&#62;'M',
                            'dob'=&#62;'5/12/1956'),
              'pastimes'=&#62;array('golf', 'opera', 'poker', 'rap'),
              'children'=&#62;array('bobby'=&#62;array('age'=&#62;12,
                                               'sex'=&#62;'M'),
                                'sally'=&#62;array('age'=&#62;8,
                                               'sex'=&#62;'F')),
              'CEO');

echo http_build_query($data, 'flags_');
?&#62;

this will output : (word wrapped for readability)

user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%2F12%2F1956&
pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&
children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&
children[sally][sex]=F&flags_0=CEO

Note: Only the numerically indexed element in the base array "CEO" received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Example 4. Using http_build_query() with an object

&#60;?php
class myClass {
    var $foo;
    var $baz;

    function myClass() {
        $this-&#62;foo = 'bar';
        $this-&#62;baz = 'boom';
    }
}

$data = new myClass();

echo http_build_query($data); // foo=bar&#38;baz=boom

?&#62;

See Also

parse_str()
parse_url()
urlencode()
array_walk()

Prev | Home | Next
get_meta_tags | Up | parse_url


parse_url

(PHP 3, PHP 4, PHP 5)

parse_url -- Parse a URL and return its components

Description

mixed parse_url ( string url [, int component] )

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Parameters

url

The URL to parse

component

Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string.

Return Values

On seriously malformed URLs, parse_url() may return FALSE and emit a E_WARNING. Otherwise an associative array is returned, whose components may be (at least one):

  • scheme - e.g. http

  • host

  • port

  • user

  • pass

  • path

  • query - after the question mark ?

  • fragment - after the hashmark #

If the component parameter is specified a string is returned instead of an array.

ChangeLog

Version | Description
5.1.2 | Added the component parameter

Examples

Example 1. A parse_url() example

&#60;?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?&#62;

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

Notes

Note: This function doesn't work with relative URLs.

Note: This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where tripple slashes (file:///...) are allowed. For any other scheme this is invalid.

See Also

pathinfo()
parse_str()
http_build_query()
dirname()
basename()

Prev | Home | Next
http_build_query | Up | rawurldecode


rawurldecode

(PHP 3, PHP 4, PHP 5)

rawurldecode -- Decode URL-encoded strings

Description

string rawurldecode ( string str )

Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.

Parameters

str

The URL to be decoded.

Return Values

Returns the decoded URL, as a string.

Examples

Example 1. rawurldecode() example

&#60;?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?&#62;

Notes

Note: rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

See Also

rawurlencode()
urldecode()
urlencode()

Prev | Home | Next
parse_url | Up | rawurlencode


rawurlencode

(PHP 3, PHP 4, PHP 5)

rawurlencode -- URL-encode according to RFC 1738

Description

string rawurlencode ( string str )

Encodes the given string according to RFC 1738.

Parameters

str

The URL to be encoded.

Return Values

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

Examples

Example 1. including a password in an FTP URL

&#60;?php
echo '&#60;a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt"&#62;';
?&#62;

The above example will output:

<a href="ftp://user:foo%20%40%2B%25%2F@ftp.example.com/x.txt">

Or, if you pass information in a PATH_INFO component of the URL:

Example 2. rawurlencode() example 2

&#60;?php
echo '&#60;a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '"&#62;';
?&#62;

The above example will output:

<a href="http://example.com/department_list_script/sales%20and%20marketing%2FMiami">

See Also

rawurldecode()
urldecode()
urlencode()
RFC 1738

Prev | Home | Next
rawurldecode | Up | urldecode


urldecode

(PHP 3, PHP 4, PHP 5)

urldecode -- Decodes URL-encoded string

Description

string urldecode ( string str )

Decodes any %## encoding in the given string.

Parameters

str

The string to be decoded.

Return Values

Returns the decoded string.

Examples

Example 1. urldecode() example

&#60;?php
$a = explode('&#38;', $QUERY_STRING);
$i = 0;
while ($i &#60; count($a)) {
    $b = split('=', $a[$i]);
    echo 'Value for parameter ', htmlspecialchars(urldecode($b[0])),
         ' is ', htmlspecialchars(urldecode($b[1])), "&#60;br /&#62;\n";
    $i++;
}
?&#62;

See Also

urlencode()
rawurlencode()
rawurldecode()

Prev | Home | Next
rawurlencode | Up | urlencode


urlencode

(PHP 3, PHP 4, PHP 5)

urlencode -- URL-encodes string

Description

string urlencode ( string str )

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Parameters

str

The string to be encoded.

Return Values

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Examples

Example 1. urlencode() example

&#60;?php
echo '&#60;a href="mycgi?foo=', urlencode($userinput), '"&#62;';
?&#62;

Example 2. urlencode() and htmlentities() example

&#60;?php
$query_string = 'foo=' . urlencode($foo) . '&#38;bar=' . urlencode($bar);
echo '&#60;a href="mycgi?' . htmlentities($query_string) . '"&#62;';
?&#62;

Notes

Note: Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2.

PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

See Also

urldecode()
htmlentities()
rawurlencode()
rawurldecode()

Prev | Home | Next
urldecode | Up | Variable Handling Functions


Variable Handling Functions

PHP Manual
Prev Next

CLXVIII. Variable Handling Functions

Introduction

For information on how variables behave, see the Variables entry in the Language Reference section of the manual.

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. Variables Configuration Options

Name | Default | Changeable | Changelog
unserialize_callback_func | NULL | PHP_INI_ALL | Available since PHP 4.2.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

unserialize_callback_func string

The unserialize() callback function will called (with the undefined class' name as parameter), if the unserializer finds an undefined class which should be instanciated. A warning appears if the specified function is not defined, or if the function doesn't include/implement the missing class. So only set this entry, if you really want to implement such a callback-function.

See also unserialize().

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
debug_zval_dump -- Dumps a string representation of an internal zend value to output
doubleval -- Alias of floatval()
empty -- Determine whether a variable is empty
floatval -- Get float value of a variable
get_defined_vars -- Returns an array of all defined variables
get_resource_type -- Returns the resource type
gettype -- Get the type of a variable
import_request_variables -- Import GET/POST/Cookie variables into the global scope
intval -- Get the integer value of a variable
is_array -- Finds whether a variable is an array
is_binary -- Finds whether a variable is a native binary string
is_bool -- Finds out whether a variable is a boolean
is_buffer -- Finds whether a variable is a native unicode or binary string
is_callable -- Verify that the contents of a variable can be called as a function
is_double -- Alias of is_float()
is_float -- Finds whether a variable is a float
is_int -- Find whether a variable is an integer
is_integer -- Alias of is_int()
is_long -- Alias of is_int()
is_null -- Finds whether a variable is NULL
is_numeric -- Finds whether a variable is a number or a numeric string
is_object -- Finds whether a variable is an object
is_real -- Alias of is_float()
is_resource -- Finds whether a variable is a resource
is_scalar -- Finds whether a variable is a scalar
is_string -- Finds whether a variable is a string
is_unicode -- Finds whether a variable is a unicode string
isset -- Determine whether a variable is set
print_r -- Prints human-readable information about a variable
serialize -- Generates a storable representation of a value
settype -- Set the type of a variable
strval -- Get string value of a variable
unserialize -- Creates a PHP value from a stored representation
unset -- Unset a given variable
var_dump -- Dumps information about a variable
var_export -- Outputs or returns a parsable string representation of a variable

Prev | Home | Next
urlencode | Up | debug_zval_dump


debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5)

debug_zval_dump -- Dumps a string representation of an internal zend value to output

Description

void debug_zval_dump ( mixed variable )

Dumps a string representation of an internal zend value to output.

Parameters

variable

The variable being evaluated.

Return Values

No value is returned.

Examples

Example 1. debug_zval_dump() example

&#60;?php
$var1 = 'Hello World';
$var2 = '';

$var2 =&#38; $var1;

debug_zval_dump(&#38;$var1);
?&#62;

The above example will output:

string(11) "Hello World" refcount(3)

Beware the refcount: The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().

This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:

Example 2.

&#60;?php
$var1 = 'Hello World';
$var2 = '';

$var2 =&#38; $var1;

debug_zval_dump($var1); // not passed by reference, this time
?&#62;

The above example will output:

string(11) "Hello World" refcount(1)

Why refcount(1)? Because a copy of $var1 is being made, when the function is called.

This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):

Example 3.

&#60;?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?&#62;

The above example will output:

string(11) "Hello World" refcount(2)

A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

See Also

var_dump()
debug_backtrace()
References Explained
Reference Counting and Aliasing (by Andi Gutmans)
References Explained (by Derick Rethans)

Prev | Home | Next
Variable Handling Functions | Up | doubleval


doubleval

(PHP 3, PHP 4, PHP 5)

doubleval -- Alias of floatval()

Description

This function is an alias of: floatval().

ChangeLog

Version | Description
4.2.0 | doubleval() became an alias of floatval(). Before this time, only doubleval() existed.

Prev | Home | Next
debug_zval_dump | Up | empty


empty

(PHP 3, PHP 4, PHP 5)

empty -- Determine whether a variable is empty

Description

bool empty ( mixed var )

Determine whether a variable is considered to be empty.

Parameters

var

Variable to be checked

Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

Return Values

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

ChangeLog

Version | Description
PHP 5 | As of PHP 5, objects with no properties are no longer considered empty.
PHP 4 | As of PHP 4, The string value "0" is considered empty.

Examples

Example 1. A simple empty() / isset() comparison.

&#60;?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?&#62;

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See Also

isset()
unset()
array_key_exists()
count()
strlen()
The type comparison tables

Prev | Home | Next
doubleval | Up | floatval


floatval

(PHP 4 >= 4.2.0, PHP 5)

floatval -- Get float value of a variable

Description

float floatval ( mixed var )

Gets the float value of var.

Parameters

var

May be any scalar type. You cannot use floatval() on arrays or objects.

Return Values

The float value of the given variable.

Examples

Example 1. floatval() Example

&#60;?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?&#62;

See Also

intval()
strval()
settype()
Type juggling

Prev | Home | Next
empty | Up | get_defined_vars


get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars -- Returns an array of all defined variables

Description

array get_defined_vars ( void )

This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.

Return Values

A multidimensional array with all the variables.

Examples

Example 1. get_defined_vars() Example

&#60;?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

/* print path to the PHP interpreter (if used as a CGI)
 * e.g. /usr/local/bin/php */
echo $arr["_"];

// print the command-line parameters if any
print_r($arr["argv"]);

// print all the server vars
print_r($arr["_SERVER"]);

// print all the available keys for the arrays of variables
print_r(array_keys(get_defined_vars()));
?&#62;

ChangeLog

Version | Description
5.0.0 | The $GLOBALS variable is included in the results of the array returned.

See Also

isset()
get_defined_functions()
get_defined_constants()

Prev | Home | Next
floatval | Up | get_resource_type


get_resource_type

(PHP 4 >= 4.0.2, PHP 5)

get_resource_type -- Returns the resource type

Description

string get_resource_type ( resource handle )

This function gets the type of the given resource.

Parameters

handle

The evaluated resource handle.

Return Values

If the given handle is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string Unknown.

This function will return FALSE and generate an error if handle is not a resource.

Examples

Example 1. get_resource_type() example

&#60;?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: file
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc-&#62;doc) . "\n";
?&#62;

Prev | Home | Next
get_defined_vars | Up | gettype


gettype

(PHP 3, PHP 4, PHP 5)

gettype -- Get the type of a variable

Description

string gettype ( mixed var )

Returns the type of the PHP variable var.

Warning

Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison.

Instead, use the is_* functions.

Return Values

Possibles values for the returned string are:

  • "boolean" (since PHP 4)

  • "integer"

  • "double" (for historical reasons "double" is returned in case of a float, and not simply "float")

  • "string"

  • "array"

  • "object"

  • "resource" (since PHP 4)

  • "NULL" (since PHP 4)

  • "user function" (PHP 3 only, deprecated)

  • "unknown type"

For PHP 4, you should use function_exists() and method_exists() to replace the prior usage of gettype() on a function.

See Also

settype()
is_array()
is_bool()
is_float()
is_int()
is_null()
is_numeric()
is_object()
is_resource()
is_scalar()
is_string()

Prev | Home | Next
get_resource_type | Up | import_request_variables


import_request_variables

(PHP 4 >= 4.1.0, PHP 5)

import_request_variables -- Import GET/POST/Cookie variables into the global scope

Description

bool import_request_variables ( string types [, string prefix] )

Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.

Using the types parameter, you can specify which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the POST uploaded file information. Note that the order of the letters matters, as when using "gp", the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.

The prefix parameter is used as a variable name prefix, prepended before all variable's name imported into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then you'll get a global variable named $pref_userid.

If you're interested in importing other variables into the global scope, such as SERVER, consider using extract().

Note: Although the prefix parameter is optional, you will get an E_NOTICE level error if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.

&#60;?php
// This will import GET and POST vars
// with an "rvar_" prefix
import_request_variables("gP", "rvar_");

echo $rvar_foo;
?&#62;

See also $_REQUEST, register_globals, Predefined Variables, and extract().

Prev | Home | Next
gettype | Up | intval


intval

(PHP 3, PHP 4, PHP 5)

intval -- Get the integer value of a variable

Description

int intval ( mixed var [, int base] )

Returns the integer value of var, using the specified base for the conversion (the default is base 10).

Parameters

var

The scalar value being converted to an integer

base

The base for the conversion (default is base 10)

Return Values

The integer value of var on success, or 0 on failure. Empty arrays and objects return 0, non-empty arrays and objects return 1.

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Examples

Example 1. intval() examples

The following examples are based on a 32 bit system.

&#60;?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
?&#62;

Notes

Note: The base parameter has no effect unless the var parameter is a string.

See Also

floatval()
strval()
settype()
is_numeric()
Type juggling
BCMath Arbitrary Precision Mathematics Functions

Prev | Home | Next
import_request_variables | Up | is_array


is_array

(PHP 3, PHP 4, PHP 5)

is_array -- Finds whether a variable is an array

Description

bool is_array ( mixed var )

Finds whether the given variable is an array.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an array, FALSE otherwise.

Examples

Example 1. Check that variable is an array

&#60;?php
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';
?&#62;

The above example will output:

Array
not an Array

See Also

is_float()
is_int()
is_string()
is_object()

Prev | Home | Next
intval | Up | is_binary


is_bool

(PHP 4, PHP 5)

is_bool -- Finds out whether a variable is a boolean

Description

bool is_bool ( mixed var )

Finds whether the given variable is a boolean.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a boolean, FALSE otherwise.

Examples

Example 1. is_bool() examples

&#60;?php
$a = false;
$b = 0;

// Since $a is a boolean, this is true
if (is_bool($a)) {
    echo "Yes, this is a boolean";
}

// Since $b is not a boolean, this is not true
if (is_bool($b)) {
    echo "Yes, this is a boolean";
}
?&#62;

See Also

is_float()
is_int()
is_string()
is_object()
is_array()

Prev | Home | Next
is_binary | Up | is_buffer


is_callable

(PHP 4 >= 4.0.6, PHP 5)

is_callable -- Verify that the contents of a variable can be called as a function

Description

bool is_callable ( mixed var [, bool syntax_only [, string &callable_name]] )

Verify that the contents of a variable can be called as a function. This can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.

The var parameter can be either the name of a function stored in a string variable, or an object and the name of a method within the object, like this:

array($SomeObject, 'MethodName')

If the syntax_only argument is TRUE the function only verifies that var might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string.

The callable_name argument receives the "callable name". In the example below it's "someClass:someMethod". Note, however, that despite the implication that someClass::SomeMethod() is a callable static method, this is not the case.

&#60;?php
//  How to check a variable to see if it can be called
//  as a function.

//
//  Simple variable containing a function
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Array containing a method
//

class someClass {

  function someMethod()
  {
  }

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true)

echo $callable_name, "\n";  //  someClass:someMethod

?&#62;

See also function_exists() and method_exists().

Prev | Home | Next
is_buffer | Up | is_double


is_double

(PHP 3, PHP 4, PHP 5)

is_double -- Alias of is_float()

Description

This function is an alias of: is_float().

Prev | Home | Next
is_callable | Up | is_float


is_float

(PHP 3, PHP 4, PHP 5)

is_float -- Finds whether a variable is a float

Description

bool is_float ( mixed var )

Finds whether the given variable is a float.

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a float, FALSE otherwise.

See Also

is_bool()
is_int()
is_numeric()
is_string()
is_array()
is_object()

Prev | Home | Next
is_double | Up | is_int


is_int

(PHP 3, PHP 4, PHP 5)

is_int -- Find whether a variable is an integer

Description

bool is_int ( mixed var )

Finds whether the given variable is an integer.

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an integer, FALSE otherwise.

See Also

is_bool()
is_float()
is_numeric()
is_string()
is_array()
is_object()

Prev | Home | Next
is_float | Up | is_integer


is_integer

(PHP 3, PHP 4, PHP 5)

is_integer -- Alias of is_int()

Description

This function is an alias of: is_int().

Prev | Home | Next
is_int | Up | is_long


is_long

(PHP 3, PHP 4, PHP 5)

is_long -- Alias of is_int()

Description

This function is an alias of: is_int().

Prev | Home | Next
is_integer | Up | is_null


is_null

(PHP 4 >= 4.0.4, PHP 5)

is_null -- Finds whether a variable is NULL

Description

bool is_null ( mixed var )

Finds whether the given variable is NULL.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is null, FALSE otherwise.

See Also

The NULL type
is_bool()
is_numeric()
is_float()
is_int()
is_string()
is_object()
is_array()

Prev | Home | Next
is_long | Up | is_numeric


is_numeric

(PHP 4, PHP 5)

is_numeric -- Finds whether a variable is a number or a numeric string

Description

bool is_numeric ( mixed var )

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a number or a numeric string, FALSE otherwise.

See Also

ctype_digit()
is_bool()
is_null()
is_float()
is_int()
is_string()
is_object()
is_array()

Prev | Home | Next
is_null | Up | is_object


is_object

(PHP 3, PHP 4, PHP 5)

is_object -- Finds whether a variable is an object

Description

bool is_object ( mixed var )

Finds whether the given variable is an object.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an object, FALSE otherwise.

Notes

Note: This function will return FALSE if used on an unserialized object where the class definition is not present (even though gettype() returns object).

See Also

is_bool()
is_int()
is_float()
is_string()
is_array()

Prev | Home | Next
is_numeric | Up | is_real


is_real

(PHP 3, PHP 4, PHP 5)

is_real -- Alias of is_float()

Description

This function is an alias of: is_float().

Prev | Home | Next
is_object | Up | is_resource


is_resource

(PHP 4, PHP 5)

is_resource -- Finds whether a variable is a resource

Description

bool is_resource ( mixed var )

Finds whether the given variable is a resource.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a resource, FALSE otherwise.

Examples

Example 1. is_resource() example

&#60;?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

?&#62;

See Also

The resource-type documentation
get_resource_type()

Prev | Home | Next
is_real | Up | is_scalar


is_scalar

(PHP 4 >= 4.0.5, PHP 5)

is_scalar -- Finds whether a variable is a scalar

Description

bool is_scalar ( mixed var )

Finds whether the given variable is a scalar.

Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource are not scalar.

Note: is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a scalar FALSE otherwise.

Examples

Example 1. is_scalar() example

&#60;?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?&#62;

The above example will output:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

See Also

is_float()
is_int()
is_numeric()
is_real()
is_string()
is_bool()
is_object()
is_array()

Prev | Home | Next
is_resource | Up | is_string


is_string

(PHP 3, PHP 4, PHP 5)

is_string -- Finds whether a variable is a string

Description

bool is_string ( mixed var )

Finds whether the given variable is a string.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a string, FALSE otherwise.

See Also

is_float()
is_int()
is_bool()
is_object()
is_array()

Prev | Home | Next
is_scalar | Up | is_unicode


isset

(PHP 3, PHP 4, PHP 5)

isset -- Determine whether a variable is set

Description

bool isset ( mixed var [, mixed var [, ...]] )

Returns TRUE if var exists; FALSE otherwise.

If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.

Warning: isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

&#60;?php

$var = '';

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}

// In the next examples we'll use var_dump to output
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?&#62;

This also work for elements in arrays:

&#60;?php

$a = array ('test' =&#62; 1, 'hello' =&#62; NULL);

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE

?&#62;

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also empty(), unset(), defined(), the type comparison tables, array_key_exists(), and the error control @ operator.

Prev | Home | Next
is_unicode | Up | print_r


print_r

(PHP 4, PHP 5)

print_r -- Prints human-readable information about a variable

Description

bool print_r ( mixed expression [, bool return] )

Note: The return parameter was added in PHP 4.3.0

print_r() displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects. print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5.

Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.

&#60;pre&#62;
&#60;?php
    $a = array ('a' =&#62; 'apple', 'b' =&#62; 'banana', 'c' =&#62; array ('x', 'y', 'z'));
    print_r ($a);
?&#62;
&#60;/pre&#62;

The above example will output:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

If you would like to capture the output of print_r(), use the return parameter. If this parameter is set to TRUE, print_r() will return its output, instead of printing it (which it does by default).

Note: This function internally uses the output buffering with this parameter so it can not be used inside ob_start() callback function.

Example 1. return parameter example

&#60;?php
    $b = array ('m' =&#62; 'monkey', 'foo' =&#62; 'bar', 'x' =&#62; array ('x', 'y', 'z'));
    $results = print_r($b, true); //$results now contains output from print_r
?&#62;

Note: If you need to capture the output of print_r() with a version of PHP prior to 4.3.0, use the output-control functions.

Note: Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a global variable that contains a reference to itself.

See also ob_start(),
var_dump() and
var_export().

Prev | Home | Next
isset | Up | serialize


serialize

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

serialize -- Generates a storable representation of a value

Description

string serialize ( mixed value )

serialize() returns a string containing a byte-stream representation of value that can be stored anywhere.

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize(). serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serialize()ing will also be stored. Any other reference will be lost.

When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.

Note: This didn't work correctly until 4.0.7.

Note: In PHP 3, object properties will be serialized, but methods are lost. That limitation was removed in PHP 4 as both properties and methods are now restored. Please see the Serializing Objects section of Classes and Objects for more information.

It is not possible to serialize PHP built-in objects.

Example 1. serialize() example

&#60;?php
// $session_data contains a multi-dimensional array with session
// information for the current user.  We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute($stmt, &#38;$sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, &#38;$sqldata)) {
        /* Something went wrong.. */
    }
}
?&#62;

See Also: unserialize().

Prev | Home | Next
print_r | Up | settype


settype

(PHP 3, PHP 4, PHP 5)

settype -- Set the type of a variable

Description

bool settype ( mixed &var, string type )

Set the type of variable var to type.

Possibles values of type are:

  • "boolean" (or, since PHP 4.2.0, "bool")

  • "integer" (or, since PHP 4.2.0, "int")

  • "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")

  • "string"

  • "array"

  • "object"

  • "null" (since PHP 4.2.0)

Returns TRUE on success or FALSE on failure.

Example 1. settype() example

&#60;?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?&#62;

See also gettype(), type-casting and type-juggling.

Prev | Home | Next
serialize | Up | strval


strval

(PHP 3, PHP 4, PHP 5)

strval -- Get string value of a variable

Description

string strval ( mixed var )

Returns the string value of var. See the documentation on string for more information on converting to string.

var may be any scalar type. You cannot use strval() on arrays or objects.

See Also

floatval()
intval()
settype()
Type juggling

Prev | Home | Next
settype | Up | unserialize


unserialize

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

unserialize -- Creates a PHP value from a stored representation

Description

mixed unserialize ( string str )

unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The converted value is returned, and can be a boolean, integer, float, string, array or object. In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.

Warning

FALSE is returned both in the case of an error and if unserializing the serialized FALSE value. It is possible to catch this special case by comparing str with serialize(false) or by catching the issued E_NOTICE.

unserialize_callback_func directive: It's possible to set a callback-function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess to define 'unserialize_callback_func'. Everytime an undefined class should be instantiated, it'll be called. To disable this feature just empty this setting. Also note that the directive unserialize_callback_func directive became available in PHP 4.2.0.

If the variable being unserialized is an object, after successfully reconstructing the object PHP will automatically attempt to call the __wakeup() member function (if it exists).

Example 1. unserialize_callback_func example

&#60;?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// unserialize_callback_func directive available as of PHP 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // set your callback_function

function mycallback($classname)
{
    // just include a file containing your classdefinition
    // you get $classname to figure out which classdefinition is required
}
?&#62;

Note: In PHP 3, methods are not preserved when unserializing a serialized object. That limitation was removed in PHP 4 as both properties and methods are now restored. Please see the Serializing Objects section of Classes and Objects or more information.

Example 2. unserialize() example

&#60;?php
// Here, we use unserialize() to load session data to the
// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array ($PHP_AUTH_USER);
if (!odbc_execute($stmt, &#38;$sqldata) || !odbc_fetch_into($stmt, &#38;$tmp)) {
    // if the execute or fetch fails, initialize to empty array
    $session_data = array();
} else {
    // we should now have the serialized data in $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // something went wrong, initialize to empty array
        $session_data = array();
    }
}
?&#62;

See also serialize().

Prev | Home | Next
strval | Up | unset


unset

(PHP 3, PHP 4, PHP 5)

unset -- Unset a given variable

Description

void unset ( mixed var [, mixed var [, mixed ...]] )

unset() destroys the specified variables. Note that in PHP 3, unset() will always return TRUE (actually, the integer value 1). In PHP 4, however, unset() is no longer a true function: it is now a statement. As such no value is returned, and attempting to take the value of unset() results in a parse error.

Example 1. unset() example

&#60;?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
?&#62;

Note: It is possible to unset even object properties visible in current context.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

&#60;?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?&#62;

The above example will output:

bar

If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:

&#60;?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?&#62;

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

&#60;?php
function foo(&#38;$bar)
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?&#62;

The above example will output:

something
something

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

&#60;?php
function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}

foo();
foo();
foo();
?&#62;

The above example will output:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also isset(),
empty(), and
array_splice().

Prev | Home | Next
unserialize | Up | var_dump


var_dump

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

var_dump -- Dumps information about a variable

Description

void var_dump ( mixed expression [, mixed expression [, ...]] )

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

In PHP 5 all public, private and protected properties of objects will be returned in the output.

Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions to capture the output of this function, and save it in a string (for example).

Parameters

expression

The variable you want to export.

Return Values

No value is returned.

Examples

Example 1. var_dump() example

&#60;?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?&#62;

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
&#60;?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?&#62;

The above example will output:

float(3.1)
bool(true)

See Also

var_export()
print_r()

Prev | Home | Next
unset | Up | var_export


var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export -- Outputs or returns a parsable string representation of a variable

Description

mixed var_export ( mixed expression [, bool return] )

var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.

Parameters

expression

The variable you want to export.

return

If used and set to TRUE, var_export() will return the variable representation instead of outputing it.

Note: This function internally uses the output buffering with this parameter so it can not be used inside ob_start() callback function.

Return Values

Returns the variable representation when the return parameter is used and evaluates to TRUE. Otherwise, this function will return NULL.

ChangeLog

Version | Description
5.1.0 | Possibility to export classes and arrays containing classes using the __set_state magic method.

Examples

Example 1. var_export() Examples

&#60;?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?&#62;

The above example will output:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
&#60;?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?&#62;

The above example will output:

3.1

Example 2. Exporting classes since PHP 5.1.0

&#60;?php
class A { public $var; }
$a = new A;
$a-&#62;var = 5;
var_export($a);
?&#62;

The above example will output:

A::__set_state(array(
   'var' => 5,
))

Example 3. Using __set_state (since PHP 5.1.0)

&#60;?php
class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj-&#62;var1 = $an_array['var1'];
        $obj-&#62;var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a-&#62;var1 = 5;
$a-&#62;var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' =&#62; 5,
                                            //    'var2' =&#62; 'foo',
                                            // ));
var_dump($b);
?&#62;

The above example will output:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Notes

Note: Variables of type resource couldn't be exported by this function.

Note: var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().

See Also

print_r()
serialize()
var_dump()

Prev | Home | Next
var_dump | Up | Verisign Payflow Pro Functions


vpopmail Functions

PHP Manual
Prev Next

CLXX. vpopmail 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.

This extension has been moved from PHP as of PHP 4.3.0 and now vpopmail lives in PECL.

Installation

As of PHP 4, these functions are only available if PHP was configured with --with-vpopmail[=DIR].

Table of Contents
vpopmail_add_alias_domain_ex -- Add alias to an existing virtual domain
vpopmail_add_alias_domain -- Add an alias for a virtual domain
vpopmail_add_domain_ex -- Add a new virtual domain
vpopmail_add_domain -- Add a new virtual domain
vpopmail_add_user -- Add a new user to the specified virtual domain
vpopmail_alias_add -- Insert a virtual alias
vpopmail_alias_del_domain -- Deletes all virtual aliases of a domain
vpopmail_alias_del -- Deletes all virtual aliases of a user
vpopmail_alias_get_all -- Get all lines of an alias for a domain
vpopmail_alias_get -- Get all lines of an alias for a domain
vpopmail_auth_user -- Attempt to validate a username/domain/password
vpopmail_del_domain_ex -- Delete a virtual domain
vpopmail_del_domain -- Delete a virtual domain
vpopmail_del_user -- Delete a user from a virtual domain
vpopmail_error -- Get text message for last vpopmail error
vpopmail_passwd -- Change a virtual user's password
vpopmail_set_user_quota -- Sets a virtual user's quota

Prev | Home | Next
pfpro_version | Up | vpopmail_add_alias_domain_ex


vpopmail_add_alias_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_alias_domain_ex -- Add alias to an existing virtual domain

Description

bool vpopmail_add_alias_domain_ex ( string olddomain, string newdomain )

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.

Prev | Home | Next
vpopmail Functions | Up | vpopmail_add_alias_domain


vpopmail_add_alias_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_alias_domain -- Add an alias for a virtual domain

Description

bool vpopmail_add_alias_domain ( string domain, string aliasdomain )

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.

Prev | Home | Next
vpopmail_add_alias_domain_ex | Up | vpopmail_add_domain_ex


vpopmail_add_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_domain_ex -- Add a new virtual domain

Description

bool vpopmail_add_domain_ex ( string domain, string passwd [, string quota [, string bounce [, bool apop]]] )

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.

Prev | Home | Next
vpopmail_add_alias_domain | Up | vpopmail_add_domain


vpopmail_add_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_domain -- Add a new virtual domain

Description

bool vpopmail_add_domain ( string domain, string dir, int uid, int gid )

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.

Prev | Home | Next
vpopmail_add_domain_ex | Up | vpopmail_add_user


vpopmail_add_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_user -- Add a new user to the specified virtual domain

Description

bool vpopmail_add_user ( string user, string domain, string password [, string gecos [, bool apop]] )

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.

Prev | Home | Next
vpopmail_add_domain | Up | vpopmail_alias_add


vpopmail_alias_add

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_add -- Insert a virtual alias

Description

bool vpopmail_alias_add ( string user, string domain, string alias )

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.

Prev | Home | Next
vpopmail_add_user | Up | vpopmail_alias_del_domain


vpopmail_alias_del_domain

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_del_domain -- Deletes all virtual aliases of a domain

Description

bool vpopmail_alias_del_domain ( string domain )

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.

Prev | Home | Next
vpopmail_alias_add | Up | vpopmail_alias_del


vpopmail_alias_del

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_del -- Deletes all virtual aliases of a user

Description

bool vpopmail_alias_del ( string user, string domain )

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.

Prev | Home | Next
vpopmail_alias_del_domain | Up | vpopmail_alias_get_all


vpopmail_alias_get_all

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_get_all -- Get all lines of an alias for a domain

Description

array vpopmail_alias_get_all ( string domain )

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.

Prev | Home | Next
vpopmail_alias_del | Up | vpopmail_alias_get


vpopmail_alias_get

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_get -- Get all lines of an alias for a domain

Description

array vpopmail_alias_get ( string alias, string domain )

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.

Prev | Home | Next
vpopmail_alias_get_all | Up | vpopmail_auth_user


vpopmail_auth_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_auth_user -- Attempt to validate a username/domain/password

Description

bool vpopmail_auth_user ( string user, string domain, string password [, string apop] )

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.

Prev | Home | Next
vpopmail_alias_get | Up | vpopmail_del_domain_ex


vpopmail_del_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_domain_ex -- Delete a virtual domain

Description

bool vpopmail_del_domain_ex ( string domain )

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.

Prev | Home | Next
vpopmail_auth_user | Up | vpopmail_del_domain


vpopmail_del_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_domain -- Delete a virtual domain

Description

bool vpopmail_del_domain ( string domain )

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.

Prev | Home | Next
vpopmail_del_domain_ex | Up | vpopmail_del_user


vpopmail_del_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_user -- Delete a user from a virtual domain

Description

bool vpopmail_del_user ( string user, string domain )

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.

Prev | Home | Next
vpopmail_del_domain | Up | vpopmail_error


vpopmail_error

(4.0.5 - 4.2.3 only, PECL)

vpopmail_error -- Get text message for last vpopmail error

Description

string vpopmail_error ( void )

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.

Prev | Home | Next
vpopmail_del_user | Up | vpopmail_passwd


vpopmail_passwd

(4.0.5 - 4.2.3 only, PECL)

vpopmail_passwd -- Change a virtual user's password

Description

bool vpopmail_passwd ( string user, string domain, string password [, bool apop] )

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.

Prev | Home | Next
vpopmail_error | Up | vpopmail_set_user_quota


vpopmail_set_user_quota

(4.0.5 - 4.2.3 only, PECL)

vpopmail_set_user_quota -- Sets a virtual user's quota

Description

bool vpopmail_set_user_quota ( string user, string domain, string quota )

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.

Prev | Home | Next
vpopmail_passwd | Up | W32api Functions


W32api Functions

PHP Manual
Prev Next

CLXXI. W32api Functions

Introduction

This extension is a generic extension API to DLLs. This was originally written to allow access to the Win32 API from PHP, although you can also access other functions exported via other DLLs.

Currently supported types are generic PHP types (strings, booleans, floats, integers and nulls) and types you define with w32api_deftype().

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

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

This extension will only work on Windows systems.

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 defines one resource type, used for user defined types. The name of this resource is "dynaparm".

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.

DC_MICROSOFT (integer)

DC_BORLAND (integer)

DC_CALL_CDECL (integer)

DC_CALL_STD (integer)

DC_RETVAL_MATH4 (integer)

DC_RETVAL_MATH8 (integer)

DC_CALL_STD_BO (integer)

DC_CALL_STD_MS (integer)

DC_CALL_STD_M8 (integer)

DC_FLAG_ARGPTR (integer)

Examples

This example gets the amount of time the system has been running and displays it in a message box.

Example 1. Get the uptime and display it in a message box

&#60;?php
// Define constants needed, taken from
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);

// Load the extension in
dl("php_w32api.dll");

// Register the GetTickCount function from kernel32.dll
w32api_register_function("kernel32.dll",
                         "GetTickCount",
                         "long");

// Register the MessageBoxA function from User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");

// Get uptime information
$ticks = GetTickCount();

// Convert it to a nicely displayable text
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);

$str = sprintf("You have been using your computer for:" .
                "\r\n %d Milliseconds, or \r\n %d Seconds" .
                "or \r\n %d mins or\r\n %d hours %d mins.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));

// Display a message box with only an OK button and the uptime text
MessageBoxA(NULL,
            $str,
            "Uptime Information",
            MB_OK);
?&#62;
Table of Contents
w32api_deftype -- Defines a type for use with other w32api_functions
w32api_init_dtype -- Creates an instance of the data type typename and fills it with the values passed
w32api_invoke_function -- Invokes function funcname with the arguments passed after the function name
w32api_register_function -- Registers function function_name from library with PHP
w32api_set_call_method -- Sets the calling method used

Prev | Home | Next
vpopmail_set_user_quota | Up | w32api_deftype


w32api_deftype

(4.2.0 - 4.2.3 only)

w32api_deftype -- Defines a type for use with other w32api_functions

Description

bool w32api_deftype ( string typename, string member1_type, string member1_name [, string ... [, string ...]] )

You need to call this function if you would like to define a type for a w32api call.

Parameters

typename

The name of the type.

member1_type

A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase.

member1_name

The member name of member1_type.

...

...

This function takes 2n+1 arguments, where n is the number of members the type has. After that is the type of the member followed by the members name (in pairs).

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.

Prev | Home | Next
W32api Functions | Up | w32api_init_dtype


w32api_init_dtype

(4.2.0 - 4.2.3 only)

w32api_init_dtype -- Creates an instance of the data type typename and fills it with the values passed

Description

resource w32api_init_dtype ( string typename, mixed value [, mixed ...] )

This function creates an instance of the data type named typename, filling in the values of the data type.

Parameters

typename

The typename parameter is case sensitive.

value

You should give the values in the same order as you defined the data type with w32api_deftype().

...

Return Values

Returns a dynaparm resource.

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.

Prev | Home | Next
w32api_deftype | Up | w32api_invoke_function


w32api_invoke_function

(4.2.0 - 4.2.3 only)

w32api_invoke_function -- Invokes function funcname with the arguments passed after the function name

Description

mixed w32api_invoke_function ( string funcname, mixed argument [, mixed ...] )

w32api_invoke_function() tries to find the previously registered function, passing the parameters you provided.

Parameters

funcname

The function name.

argument

Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.

...

Return Values

The return type is the one you set when you registered the function, the value is the one returned by the function itself.

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.

Prev | Home | Next
w32api_init_dtype | Up | w32api_register_function


w32api_register_function

(4.2.0 - 4.2.3 only)

w32api_register_function -- Registers function function_name from library with PHP

Description

bool w32api_register_function ( string library, string function_name, string return_type )

This function tries to find the function_name function in libary, and tries to import it into PHP.

Parameters

library

The library name, as a string.

function_name

The function name, as a string.

return_type

The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase.

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.

Prev | Home | Next
w32api_invoke_function | Up | w32api_set_call_method


w32api_set_call_method

(4.2.0 - 4.2.3 only)

w32api_set_call_method -- Sets the calling method used

Description

void w32api_set_call_method ( int method )

This function sets the method call type.

Parameters

method

Can be one of DC_CALL_CDECL or DC_CALL_STD (the extension default).

Return Values

No value is returned.

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.

Prev | Home | Next
w32api_register_function | Up | WDDX Functions


WDDX Functions

PHP Manual
Prev Next

CLXXII. WDDX Functions

Introduction

These functions are intended for work with WDDX.

Requirements

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

Installation

After installing expat compile PHP with --enable-wddx.

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

This extension has no constants defined.

Examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Example 1. Serializing a single value with WDDX

&#60;?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?&#62;

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Example 2. Using incremental packets with WDDX

&#60;?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?&#62;

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Note: If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).

Table of Contents
wddx_add_vars -- Add variables to a WDDX packet with the specified ID
wddx_deserialize -- Alias of wddx_unserialize()
wddx_packet_end -- Ends a WDDX packet with the specified ID
wddx_packet_start -- Starts a new WDDX packet with structure inside it
wddx_serialize_value -- Serialize a single value into a WDDX packet
wddx_serialize_vars -- Serialize variables into a WDDX packet
wddx_unserialize -- Unserializes a WDDX packet

Prev | Home | Next
w32api_set_call_method | Up | wddx_add_vars


wddx_add_vars

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_add_vars -- Add variables to a WDDX packet with the specified ID

Description

bool wddx_add_vars ( resource packet_id, mixed var_name [, mixed ...] )

Serializes the passed variables and add the result to the fiven packet.

Parameters

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
WDDX Functions | Up | wddx_deserialize


wddx_deserialize

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_deserialize -- Alias of wddx_unserialize()

Description

This function is an alias of: wddx_unserialize().

Prev | Home | Next
wddx_add_vars | Up | wddx_packet_end


wddx_packet_end

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_packet_end -- Ends a WDDX packet with the specified ID

Description

string wddx_packet_end ( resource packet_id )

Ends and returns the given WDDX packet.

Parameters

packet_id

A WDDX packet, returned by wddx_packet_start().

Return Values

Returns the string containing the WDDX packet.

Prev | Home | Next
wddx_deserialize | Up | wddx_packet_start


wddx_packet_start

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_packet_start -- Starts a new WDDX packet with structure inside it

Description

resource wddx_packet_start ( [string comment] )

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Parameters

comment

An optional comment string.

Return Values

Returns a packet ID for use in later functions, or FALSE on error.

Prev | Home | Next
wddx_packet_end | Up | wddx_serialize_value


wddx_serialize_value

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_serialize_value -- Serialize a single value into a WDDX packet

Description

string wddx_serialize_value ( mixed var [, string comment] )

Creates a WDDX packet from a single given value.

Parameters

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Return Values

Returns the WDDX packet, or FALSE on error.

Prev | Home | Next
wddx_packet_start | Up | wddx_serialize_vars


wddx_serialize_vars

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_serialize_vars -- Serialize variables into a WDDX packet

Description

string wddx_serialize_vars ( mixed var_name [, mixed ...] )

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Parameters

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Return Values

Returns the WDDX packet, or FALSE on error.

Examples

Example 1. wddx_serialize_vars() example

&#60;?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?&#62;

The above example will output:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

Prev | Home | Next
wddx_serialize_value | Up | wddx_unserialize


xattr Functions

PHP Manual
Prev Next

CLXXV. xattr Functions

Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.

Requirements

To use xattr, you will need libattr installed. It is available at http://oss.sgi.com/projects/xfs/.

Note: These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.

Installation

xattr is currently available through PECL http://pecl.php.net/package/xattr.

If PEAR is available on your *nix-like system you can use the pear installer to install the xattr extension, by the following command: pear -v install xattr.

You can always download the tar.gz package and install xattr by hand:

Example 1. xattr install by hand

gunzip xattr-xxx.tgz
tar -xvf xattr-xxx.tar
cd xattr-xxx
phpize
./configure && make && make install

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.

XATTR_ROOT (integer)

Set attribute in root (trusted) namespace. Requires root privileges.

XATTR_DONTFOLLOW (integer)

Do not follow the symbolic link but operate on symbolic link itself.

XATTR_CREATE (integer)

Function will fail if extended attribute already exists.

XATTR_REPLACE (integer)

Function will fail if extended attribute doesn't exist.

Table of Contents
xattr_get -- Get an extended attribute
xattr_list -- Get a list of extended attributes
xattr_remove -- Remove an extended attribute
xattr_set -- Set an extended attribute
xattr_supported -- Check if filesystem supports extended attributes

Prev | Home | Next
win32_stop_service | Up | xattr_get


xattr_get

(PECL)

xattr_get -- Get an extended attribute

Description

string xattr_get ( string filename, string name [, int flags] )

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Parameters

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Table 1. Supported xattr flags

XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns a string containing the value or FALSE if the attribute doesn't exist.

Examples

Example 1. Checks if system administrator has signed the file

&#60;?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?&#62;

See Also

xattr_list()
xattr_set()
xattr_remove()

Prev | Home | Next
xattr Functions | Up | xattr_list


xattr_list

(PECL)

xattr_list -- Get a list of extended attributes

Description

array xattr_list ( string filename [, int flags] )

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Parameters

filename

The path of the file.

flags

Table 1. Supported xattr flags

XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

This function returns an array with names of extended attributes.

Examples

Example 1. Prints names of all extended attributes of file

&#60;?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

?&#62;

See Also

xattr_get()

Prev | Home | Next
xattr_get | Up | xattr_remove


xattr_remove

(PECL)

xattr_remove -- Remove an extended attribute

Description

bool xattr_remove ( string filename, string name [, int flags] )

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Parameters

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Table 1. Supported xattr flags

XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Removes all extended attributes of a file

&#60;?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
    xattr_remove($file, $attr_name);
}
?&#62;

See Also

xattr_list()
xattr_set()
xattr_get()

Prev | Home | Next
xattr_list | Up | xattr_set


xattr_set

(PECL)

xattr_set -- Set an extended attribute

Description

bool xattr_set ( string filename, string name, string value [, int flags] )

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Parameters

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Table 1. Supported xattr flags

XATTR_CREATE | Function will fail if extended attribute already exists.
XATTR_REPLACE | Function will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Sets extended attributes on .wav file

&#60;?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');

/* ... other code ... */

printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?&#62;

See Also

xattr_get()
xattr_remove()

Prev | Home | Next
xattr_remove | Up | xattr_supported


xattr_supported

(PECL)

xattr_supported -- Check if filesystem supports extended attributes

Description

bool xattr_supported ( string filename [, int flags] )

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

Parameters

filename

The path of the tested file.

flags

Table 1. Supported xattr flags

XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.

Return Values

This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).

Examples

Example 1. xattr_supported() example

The following code checks if we can use extended attributes.

&#60;?php
$file = 'some_file';

if (xattr_supported($file)) {
    /* ... make use of some xattr_* functions ... */
}

?&#62;

See Also

xattr_get()
xattr_list()

Prev | Home | Next
xattr_set | Up | xdiff Functions


xdiff Functions

PHP Manual
Prev Next

CLXXVI. xdiff Functions

Introduction

xdiff extension creates and applies patches to both text and binary files.

Requirements

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage http://www.xmailserver.org/xdiff-lib.html.

Note: You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

Installation

xdiff is currently available through PECL http://pecl.php.net/package/xdiff.

If PEAR is available on your *nix-like system you can use the pear installer to install the xdiff extension, by the following command: pear -v install xdiff.

You can always download the tar.gz package and install xdiff by hand:

Example 1. xdiff install by hand

gunzip xdiff-xxx.tgz
tar -xvf xdiff-xxx.tar
cd xdiff-xxx
phpize
./configure && make && make install

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.

XDIFF_PATCH_NORMAL (integer)

XDIFF_PATCH_REVERSE (integer)

Table of Contents
xdiff_file_diff_binary -- Make binary diff of two files
xdiff_file_diff -- Make unified diff of two files
xdiff_file_merge3 -- Merge 3 files into one
xdiff_file_patch_binary -- Patch a file with a binary diff
xdiff_file_patch -- Patch a file with an unified diff
xdiff_string_diff_binary -- Make binary diff of two strings
xdiff_string_diff -- Make unified diff of two strings
xdiff_string_merge3 -- Merge 3 strings into one
xdiff_string_patch_binary -- Patch a string with a binary diff
xdiff_string_patch -- Patch a string with an unified diff

Prev | Home | Next
xattr_supported | Up | xdiff_file_diff_binary


xdiff_file_diff_binary

(PECL)

xdiff_file_diff_binary -- Make binary diff of two files

Description

bool xdiff_file_diff_binary ( string file1, string file2, string dest )

xdiff_file_diff_binary() makes binary diff of files file1 and file2 and stores result in file dest. This function works with both text and binary files. Resulting file is in binary format.

Note: Both files will be loaded into memory so ensure that your memory_limit is set high enough.

Returns TRUE on success or FALSE on failure.

Example 1. xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

&#60;?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?&#62;

See also xdiff_string_diff_binary().

Prev | Home | Next
xdiff Functions | Up | xdiff_file_diff


xdiff_file_diff

(PECL)

xdiff_file_diff -- Make unified diff of two files

Description

bool xdiff_file_diff ( string file1, string file2, string dest [, int context [, bool minimal]] )

xdiff_file_diff() makes unified diff of files file1 and file2 and stores result in file dest. context indicated how many lines of context you want to include in diff result. Set minimal to TRUE if you want to minimalize size of diff (can take a long time). Resulting file is human-readable.

Note: This function doesn't work well with binary files. To make diff of binary files use xdiff_file_diff_binary().

Returns TRUE on success or FALSE on failure.

Example 1. xdiff_file_diff() example

The following code makes unified diff of two php files.

&#60;?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?&#62;

See also xdiff_string_diff().

Prev | Home | Next
xdiff_file_diff_binary | Up | xdiff_file_merge3


xdiff_file_merge3

(PECL)

xdiff_file_merge3 -- Merge 3 files into one

Description

mixed xdiff_file_merge3 ( string file1, string file2, string file3, string dest )

xdiff_file_merge3() merges files file1, file2 and file3 into one and stores result in file dest.

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Example 1. xdiff_file_merge3() example

The following code merges three files into one.

&#60;?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
    echo "Rejects:\n";
    echo $errors;
}
?&#62;

See also xdiff_string_merge3().

Prev | Home | Next
xdiff_file_diff | Up | xdiff_file_patch_binary


xdiff_file_patch_binary

(PECL)

xdiff_file_patch_binary -- Patch a file with a binary diff

Description

bool xdiff_file_patch_binary ( string file, string patch, string dest )

xdiff_file_patch_binary() patches file file with binary patch in file patch and stores result in file dest.

Note: Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

Returns TRUE on success or FALSE on failure.

Example 1. xdiff_file_patch_binary() example

The following code applies binary diff to a file.

&#60;?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?&#62;

See also xdiff_string_patch_binary().

Prev | Home | Next
xdiff_file_merge3 | Up | xdiff_file_patch


xdiff_file_patch

(PECL)

xdiff_file_patch -- Patch a file with an unified diff

Description

mixed xdiff_file_patch ( string file, string patch, string dest [, int flags] )

xdiff_file_patch() patches file file with unified patch in file patch and stores result in file dest.

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Returns FALSE if an internal error happened, string with rejected chunks of patch or TRUE if patch has been successfully applied.

Example 1. xdiff_file_patch() example

The following code applies unified diff to a file.

&#60;?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?&#62;

Example 2. Patch reversing example

The following code reverses a patch.

&#60;?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?&#62;

See also xdiff_string_patch().

Prev | Home | Next
xdiff_file_patch_binary | Up | xdiff_string_diff_binary


xdiff_string_diff_binary

(PECL)

xdiff_string_diff_binary -- Make binary diff of two strings

Description

string xdiff_string_diff_binary ( string str1, string str2 )

xdiff_string_diff_binary() makes binary diff of strings str1 and str2.

Returns string with result or FALSE if an internal error happened.

See also xdiff_file_diff_binary().

Prev | Home | Next
xdiff_file_patch | Up | xdiff_string_diff


xdiff_string_diff

(PECL)

xdiff_string_diff -- Make unified diff of two strings

Description

string xdiff_string_diff ( string str1, string str2 [, int context [, bool minimal]] )

xdiff_string_diff() makes unified diff of strings str1 and str2. context indicated how many lines of context you want to include in diff result. Set minimal to TRUE if you want to minimalize size of diff (can take a long time).

Note: This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_diff_binary().

Returns string with result or FALSE if an internal error happened.

Example 1. xdiff_string_diff() example

The following code makes unified diff of two articles.

&#60;?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

?&#62;

See also xdiff_file_diff().

Prev | Home | Next
xdiff_string_diff_binary | Up | xdiff_string_merge3


xdiff_string_merge3

(PECL)

xdiff_string_merge3 -- Merge 3 strings into one

Description

mixed xdiff_string_merge3 ( string str1, string str2, string str3 [, string &error] )

xdiff_string_merge3() merges strings str1, str2 and str3 into one.

If error is passed then rejected parts are stored inside this variable.

Returns merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

See also xdiff_file_merge3().

Prev | Home | Next
xdiff_string_diff | Up | xdiff_string_patch_binary


xdiff_string_patch_binary

(PECL)

xdiff_string_patch_binary -- Patch a string with a binary diff

Description

string xdiff_string_patch_binary ( string str, string patch )

xdiff_string_patch_binary() patches string str with binary patch in string patch.

Returns a patched string.

See also xdiff_file_patch_binary().

Prev | Home | Next
xdiff_string_merge3 | Up | xdiff_string_patch


xdiff_string_patch

(PECL)

xdiff_string_patch -- Patch a string with an unified diff

Description

string xdiff_string_patch ( string str, string patch [, int flags [, string &error]] )

xdiff_string_patch() patches string str with unified patch in string patch.

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

If error is passed then rejected parts are stored inside this variable.

Example 1. xdiff_string_patch() example

The following code applies changes to some article.

&#60;?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
    echo "New article:\n";
    echo $new_article;
}

if (strlen($errors)) {
    echo "Rejects: \n";
    echo $errors;
}

?&#62;

Returns a patched string.

See also xdiff_file_patch().

Prev | Home | Next
xdiff_string_patch_binary | Up | XML Parser Functions


XML Parser Functions

PHP Manual
Prev Next

CLXXVII. XML Parser Functions

Introduction

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at http://www.w3.org/XML/.

This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.

This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.

Requirements

This extension uses an expat compat layer by default. It can use also expat, which can be found at http://www.jclark.com/xml/expat.html. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
A source RPM package of expat can be found at http://sourceforge.net/projects/expat/.

Installation

These functions are enabled by default, using the bundled expat library. You can disable XML support with --disable-xml. If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. In order you don't want to use the bundled expat library configure PHP --with-expat-dir=DIR, where DIR should point to the base installation directory of expat.

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

xml

The xml resource as returned by xml_parser_create() and xml_parser_create_ns() references an xml parser instance to be used with the functions provided by this extension.

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.

XML_ERROR_NONE (integer)

XML_ERROR_NO_MEMORY (integer)

XML_ERROR_SYNTAX (integer)

XML_ERROR_NO_ELEMENTS (integer)

XML_ERROR_INVALID_TOKEN (integer)

XML_ERROR_UNCLOSED_TOKEN (integer)

XML_ERROR_PARTIAL_CHAR (integer)

XML_ERROR_TAG_MISMATCH (integer)

XML_ERROR_DUPLICATE_ATTRIBUTE (integer)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)

XML_ERROR_PARAM_ENTITY_REF (integer)

XML_ERROR_UNDEFINED_ENTITY (integer)

XML_ERROR_RECURSIVE_ENTITY_REF (integer)

XML_ERROR_ASYNC_ENTITY (integer)

XML_ERROR_BAD_CHAR_REF (integer)

XML_ERROR_BINARY_ENTITY_REF (integer)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)

XML_ERROR_MISPLACED_XML_PI (integer)

XML_ERROR_UNKNOWN_ENCODING (integer)

XML_ERROR_INCORRECT_ENCODING (integer)

XML_ERROR_UNCLOSED_CDATA_SECTION (integer)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)

XML_OPTION_CASE_FOLDING (integer)

XML_OPTION_TARGET_ENCODING (integer)

XML_OPTION_SKIP_TAGSTART (integer)

XML_OPTION_SKIP_WHITE (integer)

Event Handlers

The XML event handlers defined are:

Table 1. Supported XML handlers

PHP function to set handler | Event description
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant.
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved.
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity.
xml_set_notation_decl_handler() | This handler is called for declaration of a notation.
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.

Case Folding

The element handler functions may get their element names case-folded. Case-folding is defined by the XML standard as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.

By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.

Error Codes

The following constants are defined for XML error codes (as returned by xml_parse()):

XML_ERROR_NONE
XML_ERROR_NO_MEMORY
XML_ERROR_SYNTAX
XML_ERROR_NO_ELEMENTS
XML_ERROR_INVALID_TOKEN
XML_ERROR_UNCLOSED_TOKEN
XML_ERROR_PARTIAL_CHAR
XML_ERROR_TAG_MISMATCH
XML_ERROR_DUPLICATE_ATTRIBUTE
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
XML_ERROR_PARAM_ENTITY_REF
XML_ERROR_UNDEFINED_ENTITY
XML_ERROR_RECURSIVE_ENTITY_REF
XML_ERROR_ASYNC_ENTITY
XML_ERROR_BAD_CHAR_REF
XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING

Character Encoding

PHP's XML extension supports the Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.

Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.

Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.

If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.

If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.

Examples

Here are some example PHP scripts parsing XML documents.

XML Element Structure Example

This first example displays the structure of the start elements in a document with indentation.

Example 1. Show XML Element Structure

&#60;?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;
    for ($i = 0; $i &#60; $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?&#62;

XML Tag Mapping Example

Example 2. Map XML to HTML

This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.

&#60;?php
$file = "data.xml";
$map_array = array(
    "BOLD"     =&#62; "B",
    "EMPHASIS" =&#62; "I",
    "LITERAL"  =&#62; "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "&#60;$map_array[$name]&#62;";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "&#60;/$map_array[$name]&#62;";
    }
}

function characterData($parser, $data)
{
    echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?&#62;

XML External Entity Example

This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.

XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)

Example 3. External Entity Example

&#60;?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // only trust local files owned by ourselves
    if (!eregi("^([a-z]+)://", $file)
        &#38;&#38; fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&#38;lt;&#60;font color=\"#0000cc\"&#62;$name&#60;/font&#62;";
    if (count($attribs)) {
        foreach ($attribs as $k =&#62; $v) {
            echo " &#60;font color=\"#009900\"&#62;$k&#60;/font&#62;=\"&#60;font
                   color=\"#990000\"&#62;$v&#60;/font&#62;\"";
        }
    }
    echo "&#38;gt;";
}

function endElement($parser, $name)
{
    echo "&#38;lt;/&#60;font color=\"#0000cc\"&#62;$name&#60;/font&#62;&#38;gt;";
}

function characterData($parser, $data)
{
    echo "&#60;b&#62;$data&#60;/b&#62;";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // If the parsed document is "trusted", we say it is safe
            // to execute PHP code inside it.  If not, display the code
            // instead.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Untrusted PHP code: &#60;i&#62;%s&#60;/i&#62;",
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data)
{
    if (substr($data, 0, 1) == "&#38;" &#38;&#38; substr($data, -1, 1) == ";") {
        printf('&#60;font color="#aa00aa"&#62;%s&#60;/font&#62;',
                htmlspecialchars($data));
    } else {
        printf('&#60;font size="-1"&#62;%s&#60;/font&#62;',
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Could not open entity %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file)
{
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");

    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("could not open XML input");
}

echo "&#60;pre&#62;";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "&#60;/pre&#62;";
echo "parse complete\n";
xml_parser_free($xml_parser);

?&#62;

Example 4. xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php echo 'Hi!  This is PHP version ' . phpversion(); ?>
  </para>
 </section>
</chapter>

This file is included from xmltest.xml:

Example 5. xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>

Table of Contents
utf8_decode -- Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
utf8_encode -- Encodes an ISO-8859-1 string to UTF-8
xml_error_string -- Get XML parser error string
xml_get_current_byte_index -- Get current byte index for an XML parser
xml_get_current_column_number -- Get current column number for an XML parser
xml_get_current_line_number -- Get current line number for an XML parser
xml_get_error_code -- Get XML parser error code
xml_parse_into_struct -- Parse XML data into an array structure
xml_parse -- Start parsing an XML document
xml_parser_create_ns -- Create an XML parser with namespace support
xml_parser_create -- Create an XML parser
xml_parser_free -- Free an XML parser
xml_parser_get_option -- Get options from an XML parser
xml_parser_set_option -- Set options in an XML parser
xml_set_character_data_handler -- Set up character data handler
xml_set_default_handler -- Set up default handler
xml_set_element_handler -- Set up start and end element handlers
xml_set_end_namespace_decl_handler -- Set up end namespace declaration handler
xml_set_external_entity_ref_handler -- Set up external entity reference handler
xml_set_notation_decl_handler -- Set up notation declaration handler
xml_set_object -- Use XML Parser within an object
xml_set_processing_instruction_handler -- Set up processing instruction (PI) handler
xml_set_start_namespace_decl_handler -- Set up start namespace declaration handler
xml_set_unparsed_entity_decl_handler -- Set up unparsed entity declaration handler

Prev | Home | Next
xdiff_string_patch | Up | utf8_decode


utf8_decode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

utf8_decode -- Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

Description

string utf8_decode ( string data )

This function decodes data, assumed to be UTF-8 encoded, to ISO-8859-1.

See also utf8_encode() for an explanation of UTF-8 encoding.

Prev | Home | Next
XML Parser Functions | Up | utf8_encode


utf8_encode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

utf8_encode -- Encodes an ISO-8859-1 string to UTF-8

Description

string utf8_encode ( string data )

This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicode for encoding wide character values into a byte stream. UTF-8 is transparent to plain ASCII characters, is self-synchronized (meaning it is possible for a program to figure out where in the bytestream characters start) and can be used with normal string comparison functions for sorting and such.PHP encodes UTF-8 characters in up to four bytes, like this:

Table 1. UTF-8 encoding

bytes | bits | representation
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Each b represents a bit that can be used to store character data.

Prev | Home | Next
utf8_decode | Up | xml_error_string


xml_error_string

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_error_string -- Get XML parser error string

Description

string xml_error_string ( int code )

Gets the XML parser error string associated with the given code.

Parameters

code

An error code from xml_get_error_code().

Return Values

Returns a string with a textual description of the error code, or FALSE if no description was found.

See Also

xml_get_error_code()

Prev | Home | Next
utf8_encode | Up | xml_get_current_byte_index


xml_get_current_byte_index

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_byte_index -- Get current byte index for an XML parser

Description

int xml_get_current_byte_index ( resource parser )

Gets the current byte index of the given XML parser.

Parameters

parser

A reference to the XML parser to get byte index from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).

Notes

Warning

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

See Also

xml_get_current_column_index()
xml_get_current_line_index()

Prev | Home | Next
xml_error_string | Up | xml_get_current_column_number


xml_get_current_column_number

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_column_number -- Get current column number for an XML parser

Description

int xml_get_current_column_number ( resource parser )

Gets the current column number of the given XML parser.

Parameters

parser

A reference to the XML parser to get column number from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

See Also

xml_get_current_byte_index()
xml_get_current_line_index()

Prev | Home | Next
xml_get_current_byte_index | Up | xml_get_current_line_number


xml_get_current_line_number

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_line_number -- Get current line number for an XML parser

Description

int xml_get_current_line_number ( resource parser )

Gets the current line number for the given XML parser.

Parameters

parser

A reference to the XML parser to get line number from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.

See Also

xml_get_current_column_index()
xml_get_current_byte_index()

Prev | Home | Next
xml_get_current_column_number | Up | xml_get_error_code


xml_get_error_code

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_error_code -- Get XML parser error code

Description

int xml_get_error_code ( resource parser )

Gets the XML parser error code.

Parameters

parser

A reference to the XML parser to get error code from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.

See Also

xml_error_string()

Prev | Home | Next
xml_get_current_line_number | Up | xml_parse_into_struct


xml_parse_into_struct

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

xml_parse_into_struct -- Parse XML data into an array structure

Description

int xml_parse_into_struct ( resource parser, string data, array &values [, array &index] )

This function parses an XML file into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.

Note: xml_parse_into_struct() returns 0 for failure and 1 for success. This is not the same as FALSE and TRUE, be careful with operators such as ===.

Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embedded inside a para tag, and then we parse this and print out the structures generated:

Example 1. xml_parse_into_struct() example

&#60;?php
$simple = "&#60;para&#62;&#60;note&#62;simple note&#60;/note&#62;&#60;/para&#62;";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?&#62;

When we run that code, the output will be:

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Vals array
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:

Example 2. moldb.xml - small database of molecular information

<?xml version="1.0"?>
<moldb>

  <molecule>
      <name>Alanine</name>
      <symbol>ala</symbol>
      <code>A</code>
      <type>hydrophobic</type>
  </molecule>

  <molecule>
      <name>Lysine</name>
      <symbol>lys</symbol>
      <code>K</code>
      <type>charged</type>
  </molecule>

</moldb>
And some code to parse the document and generate the appropriate objects:

Example 3. parsemoldb.php - parses moldb.xml into an array of molecular objects

&#60;?php

class AminoAcid {
    var $name;  // aa name
    var $symbol;    // three letter symbol
    var $code;  // one letter code
    var $type;  // hydrophobic, charged or neutral

    function AminoAcid ($aa)
    {
        foreach ($aa as $k=&#62;$v)
            $this-&#62;$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // read the XML database of aminoacids
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // loop through the structures
    foreach ($tags as $key=&#62;$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each molecule definition
            for ($i=0; $i &#60; count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i &#60; count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?&#62;
After executing parsemoldb.php, the variable $db contains an array of AminoAcid objects, and the output of the script confirms that:

** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

Prev | Home | Next
xml_get_error_code | Up | xml_parse


xml_parse

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parse -- Start parsing an XML document

Description

int xml_parse ( resource parser, string data [, bool is_final] )

xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.

Parameters

parser

A reference to the XML parser to use.

data

Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the is_final parameter is set and TRUE when the last data is parsed.

is_final

If set and TRUE, data is the last piece of data sent in this parse.

Return Values

Returns 1 on success or 0 on failure.

For unsuccessful parses, error information can be retrieved with
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() and
xml_get_current_byte_index().

Note: Entity errors are reported at the end of the data thus only if is_final is set and TRUE.

Prev | Home | Next
xml_parse_into_struct | Up | xml_parser_create_ns


xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5)

xml_parser_create_ns -- Create an XML parser with namespace support

Description

resource xml_parser_create_ns ( [string encoding [, string separator]] )

xml_parser_create_ns() creates a new XML parser with XML namespace support and returns a resource handle referencing it to be used by the other XML functions.

With a namespace aware parser tag parameters passed to the various handler functions will consist of namespace and tag name separated by the string specified in seperator or ':' by default.

The optional encoding specifies the character encoding for the input/output in PHP 4. Starting from PHP 5, the input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. In PHP 4, the default output encoding is the same as the input charset. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1, while in PHP 5.0.2 and upper is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

See also xml_parser_create(), and xml_parser_free().

Prev | Home | Next
xml_parse | Up | xml_parser_create


xml_parser_create

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_create -- Create an XML parser

Description

resource xml_parser_create ( [string encoding] )

xml_parser_create() creates a new XML parser and returns a resource handle referencing it to be used by the other XML functions.

The optional encoding specifies the character encoding for the input/output in PHP 4. Starting from PHP 5, the input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. In PHP 4, the default output encoding is the same as the input charset. If empty string is passed, the parser attempts to identify which encoding the document is encoded in by looking at the heading 3 or 4 bytes. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1, while in PHP 5.0.2 and upper is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

See also xml_parser_create_ns() and xml_parser_free().

Prev | Home | Next
xml_parser_create_ns | Up | xml_parser_free


xml_parser_free

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_free -- Free an XML parser

Description

bool xml_parser_free ( resource parser )

Frees the given XML parser.

Parameters

parser

A reference to the XML parser to free.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it frees the parser and returns TRUE.

Prev | Home | Next
xml_parser_create | Up | xml_parser_get_option


xml_parser_get_option

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_get_option -- Get options from an XML parser

Description

mixed xml_parser_get_option ( resource parser, int option )

Gets an option value from an XML parser.

Parameters

parser

A reference to the XML parser to get an option from.

option

Which option to fetch. XML_OPTION_CASE_FOLDING and XML_OPTION_TARGET_ENCODING are available. See xml_parser_set_option() for their description.

Return Values

This function returns FALSE if parser does not refer to a valid parser or if option isn't valid (generates also a E_WARNING). Else the option's value is returned.

Prev | Home | Next
xml_parser_free | Up | xml_parser_set_option


xml_parser_set_option

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_set_option -- Set options in an XML parser

Description

bool xml_parser_set_option ( resource parser, int option, mixed value )

parser

A reference to the XML parser to set an option in.

option

Which option to set. See below.

value

The option's new value.

This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.

The following options are available:

Table 1. XML parser options

Option constant | Data type | Description
XML_OPTION_CASE_FOLDING | integer | Controls whether case-folding is enabled for this XML parser. Enabled by default.
XML_OPTION_SKIP_TAGSTART | integer | Specify how many characters should be skipped in the beginning of a tag name.
XML_OPTION_SKIP_WHITE | integer | Whether to skip values consisting of whitespace characters.
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser.By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

Prev | Home | Next
xml_parser_get_option | Up | xml_set_character_data_handler


xml_set_character_data_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_character_data_handler -- Set up character data handler

Description

bool xml_set_character_data_handler ( resource parser, callback handler )

Sets the character data handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters: handler ( resource parser, string data )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

data

The second parameter, data, contains the character data as a string.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_parser_set_option | Up | xml_set_default_handler


xml_set_default_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_default_handler -- Set up default handler

Description

bool xml_set_default_handler ( resource parser, callback handler )

Sets the default handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters: handler ( resource parser, string data )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

data

The second parameter, data, contains the character data.This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_character_data_handler | Up | xml_set_element_handler


xml_set_element_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_element_handler -- Set up start and end element handlers

Description

bool xml_set_element_handler ( resource parser, callback start_element_handler, callback end_element_handler )

Sets the element handler functions for the XML parser parser. start_element_handler and end_element_handler are strings containing the names of functions that must exist when xml_parse() is called for parser.

The function named by start_element_handler must accept three parameters: start_element_handler ( resource parser, string name, array attribs )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

name

The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.

attribs

The third parameter, attribs, contains an associative array with the element's attributes (if any).The keys of this array are the attribute names, the values are the attribute values.Attribute names are case-folded on the same criteria as element names.Attribute values are not case-folded.

The original order of the attributes can be retrieved by walking through attribs the normal way, using each().The first key in the array was the first attribute, and so on.

The function named by end_element_handler must accept two parameters: end_element_handler ( resource parser, string name )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

name

The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handlers are set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_default_handler | Up | xml_set_end_namespace_decl_handler


xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_end_namespace_decl_handler -- Set up end namespace declaration handler

Description

bool xml_set_end_namespace_decl_handler ( resource parser, callback handler )

Warning

This function is currently not documented; only the argument list is available.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_element_handler | Up | xml_set_external_entity_ref_handler


xml_set_external_entity_ref_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_external_entity_ref_handler -- Set up external entity reference handler

Description

bool xml_set_external_entity_ref_handler ( resource parser, callback handler )

Sets the external entity reference handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept five parameters, and should return an integer value.If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING. handler ( resource parser, string open_entity_names, string base, string system_id, string public_id )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

open_entity_names

The second parameter, open_entity_names, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).

base

This is the base for resolving the system identifier (system_id) of the external entity.Currently this parameter will always be set to an empty string.

system_id

The fourth parameter, system_id, is the system identifier as specified in the entity declaration.

public_id

The fifth parameter, public_id, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_end_namespace_decl_handler | Up | xml_set_notation_decl_handler


xml_set_notation_decl_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_notation_decl_handler -- Set up notation declaration handler

Description

bool xml_set_notation_decl_handler ( resource parser, callback handler )

Sets the notation declaration handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

A notation declaration is part of the document's DTD and has the following format:

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
See section 4.7 of the XML 1.0 spec for the definition of notation declarations.

The function named by handler must accept five parameters: handler ( resource parser, string notation_name, string base, string system_id, string public_id )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

notation_name

This is the notation's name, as per the notation format described above.

base

This is the base for resolving the system identifier (system_id) of the notation declaration. Currently this parameter will always be set to an empty string.

system_id

System identifier of the external notation declaration.

public_id

Public identifier of the external notation declaration.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_external_entity_ref_handler | Up | xml_set_object


xml_set_object

(PHP 4, PHP 5)

xml_set_object -- Use XML Parser within an object

Description

bool xml_set_object ( resource parser, object &object )

This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.

Example 1. xml_set_object() example

&#60;?php
class xml  {
    var $parser;

    function xml()
    {
        $this-&#62;parser = xml_parser_create();

        xml_set_object($this-&#62;parser, $this);
        xml_set_element_handler($this-&#62;parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this-&#62;parser, "cdata");
    }

    function parse($data)
    {
        xml_parse($this-&#62;parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // end of class xml

$xml_parser = new xml();
$xml_parser-&#62;parse("&#60;A ID='hallo'&#62;PHP&#60;/A&#62;");
?&#62;

Prev | Home | Next
xml_set_notation_decl_handler | Up | xml_set_processing_instruction_handler


xml_set_processing_instruction_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_processing_instruction_handler -- Set up processing instruction (PI) handler

Description

bool xml_set_processing_instruction_handler ( resource parser, callback handler )

Sets the processing instruction (PI) handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

A processing instruction has the following format:

<?target
     data?>

You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents.If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.

The function named by handler must accept three parameters: handler ( resource parser, string target, string data )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

target

The second parameter, target, contains the PI target.

data

The third parameter, data, contains the PI data.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_object | Up | xml_set_start_namespace_decl_handler


xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_start_namespace_decl_handler -- Set up start namespace declaration handler

Description

bool xml_set_start_namespace_decl_handler ( resource parser, callback handler )

Warning

This function is currently not documented; only the argument list is available.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_processing_instruction_handler | Up | xml_set_unparsed_entity_decl_handler


xml_set_unparsed_entity_decl_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_unparsed_entity_decl_handler -- Set up unparsed entity declaration handler

Description

bool xml_set_unparsed_entity_decl_handler ( resource parser, callback handler )

Sets the unparsed entity declaration handler function for the XML parser parser.handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

This handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

See section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.

The function named by handler must accept six parameters: handler ( resource parser, string entity_name, string base, string system_id, string public_id, string notation_name )

parser

The first parameter, parser, is a reference to the XML parser calling the handler.

entity_name

The name of the entity that is about to be defined.

base

This is the base for resolving the system identifier (systemId) of the external entity.Currently this parameter will always be set to an empty string.

system_id

System identifier for the external entity.

public_id

Public identifier for the external entity.

notation_name

Name of the notation of this entity (see xml_set_notation_decl_handler()).

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

TRUE is returned if the handler is set up, FALSE if parser is not a parser.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Prev | Home | Next
xml_set_start_namespace_decl_handler | Up | XML-RPC Functions


XML-RPC Functions

PHP Manual
Prev Next

CLXXVIII. XML-RPC Functions

Introduction

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at http://www.xmlrpc.com/, and more documentation on this extension and its functions at http://xmlrpc-epi.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

No external libraries are needed to build this extension.

Installation

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. XML-RPC configuration options

Name | Default | Changeable | Changelog
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0.
xmlrpc_error_number | "0" | PHP_INI_ALL | Available since PHP 4.1.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
xmlrpc_decode_request -- Decodes XML into native PHP types
xmlrpc_decode -- Decodes XML into native PHP types
xmlrpc_encode_request -- Generates XML for a method request
xmlrpc_encode -- Generates XML for a PHP value
xmlrpc_get_type -- Gets xmlrpc type for a PHP value
xmlrpc_is_fault -- Determines if an array value represents an XMLRPC fault
xmlrpc_parse_method_descriptions -- Decodes XML into a list of method descriptions
xmlrpc_server_add_introspection_data -- Adds introspection documentation
xmlrpc_server_call_method -- Parses XML requests and call methods
xmlrpc_server_create -- Creates an xmlrpc server
xmlrpc_server_destroy -- Destroys server resources
xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentation
xmlrpc_server_register_method -- Register a PHP function to resource method matching method_name
xmlrpc_set_type -- Sets xmlrpc type, base64 or datetime, for a PHP string value

Prev | Home | Next
xml_set_unparsed_entity_decl_handler | Up | xmlrpc_decode_request


xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode_request -- Decodes XML into native PHP types

Description

mixed xmlrpc_decode_request ( string xml, string &method [, string encoding] )

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.

Prev | Home | Next
XML-RPC Functions | Up | xmlrpc_decode


xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode -- Decodes XML into native PHP types

Description

mixed xmlrpc_decode ( string xml [, string encoding] )

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

xml

XML response returned by XMLRPC method.

encoding

Input encoding supported by iconv (defaults to "iso-8859-1").

Return Values

Returns either an array, or an integer, or a string, or a boolean according to the response returned by the XMLRPC method.

Examples

See example by xmlrpc_encode_request().

See Also

xmlrpc_encode_request()
xmlrpc_is_fault()

Prev | Home | Next
xmlrpc_decode_request | Up | xmlrpc_encode_request


xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode_request -- Generates XML for a method request

Description

string xmlrpc_encode_request ( string method, mixed params [, array output_options] )

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

method

Name of the method to call.

params

Method parameters compatible with method signature.

output_options

Array specifying output options may contain (default values are emphasised):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

Return Values

Returns a string containing the XML representation of the request.

Examples

Example 1. XMLRPC client functions example

&#60;?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' =&#62; array(
    'method' =&#62; "POST",
    'header' =&#62; "Content-Type: text/xml",
    'content' =&#62; $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if (xmlrpc_is_fault($response)) {
    trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
    print_r($response);
}
?&#62;

See Also

stream_context_create()
file_get_contents()
xmlrpc_decode()

Prev | Home | Next
xmlrpc_decode | Up | xmlrpc_encode


xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode -- Generates XML for a PHP value

Description

string xmlrpc_encode ( mixed value )

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.

Prev | Home | Next
xmlrpc_encode_request | Up | xmlrpc_get_type


xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_get_type -- Gets xmlrpc type for a PHP value

Description

string xmlrpc_get_type ( mixed value )

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.

This function is especially useful for base64 and datetime strings.

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
xmlrpc_encode | Up | xmlrpc_is_fault


xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5)

xmlrpc_is_fault -- Determines if an array value represents an XMLRPC fault

Description

bool xmlrpc_is_fault ( array arg )

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

arg

Array returned by xmlrpc_decode().

Return Values

Returns TRUE if the argument means fault, FALSE otherwise. Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

Examples

See example by xmlrpc_encode_request().

See Also

xmlrpc_decode()

Prev | Home | Next
xmlrpc_get_type | Up | xmlrpc_parse_method_descriptions


xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_parse_method_descriptions -- Decodes XML into a list of method descriptions

Description

array xmlrpc_parse_method_descriptions ( string xml )

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.

Prev | Home | Next
xmlrpc_is_fault | Up | xmlrpc_server_add_introspection_data


xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_add_introspection_data -- Adds introspection documentation

Description

int xmlrpc_server_add_introspection_data ( resource server, array desc )

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.

Prev | Home | Next
xmlrpc_parse_method_descriptions | Up | xmlrpc_server_call_method


xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_call_method -- Parses XML requests and call methods

Description

string xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options] )

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.

Prev | Home | Next
xmlrpc_server_add_introspection_data | Up | xmlrpc_server_create


xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_create -- Creates an xmlrpc server

Description

resource xmlrpc_server_create ( void )

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.

Prev | Home | Next
xmlrpc_server_call_method | Up | xmlrpc_server_destroy


xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_destroy -- Destroys server resources

Description

int xmlrpc_server_destroy ( resource server )

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.

Prev | Home | Next
xmlrpc_server_create | Up | xmlrpc_server_register_introspection_callback


xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentation

Description

bool xmlrpc_server_register_introspection_callback ( resource server, string function )

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.

Prev | Home | Next
xmlrpc_server_destroy | Up | xmlrpc_server_register_method


xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_method -- Register a PHP function to resource method matching method_name

Description

bool xmlrpc_server_register_method ( resource server, string method_name, string function )

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.

Prev | Home | Next
xmlrpc_server_register_introspection_callback | Up | xmlrpc_set_type


xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_set_type -- Sets xmlrpc type, base64 or datetime, for a PHP string value

Description

bool xmlrpc_set_type ( string &value, string type )

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.

Prev | Home | Next
xmlrpc_server_register_method | Up | XMLReader functions


XSL functions

PHP Manual
Prev Next

CLXXXI. XSL functions

Introduction

The XSL extension implements the XSL standard, performing XSLT transformations using the libxslt library

Requirements

This extension uses libxslt which can be found at http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

Installation

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory.

Predefined Classes

XSLTProcessor

Constructor

  • XSLTProcessor::__construct - construct a new XSLTProcessor object

Methods

  • XSLTProcessor::getParameter - Get value of a parameter

  • XSLTProcessor::hasExsltSupport - Determine if PHP has EXSLT support

  • XSLTProcessor::importStylesheet - Import stylesheet

  • XSLTProcessor::registerPHPFunctions - Enables the ability to use PHP functions as XSLT functions

  • XSLTProcessor::removeParameter - Remove parameter

  • XSLTProcessor::setParameter - Set value for a parameter

  • XSLTProcessor::transformToDoc - Transform to DOMDocument

  • XSLTProcessor::transformToURI - Transform to URI

  • XSLTProcessor::transformToXML - Transform to XML

Examples

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Example 1. collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Example 2. collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>

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.

XSL_CLONE_AUTO (integer)

XSL_CLONE_NEVER (integer)

XSL_CLONE_ALWAYS (integer)

LIBXSLT_VERSION (integer)

libxslt version like 10117. Available as of PHP 5.1.2.

LIBXSLT_DOTTED_VERSION (string)

libxslt version like 1.1.17. Available as of PHP 5.1.2.

LIBEXSLT_VERSION (integer)

libexslt version like 813. Available as of PHP 5.1.2.

LIBEXSLT_DOTTED_VERSION (string)

libexslt version like 1.1.17. Available as of PHP 5.1.2.

Table of Contents
XSLTProcessor::__construct -- Creates a new XSLTProcessor object
XSLTProcessor::getParameter -- Get value of a parameter
XSLTProcessor::hasExsltSupport -- Determine if PHP has EXSLT support
XSLTProcessor::importStylesheet -- Import stylesheet
XSLTProcessor::registerPHPFunctions -- Enables the ability to use PHP functions as XSLT functions
XSLTProcessor::removeParameter -- Remove parameter
XSLTProcessor::setParameter -- Set value for a parameter
XSLTProcessor::transformToDoc -- Transform to a DOMDocument
XSLTProcessor::transformToURI -- Transform to URI
XSLTProcessor::transformToXML -- Transform to XML

Prev | Home | Next
XMLWriter::writeRaw | Up | XSLTProcessor::__construct


XSLTProcessor::__construct

(no version information, might be only in CVS)

XSLTProcessor::__construct -- Creates a new XSLTProcessor object

Description

class XSLTProcessor {

__construct ( (void); )

}

Creates a new XSLTProcessor object.

Examples

Example 1. Creating an XSLTProcessor

&#60;?php

$doc = new DOMDocument();
$xsl = new XSLTProcessor();

$doc-&#62;load($xsl_filename);
$xsl-&#62;importStyleSheet($doc);

$doc-&#62;load($xml_filename);
echo $xsl-&#62;transformToXML($doc);

?&#62;

Prev | Home | Next
XSL functions | Up | XSLTProcessor::getParameter


XSLTProcessor::getParameter

(no version information, might be only in CVS)

XSLTProcessor::getParameter -- Get value of a parameter

Description

class XSLTProcessor {

string getParameter ( string namespaceURI, string localName )

}

Gets a parameter if previously set by XSLTProcessor::setParameter.

Parameters

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Return Values

The value of the parameter or NULL if it's not set.

See Also

XSLTProcessor::setParameter
XSLTProcessor::removeParameter

Prev | Home | Next
XSLTProcessor::__construct | Up | XSLTProcessor::hasExsltSupport


XSLTProcessor::hasExsltSupport

(no version information, might be only in CVS)

XSLTProcessor::hasExsltSupport -- Determine if PHP has EXSLT support

Description

class XSLTProcessor {

bool hasExsltSupport ( void )

}

This method determine if PHP was built with the EXSLT library.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Testing EXSLT support

&#60;?php

$proc = new XSLTProcessor;
if (!$proc-&#62;hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?&#62;

Prev | Home | Next
XSLTProcessor::getParameter | Up | XSLTProcessor::importStylesheet


XSLTProcessor::importStylesheet

(no version information, might be only in CVS)

XSLTProcessor::importStylesheet -- Import stylesheet

Description

class XSLTProcessor {

void importStylesheet ( DOMDocument stylesheet )

}

This method import the stylesheet into the XSLTProcessor for transformations.

Parameters

stylesheet

The imported style sheet as a DOMDocument object.

Return Values

No value is returned.

Prev | Home | Next
XSLTProcessor::hasExsltSupport | Up | XSLTProcessor::registerPHPFunctions


XSLTProcessor::registerPHPFunctions

(no version information, might be only in CVS)

XSLTProcessor::registerPHPFunctions -- Enables the ability to use PHP functions as XSLT functions

Description

class XSLTProcessor {

void registerPHPFunctions ( [mixed restrict] )

}

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Parameters

restrict

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

Return Values

No value is returned.

Examples

Example 1. Simple PHP Function call from a stylesheet

&#60;?php
$xml = &#60;&#60;&#60;EOB
&#60;allusers&#62;
 &#60;user&#62;
  &#60;uid&#62;bob&#60;/uid&#62;
 &#60;/user&#62;
 &#60;user&#62;
  &#60;uid&#62;joe&#60;/uid&#62;
 &#60;/user&#62;
&#60;/allusers&#62;
EOB;
$xsl = &#60;&#60;&#60;EOB
&#60;?xml version="1.0" encoding="UTF-8"?&#62;
&#60;xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl"&#62;
&#60;xsl:output method="html" encoding="utf-8" indent="yes"/&#62;
 &#60;xsl:template match="allusers"&#62;
  &#60;html&#62;&#60;body&#62;
    &#60;h2&#62;Users&#60;/h2&#62;
    &#60;table&#62;
    &#60;xsl:for-each select="user"&#62;
      &#60;tr&#62;&#60;td&#62;
        &#60;xsl:value-of
             select="php:function('ucfirst',string(uid))"/&#62;
      &#60;/td&#62;&#60;/tr&#62;
    &#60;/xsl:for-each&#62;
    &#60;/table&#62;
  &#60;/body&#62;&#60;/html&#62;
 &#60;/xsl:template&#62;
&#60;/xsl:stylesheet&#62;
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc-&#62;registerPHPFunctions();
$proc-&#62;importStyleSheet($xsldoc);
echo $proc-&#62;transformToXML($xmldoc);
?&#62;

ChangeLog

Version | Description
5.1.0 | The restrict parameter was added.

Prev | Home | Next
XSLTProcessor::importStylesheet | Up | XSLTProcessor::removeParameter


XSLTProcessor::removeParameter

(no version information, might be only in CVS)

XSLTProcessor::removeParameter -- Remove parameter

Description

class XSLTProcessor {

bool removeParameter ( string namespaceURI, string localName )

}

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

Parameters

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XSLTProcessor::setParameter
XSLTProcessor::getParameter

Prev | Home | Next
XSLTProcessor::registerPHPFunctions | Up | XSLTProcessor::setParameter


XSLTProcessor::setParameter

(no version information, might be only in CVS)

XSLTProcessor::setParameter -- Set value for a parameter

Description

class XSLTProcessor {

bool setParameter ( string namespace, string name, string value )

}class XSLTProcessor {

bool setParameter ( string namespace, array options )

}

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

Parameters

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs. This syntax is available since PHP 5.1.0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Changing the owner before the transformation

&#60;?php

$collections = array(
    'Marc Rutkowski' =&#62; 'marc',
    'Olivier Parmentier' =&#62; 'olivier'
);

$xsl = new DOMDocument;
$xsl-&#62;load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc-&#62;importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name =&#62; $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml-&#62;load('collection_' . $file . '.xml');

    $proc-&#62;setParameter('', 'owner', $name);
    $proc-&#62;transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?&#62;

See Also

XSLTProcessor::getParameter
XSLTProcessor::removeParameter

Prev | Home | Next
XSLTProcessor::removeParameter | Up | XSLTProcessor::transformToDoc


XSLTProcessor::transformToDoc

(no version information, might be only in CVS)

XSLTProcessor::transformToDoc -- Transform to a DOMDocument

Description

class XSLTProcessor {

DOMDocument transformToDoc ( DOMNode doc )

}

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor::importStylesheet method.

Parameters

doc

The node to be transformed.

Return Values

The resulting DOMDocument or FALSE on error.

Examples

Example 1. Transforming to a DOMDocument

&#60;?php

// Load the XML source
$xml = new DOMDocument;
$xml-&#62;load('collection.xml');

$xsl = new DOMDocument;
$xsl-&#62;load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc-&#62;importStyleSheet($xsl); // attach the xsl rules

echo trim($proc-&#62;transformToDoc($xml)-&#62;firstChild-&#62;wholeText);

?&#62;

The above example will output:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

See Also

XSLTProcessor::transformToURI
XSLTProcessor::transformToXML

Prev | Home | Next
XSLTProcessor::setParameter | Up | XSLTProcessor::transformToURI


XSLTProcessor::transformToURI

(no version information, might be only in CVS)

XSLTProcessor::transformToURI -- Transform to URI

Description

class XSLTProcessor {

int transformToURI ( DOMDocument doc, string uri )

}

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet method.

Parameters

doc

The transformed document.

uri

Return Values

Returns the number of bytes written or FALSE if an error occurred.

Examples

Example 1. Transforming to a HTML file

&#60;?php

// Load the XML source
$xml = new DOMDocument;
$xml-&#62;load('collection.xml');

$xsl = new DOMDocument;
$xsl-&#62;load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc-&#62;importStyleSheet($xsl); // attach the xsl rules

$proc-&#62;transformToURI($xml, 'file:///tmp/out.html');

?&#62;

See Also

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML

Prev | Home | Next
XSLTProcessor::transformToDoc | Up | XSLTProcessor::transformToXML


XSLTProcessor::transformToXML

(no version information, might be only in CVS)

XSLTProcessor::transformToXML -- Transform to XML

Description

class XSLTProcessor {

string transformToXML ( DOMDocument doc )

}

Transforms the source node to a string applying the stylesheet given by the XSLTProcessor::importStylesheet method.

Parameters

doc

The transformed document.

Return Values

The result of the transformation as a string or FALSE on error.

Examples

Example 1. Transforming to a string

&#60;?php

// Load the XML source
$xml = new DOMDocument;
$xml-&#62;load('collection.xml');

$xsl = new DOMDocument;
$xsl-&#62;load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc-&#62;importStyleSheet($xsl); // attach the xsl rules

echo $proc-&#62;transformToXML($xml);

?&#62;

The above example will output:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

See Also

XSLTProcessor::transformToDoc
XSLTProcessor::transformToURI

Prev | Home | Next
XSLTProcessor::transformToURI | Up | XSLT Functions


XSLT Functions

PHP Manual
Prev Next

CLXXXII. XSLT Functions

Introduction

This PHP extension provides a processor independent API to XSLT transformations. Currently this extension only supports the Sablotron library from the Ginger Alliance. Support is planned for other libraries, such as the Xalan library or the libxslt library.

XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML documents into other XML documents. It is a standard defined by The World Wide Web Consortium (W3C). Information about XSLT and related technologies can be found at http://www.w3.org/TR/xslt.

Note: This extension is different than the sablotron extension distributed with versions of PHP prior to PHP 4.1, currently only the new XSLT extension in PHP 4.1 is supported. If you need support for the old extension, please ask your questions on the PHP mailing lists.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Note: If you need xslt support with PHP 5 you can use the XSL extension.

Requirements

This extension uses Sablotron and expat, which can both be found at http://www.gingerall.org/sablotron.html. Binaries are provided as well as source.

Installation

On Unix, run configure with the --enable-xslt --with-xslt-sablot options. The Sablotron library should be installed somewhere your compiler can find it.

Make sure you have the same libraries linked to the Sablotron library as those, which are linked with PHP. The configuration options: --with-expat-dir=DIR --with-iconv-dir=DIR are there to help you specify them. When asking for support, always mention these directives, and whether there are other versions of those libraries installed on your system somewhere. Naturally, provide all the version numbers.

Caution

Be sure your Sablot library is linked to -lstdc++ as otherwise your configure will fail, or PHP will fail to run or load.

JavaScript E-XSLT support: If you compiled Sablotron with JavaScript support, you must specify the option: --with-sablot-js=DIR.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy several files from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). For PHP <= 4.2.0 copy sablot.dll and expat.dll to your SYSTEM32 folder. For PHP >= 4.2.1 copy sablot.dll, expat.dll and iconv.dll to your SYSTEM32 folder.

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.

XSLT_OPT_SILENT (integer)

Drop all logging and error reporting. This is a generic option for all backends that may be added in the future.

XSLT_SABOPT_PARSE_PUBLIC_ENTITIES (integer)

Tell Sablotron to parse public entities. By default this has been turned off.

XSLT_SABOPT_DISABLE_ADDING_META (integer)

Do not add the meta tag "Content-Type" for HTML output. The default is set during compilation of Sablotron.

XSLT_SABOPT_DISABLE_STRIPPING (integer)

Suppress the whitespace stripping (on data files only).

XSLT_SABOPT_IGNORE_DOC_NOT_FOUND (integer)

Consider unresolved documents (the document() function) non-lethal.

XSLT_SABOPT_FILES_TO_HANDLER (integer)

XSLT_ERR_UNSUPPORTED_SCHEME (integer)

Error return code, for scheme handlers.

Table of Contents
xslt_backend_info -- Returns the information on the compilation settings of the backend
xslt_backend_name -- Returns the name of the backend
xslt_backend_version -- Returns the version number of Sablotron
xslt_create -- Create a new XSLT processor
xslt_errno -- Returns an error number
xslt_error -- Returns an error string
xslt_free -- Free XSLT processor
xslt_getopt -- Get options on a given xsl processor
xslt_process -- Perform an XSLT transformation
xslt_set_base -- Set the base URI for all XSLT transformations
xslt_set_encoding -- Set the encoding for the parsing of XML documents
xslt_set_error_handler -- Set an error handler for a XSLT processor
xslt_set_log -- Set the log file to write log messages to
xslt_set_object -- Sets the object in which to resolve callback functions
xslt_set_sax_handler -- Set SAX handlers for a XSLT processor
xslt_set_sax_handlers -- Set the SAX handlers to be called when the XML document gets processed
xslt_set_scheme_handler -- Set Scheme handlers for a XSLT processor
xslt_set_scheme_handlers -- Set the scheme handlers for the XSLT processor
xslt_setopt -- Set options on a given xsl processor

Prev | Home | Next
XSLTProcessor::transformToXML | Up | xslt_backend_info


xslt_backend_info

(PHP 4 >= 4.3.0, PECL)

xslt_backend_info -- Returns the information on the compilation settings of the backend

Description

string xslt_backend_info ( void )

xslt_backend_info() returns a string with information about the compilation setting of the backend or an error string when no information available.

See Also

xslt_backend_name() and xslt_backend_version().

Prev | Home | Next
XSLT Functions | Up | xslt_backend_name


xslt_backend_name

(PHP 4 >= 4.3.0, PECL)

xslt_backend_name -- Returns the name of the backend

Description

string xslt_backend_name ( void )

xslt_backend_name() will always return Sablotron.

Examples

Example 1. xslt_backend_name() example

&#60;?php

echo xslt_backend_name(); // Sablotron

?&#62;

See Also

xslt_backend_info() and xslt_backend_version().

Prev | Home | Next
xslt_backend_info | Up | xslt_backend_version


xslt_backend_version

(PHP 4 >= 4.3.0, PECL)

xslt_backend_version -- Returns the version number of Sablotron

Description

string xslt_backend_version ( void )

xslt_backend_version() returns the version number of Sablotron if available, FALSE otherwise.

Examples

Example 1. xslt_backend_version() example

&#60;?php

echo xslt_backend_version(); // 0.98 for example

?&#62;

See Also

xslt_backend_name() and xslt_backend_info().

Prev | Home | Next
xslt_backend_name | Up | xslt_create


xslt_create

(PHP 4 >= 4.0.3, PECL)

xslt_create -- Create a new XSLT processor

Description

resource xslt_create ( void )

Create and return a new XSLT processor resource for manipulation by the other XSLT functions.

Examples

Example 1. xslt_create() example

&#60;?php
function xml2html($xmldata, $xsl)
{
    /* $xmldata -&#62; your XML */
    /* $xsl -&#62; XSLT file */

    $path = 'include';
    $arguments = array('/_xml' =&#62; $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', "$path/$xsl", NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?&#62;

See Also

xslt_free().

Prev | Home | Next
xslt_backend_version | Up | xslt_errno


xslt_errno

(PHP 4 >= 4.0.3, PECL)

xslt_errno -- Returns an error number

Description

int xslt_errno ( resource xh )

Returns an error code describing the last error that occurred on the passed XSLT processor.

See Also

xslt_error().

Prev | Home | Next
xslt_create | Up | xslt_error


xslt_error

(PHP 4 >= 4.0.3, PECL)

xslt_error -- Returns an error string

Description

string xslt_error ( resource xh )

Returns a string describing the last error that occurred on the passed XSLT processor.

Examples

Example 1. Handling errors using the xslt_error() and xslt_errno() functions.

&#60;?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result) {
    die(sprintf("Cannot process XSLT document [%d]: %s",
                xslt_errno($xh), xslt_error($xh)));
}

echo $result;

xslt_free($xh);
?&#62;

See Also

xslt_errno().

Prev | Home | Next
xslt_errno | Up | xslt_free


xslt_free

(PHP 4 >= 4.0.3, PECL)

xslt_free -- Free XSLT processor

Description

void xslt_free ( resource xh )

Free the XSLT processor identified by the given handle.

See Also

xslt_create()

Prev | Home | Next
xslt_error | Up | xslt_getopt


xslt_getopt

(PHP 4 >= 4.3.0, PECL)

xslt_getopt -- Get options on a given xsl processor

Description

int xslt_getopt ( resource processor )

xslt_getopt() returns the options on the given processor.

See Also

xslt_setopt().

Prev | Home | Next
xslt_free | Up | xslt_process


xslt_process

(PHP 4 >= 4.0.3, PECL)

xslt_process -- Perform an XSLT transformation

Description

mixed xslt_process ( resource xh, string xmlcontainer, string xslcontainer [, string resultcontainer [, array arguments [, array parameters]]] )

The xslt_process() function is the crux of the new XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source - the containers. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports). The input containers default to a filename 'containing' the document to be processed. The result container defaults to a filename for the transformed document. If the result container is not specified - i.e. NULL - than the result is returned.

Warning

As of PHP 4.0.6, this function no longer takes XML strings in xmlcontainer or xslcontainer. Passing a string containing XML to either of these parameters will result in a segmentation fault in Sablotron versions up to and including version 0.95.

Containers can also be set via the arguments array (see below).

The simplest type of transformation with the xslt_process() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with sablotron is really quite easy...

Example 1. Using the xslt_process() to transform an XML file and a XSL file to a new XML file

&#60;?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
if (xslt_process($xh, 'sample.xml', 'sample.xsl', 'result.xml')) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into result.xml";
    echo ", result.xml has the following contents\n&#60;br /&#62;\n";
    echo "&#60;pre&#62;\n";
    readfile('result.xml');
    echo "&#60;/pre&#62;\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  result.xml the reason is that " . xslt_error($xh) . " and the ";
    echo "error code is " . xslt_errno($xh);
}

xslt_free($xh);

?&#62;

While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...

Example 2. Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data

&#60;?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document, returning the result into the $result variable
$result = xslt_process($xh, 'sample.xml', 'sample.xsl');
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n&#60;br /&#62;\n";
    echo "&#60;pre&#62;\n";
    echo $result;
    echo "&#60;/pre&#62;\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh);
    echo " and the error code is " . xslt_errno($xh);
}

xslt_free($xh);

?&#62;

The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then substituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.

Example 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data

&#60;?php
// $xml and $xsl contain the XML and XSL data

$arguments = array(
     '/_xml' =&#62; $xml,
     '/_xsl' =&#62; $xsl
);

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n&#60;br /&#62;\n";
    echo "&#60;pre&#62;\n";
    echo $result;
    echo "&#60;/pre&#62;\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh);
    echo " and the error code is " . xslt_errno($xh);
}
xslt_free($xh);
?&#62;

Finally, the last argument to the xslt_process() function represents an array for any top-level parameters that you want to pass to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction. The parameters must be UTF-8 encoded and their values will be interpreted as strings by the Sablotron processor. In other words - you cannot pass node-sets as parameters to the XSLT document.

Example 4. Passing PHP variables to XSL files

&#60;?php

// XML string
$xml = '&#60;?xml version="1.0"?&#62;
&#60;para&#62;
 change me
&#60;/para&#62;';

// XSL string
$xsl = '
&#60;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&#62;
&#60;xsl:output method="html" encoding="ISO-8859-1" indent="no"
 omit-xml-declaration="yes"  media-type="text/html"/&#62;
 &#60;xsl:param name="myvar"/&#62;
 &#60;xsl:param name="mynode"/&#62;
 &#60;xsl:template match="/"&#62;
My PHP variable : &#60;xsl:value-of select="$myvar"/&#62;&#60;br /&#62;
My node set : &#60;xsl:value-of select="$mynode"/&#62;
 &#60;/xsl:template&#62;
&#60;/xsl:stylesheet&#62;';

$xh = xslt_create();

// the second parameter will be interpreted as a string
$parameters = array (
  'myvar' =&#62; 'test',
  'mynode' =&#62; '&#60;foo&#62;bar&#60;/foo&#62;'
);

$arguments = array (
  '/_xml' =&#62; $xml,
  '/_xsl' =&#62; $xsl
);

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments, $parameters);

?&#62;

The above example will output:

My PHP variable : test<br>
My node set : &lt;foo&gt;bar&lt;/foo&gt;

Note: Please note that file:// is needed in front of path if you use Windows.

Prev | Home | Next
xslt_getopt | Up | xslt_set_base


xslt_set_base

(PHP 4 >= 4.0.5, PECL)

xslt_set_base -- Set the base URI for all XSLT transformations

Description

void xslt_set_base ( resource xh, string uri )

Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve document() and other commands which access external resources. It is also used to resolve URIs for the <xsl:include> and <xsl:import> elements.

As of 4.3, the default base URI is the directory of the executing script. In effect, it is the directory name value of the __FILE__ constant. Prior to 4.3, the default base URI was less predictable.

Note: Please note that file:// is needed in front of path if you use Windows.

Prev | Home | Next
xslt_process | Up | xslt_set_encoding


xslt_set_encoding

(PHP 4 >= 4.0.5, PECL)

xslt_set_encoding -- Set the encoding for the parsing of XML documents

Description

void xslt_set_encoding ( resource xh, string encoding )

Set the output encoding for the XSLT transformations. When using the Sablotron backend, this option is only available when you compile Sablotron with encoding support.

Prev | Home | Next
xslt_set_base | Up | xslt_set_error_handler


xslt_set_error_handler

(PHP 4 >= 4.0.4, PECL)

xslt_set_error_handler -- Set an error handler for a XSLT processor

Description

void xslt_set_error_handler ( resource xh, mixed handler )

Set an error handler function for the XSLT processor given by xh, this function will be called whenever an error occurs in the XSLT transformation (this function is also called for notices).

The user function needs to accept four parameters: the XSLT processor, the error level, the error code and an array of messages. The function can be shown as: error_handler ( resource xh, int error_level, int error_code, array messages )

Examples

Example 1. xslt_set_error_handler() Example

&#60;?php

// Our XSLT error handler
function xslt_error_handler($handler, $errno, $level, $info)
{
  // for now, let's just see the arguments
  var_dump(func_get_args());
}

// XML content :
$xml='&#60;?xml version="1.0"?&#62;
&#60;para&#62;
 oops, I misspelled the closing tag
&#60;/pata&#62;';

// XSL content :
$xsl='&#60;?xml version="1.0"?&#62;
&#60;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&#62;
&#60;xsl:template match="/"&#62;
   &#60;strong&#62;&#60;xsl:value-of select="para"/&#62;&#60;/strong&#62;
&#60;/xsl:template&#62;
&#60;/xsl:stylesheet&#62;';

$xh = xslt_create();

xslt_set_error_handler($xh, "xslt_error_handler");

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl',
                  NULL, array("/_xml" =&#62; $xml, "/_xsl" =&#62; $xsl));

?&#62;

The above example will output something similar to:

array(4) {
  [0]=>
  resource(1) of type (XSLT Processor)
  [1]=>
  int(3)
  [2]=>
  int(0)
  [3]=>
  array(6) {
    ["msgtype"]=>
    string(5) "error"
    ["code"]=>
    string(1) "2"
    ["module"]=>
    string(9) "Sablotron"
    ["URI"]=>
    string(9) "arg:/_xml"
    ["line"]=>
    string(1) "4"
    ["msg"]=>
    string(34) "XML parser error 7: mismatched tag"
  }
}

See Also

xslt_set_object() if you want to use an object method as handler.

Prev | Home | Next
xslt_set_encoding | Up | xslt_set_log


xslt_set_log

(PHP 4 >= 4.0.6, PECL)

xslt_set_log -- Set the log file to write log messages to

Description

void xslt_set_log ( resource xh [, mixed log] )

xh

A reference to the XSLT parser.

log

This parameter is either a boolean value which toggles logging on and off, or a string containing the logfile in which log errors too.

This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are different than error messages, in that log messages are not actually error messages but rather messages related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes wrong.

By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a boolean parameter which enables logging, then if you want to set the log file to debug to, you must then pass it a string containing the filename.

Note: Please note that file:// is needed in front of path if you use Windows.

Examples

Example 1. Using the XSLT Logging features

&#60;?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . '/myfile.log');

$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
echo $result;

xslt_free($xh);
?&#62;

Prev | Home | Next
xslt_set_error_handler | Up | xslt_set_object


xslt_set_object

(PHP 4 >= 4.3.0, PECL)

xslt_set_object -- Sets the object in which to resolve callback functions

Description

bool xslt_set_object ( resource processor, object &obj )

This function allows to use the processor inside an object and to resolve all callback functions in it.

The callback functions can be declared with xml_set_sax_handlers(), xslt_set_scheme_handlers() or xslt_set_error_handler() and are assumed to be methods of object.

Examples

Example 1. Using your own error handler as a method

&#60;?php

class my_xslt_processor {

    var $_xh; // our XSLT processor

    function my_xslt_processor()
    {
        $this-&#62;_xh = xslt_create();

        // Make $this object the callback resolver
        xslt_set_object($this-&#62;_xh, $this);

        // Let's handle the errors
        xslt_set_error_handler($this-&#62;_xh, "my_xslt_error_handler");
    }

    function my_xslt_error_handler($handler, $errno, $level, $info)
    {
        // for now, let's just see the arguments
        var_dump(func_get_args());
    }
}

?&#62;

Prev | Home | Next
xslt_set_log | Up | xslt_set_sax_handler


xslt_set_sax_handler

(4.0.3 - 4.0.6 only)

xslt_set_sax_handler -- Set SAX handlers for a XSLT processor

Description

void xslt_set_sax_handler ( resource xh, array handlers )

Set SAX handlers on the resource handle given by xh. SAX handlers should be a two dimensional array with the format (all top level elements are optional):

array(
[document] =&#62;
    array(
        start document handler,
        end document handler
    ),
[element] =&#62;
    array(
        start element handler,
        end element handler
    ),
[namespace] =&#62;
    array(
        start namespace handler,
        end namespace handler
    ),
[comment] =&#62; comment handler,
[pi] =&#62; processing instruction handler,
[character] =&#62; character data handler
)

Prev | Home | Next
xslt_set_object | Up | xslt_set_sax_handlers


xslt_set_sax_handlers

(PHP 4 >= 4.0.6, PECL)

xslt_set_sax_handlers -- Set the SAX handlers to be called when the XML document gets processed

Description

void xslt_set_sax_handlers ( resource processor, array handlers )

xslt_set_sax_handlers() registers the SAX handlers for the document, given a XSLT processor resource.

handlers should be an array in the following format:

&#60;?php

$handlers = array(

  "document" =&#62; array(
    "start_doc",
    "end_doc"),

  "element"  =&#62; array(
    "start_element",
    "end_element"),

  "namespace" =&#62; array(
    "start_namespace",
    "end_namespace"),

  "comment"   =&#62; "comment",

  "pi"        =&#62; "pi",

  "character" =&#62; "characters"

);
?&#62;

Where the functions follow the syntax described for the scheme handler functions.

Note: The given array does not need to contain all of the different sax handler elements (although it can), but it only needs to conform to "handler" => "function" format described above.

Each of the individual SAX handler functions are in the format below:

  • start_doc ( resource processor )

  • end_doc ( resource processor )

  • start_element ( resource processor, string name, array attributes )

  • end_element ( resource processor, string name )

  • start_namespace ( resource processor, string prefix, string uri )

  • end_namespace ( resource processor, string prefix )

  • comment ( resource processor, string contents )

  • pi ( resource processor, string target, string contents )

  • characters ( resource processor, string contents )

Using xslt_set_sax_handlers() doesn't look very different than running a SAX parser like xml_parse() on the result of an xslt_process() transformation.

Examples

Example 1. xslt_set_sax_handlers() Example

&#60;?php
// From ohlesbeauxjours at yahoo dot fr
// Here's a simple example that applies strtoupper() on
// the content of every &#60;auteur&#62; tag and then displays the
// resulting XML tree:

$xml='&#60;?xml version="1.0"?&#62;
&#60;books&#62;
 &#60;book&#62;
  &#60;title&#62;Mme Bovary&#60;/title&#62;
  &#60;author&#62;Gustave Flaubert&#60;/author&#62;
 &#60;/book&#62;
 &#60;book&#62;
  &#60;title&#62;Mrs Dalloway&#60;/title&#62;
  &#60;author&#62;Virginia Woolf&#60;/author&#62;
 &#60;/book&#62;
&#60;/books&#62;';

$xsl='&#60;?xml version="1.0"?&#62;
&#60;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&#62;
&#60;xsl:output method="html" encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes"/&#62;
&#60;xsl:template match="/"&#62;
 &#60;xsl:for-each select="books/book"&#62;
  &#60;livre&#62;
   &#60;auteur&#62;&#60;xsl:value-of select="author/text()"/&#62;&#60;/auteur&#62;
  &#60;/livre&#62;
 &#60;/xsl:for-each&#62;
&#60;/xsl:template&#62;
&#60;/xsl:stylesheet&#62;';

// Handlers :
function start_document()
{
  // start reading the document
}

function end_document()
{
  // end reading the document
}

function start_element($parser, $name, $attributes)
{
  global $result,$tag;
  $result .= "&#60;". $name . "&#62;";
  $tag = $name;
}

function end_element($parser, $name)
{
  global $result;
  $result .= "&#60;/" . $name . "&#62;";
}

function characters($parser, $data)
{
  global $result,$tag;
  if ($tag == "auteur" ) {
    $data = strtoupper($data);
  }
  $result .= $data;
}

// Transformation :
$xh = xslt_create();
$handlers = array("document" =&#62; array("start_document","end_document"),
   "element" =&#62; array("start_element","end_element"),
   "character" =&#62; "characters");

xslt_set_sax_handlers($xh, $handlers);
xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=&#62;$xml, "/_xsl"=&#62;$xsl));
xslt_free($xh);
?&#62;

You can also use xslt_set_object() if you want to implement your handlers in an object.

Example 2. Object oriented handler

&#60;?php
// This is the object oriented version of the previous example
class data_sax_handler {

  var $buffer, $tag, $attrs;

  var $_xh;

  function data_sax_handler($xml, $xsl)
  {
      // our xslt resource
      $this-&#62;_xh = xslt_create();

      xslt_set_object($this-&#62;_xs, $this);

      // configure sax handlers
      $handlers = array(
        "document" =&#62; array('start_document', 'end_document'),
        "element" =&#62; array('start_element', 'end_element'),
        "character" =&#62; 'characters'
      );

      xslt_set_sax_handlers($this-&#62;_xh, $handlers);

      xslt_process($this-&#62;_xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=&#62;$xml, "/_xsl"=&#62;$xsl));
      xslt_free($this-&#62;_xh);

  }

  function start_document()
  {
        // start reading the document
  }

  function end_document() {
        // complete reading the document
  }

  function start_element($parser, $name, $attributes) {
        $this-&#62;tag = $name;
        $this-&#62;buffer .= "&#60;" . $name . "&#62;";
        $this-&#62;attrs = $attributes;
  }

  function end_element($parser, $name)
  {
        $this-&#62;tag = '';
        $this-&#62;buffer .= "&#60;/" . $name . "&#62;";
  }

  function characters($parser, $data)
  {
    if ($this-&#62;tag == 'auteur') {
          $data = strtoupper($data);
    }
    $this-&#62;buffer .= $data;
  }

  function get_buffer() {
    return $this-&#62;buffer;
  }

}

$exec = new data_sax_handler($xml, $xsl);

?&#62;

Both examples will output:

<livre>
   <auteur>GUSTAVE FLAUBERT</auteur>
</livre>
<livre>
   <auteur>VIRGINIA WOOLF</auteur>
</livre>

Prev | Home | Next
xslt_set_sax_handler | Up | xslt_set_scheme_handler


xslt_set_scheme_handler

(4.0.5 - 4.0.6 only)

xslt_set_scheme_handler -- Set Scheme handlers for a XSLT processor

Description

void xslt_set_scheme_handler ( resource xh, array handlers )

Set Scheme handlers on the resource handle given by xh. Scheme handlers should be an array with the format (all elements are optional):

array(
[get_all] =&#62; get all handler,
[open] =&#62; open handler,
[get] =&#62; get handler,
[put] =&#62; put handler,
[close] =&#62; close handler
)

Prev | Home | Next
xslt_set_sax_handlers | Up | xslt_set_scheme_handlers


xslt_set_scheme_handlers

(PHP 4 >= 4.0.6, PECL)

xslt_set_scheme_handlers -- Set the scheme handlers for the XSLT processor

Description

void xslt_set_scheme_handlers ( resource processor, array handlers )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
xslt_set_scheme_handler | Up | xslt_setopt


xslt_setopt

(PHP 4 >= 4.3.0, PECL)

xslt_setopt -- Set options on a given xsl processor

Description

mixed xslt_setopt ( resource processor, int newmask )

xslt_setopt() sets the options specified by newmask on the given processor. Returns the number of previous mask is possible, TRUE otherwise, FALSE in case of an error.

newmask is a bitmask constructed with the following constants:

  • XSLT_SABOPT_PARSE_PUBLIC_ENTITIES - Tell the processor to parse public entities. By default this has been turned off.

  • XSLT_SABOPT_DISABLE_ADDING_META - Do not add the meta tag "Content-Type" for HTML output. The default is set during the compilation of the processor.

  • XSLT_SABOPT_DISABLE_STRIPPING - Suppress the whitespace stripping (on data files only).

  • XSLT_SABOPT_IGNORE_DOC_NOT_FOUND - Consider unresolved documents (the document() function) non-lethal.

Examples

Example 1. xslt_setopt() Example

&#60;?php

$xh = xslt_create();

// Tell Sablotron to process public entities
xslt_setopt($xh, XSLT_SABOPT_PARSE_PUBLIC_ENTITIES);

// Let's also ask him to suppress whitespace stripping
xslt_setopt($xh, xslt_getopt($xh) | XSLT_SABOPT_DISABLE_STRIPPING);

?&#62;

See Also

xslt_getopt().

Prev | Home | Next
xslt_set_scheme_handlers | Up | YAZ Functions


YAZ Functions

PHP Manual
Prev Next

CLXXXIII. YAZ Functions

Introduction

This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.

The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared among users, thus saving the connect and initialize phase steps in most cases.

YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.

Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Installation

Obtain YAZ (ANSI/NISO Z39.50 support) and install it. YAZ can be fetched in source or in various prebuilt packages from the YAZ archive. Systems such as Debian GNU/Linux, Suse Linux, FreeBSD also has YAZ as part of their distribution.

For the PHP 4 series, the YAZ extension is bundled (but not YAZ itself) Build PHP with your favorite modules and add option --with-yaz[=DIR].

Example 1. YAZ compilation for PHP 4 on Unix

gunzip -c php-4.4.X.tar.gz|tar xf -
gunzip -c yaz-2.1.8.tar.gz|tar xf -
cd yaz-2.1.8
./configure --prefix=/usr
make
sudo make install
cd ../php-4.4.X.
./configure --with-yaz=/usr/bin
make
sudo make install

For PHP 5, the YAZ extension is in PECL and is installed as a shared object/dll. If you have pear installed the easiest way to download, configure and install the YAZ extension is by using the pear command.

Example 2. Installation of PECL YAZ on GNU/Debian Linux

On a Debian GNU/Linux system the following installs YAZ and PECL YAZ:

sudo apt-get install libyaz-dev
sudo pear install yaz

On Windows, php_yaz.dll depend on yaz.dll. The yaz.dll is part of the Win32 ZIP from the PHP site. It is also part of the Windows YAZ install available from the YAZ WIN32 area.

Warning

The PHP 5.0.5 Win32 zip includes a too old version of yaz.dll (version 1.9.1 < required version 2.0.13). If that's the case use the yaz.dll from a newer YAZ WIN32 install.

On windows, don't forget to add the PHP directory to the PATH, so that the yaz.dll file can be found by the system.

If you are using YAZ as a shared extension, add (or uncomment) the following line in php.ini on Unix:

extension=yaz.so
And for Windows:
extension=php_yaz.dll

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they both share the same internal symbol.

Note: The above problem is solved in version 2.0 of YAZ.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. YAZ configuration options

Name | Default | Changeable | Changelog
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0.
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.

The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in array host.

Example 3. Parallel searching using Yaz

&#60;?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || count($host) == 0) {
    echo '&#60;form method="get"&#62;
    &#60;input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils" /&#62;
        GILS test
    &#60;input type="checkbox"
    name="host[]" value="localhost:9999/Default" /&#62;
        local test
    &#60;input type="checkbox" checked="checked"
    name="host[]" value="z3950.loc.gov:7090/voyager" /&#62;
        Library of Congress
    &#60;br /&#62;
    RPN Query:
    &#60;input type="text" size="30" name="query" /&#62;
    &#60;input type="submit" name="action" value="Search" /&#62;
    &#60;/form&#62;
    ';
} else {
    echo 'You searched for ' . htmlspecialchars($query) . '&#60;br /&#62;';
    for ($i = 0; $i &#60; $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
    yaz_syntax($id[$i], "usmarc");
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $query);
    }
    yaz_wait();
    for ($i = 0; $i &#60; $num_hosts; $i++) {
        echo '&#60;hr /&#62;' . $host[$i] . ':';
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '&#60;dl&#62;';
        for ($p = 1; $p &#60;= 10; $p++) {
            $rec = yaz_record($id[$i], $p, "string");
            if (empty($rec)) continue;
            echo "&#60;dt&#62;&#60;b&#62;$p&#60;/b&#62;&#60;/dt&#62;&#60;dd&#62;";
            echo nl2br($rec);
            echo "&#60;/dd&#62;";
        }
        echo '&#60;/dl&#62;';
    }
}
?&#62;

Table of Contents
yaz_addinfo -- Returns additional error information
yaz_ccl_conf -- Configure CCL parser
yaz_ccl_parse -- Invoke CCL Parser
yaz_close -- Close YAZ connection
yaz_connect -- Prepares for a connection to a Z39.50 server
yaz_database -- Specifies the databases within a session
yaz_element -- Specifies Element-Set Name for retrieval
yaz_errno -- Returns error number
yaz_error -- Returns error description
yaz_es_result -- Inspects Extended Services Result
yaz_es -- Prepares for an Extended Service Request
yaz_get_option -- Returns value of option for connection
yaz_hits -- Returns number of hits for last search
yaz_itemorder -- Prepares for Z39.50 Item Order with an ILL-Request package
yaz_present -- Prepares for retrieval (Z39.50 present)
yaz_range -- Specifies a range of records to retrieve
yaz_record -- Returns a record
yaz_scan_result -- Returns Scan Response result
yaz_scan -- Prepares for a scan
yaz_schema -- Specifies schema for retrieval
yaz_search -- Prepares for a search
yaz_set_option -- Sets one or more options for connection
yaz_sort -- Sets sorting criteria
yaz_syntax -- Specifies the preferred record syntax for retrieval
yaz_wait -- Wait for Z39.50 requests to complete

Prev | Home | Next
xslt_setopt | Up | yaz_addinfo


yaz_addinfo

(PHP 4 >= 4.0.1, PECL)

yaz_addinfo -- Returns additional error information

Description

string yaz_addinfo ( resource id )

Returns additional error information for the last request on the server.

With some servers, this function may return the same string as yaz_error().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.

See Also

yaz_error()
yaz_errno()

Prev | Home | Next
YAZ Functions | Up | yaz_ccl_conf


yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL)

yaz_ccl_conf -- Configure CCL parser

Description

void yaz_ccl_conf ( resource id, array config )

This function configures the CCL query parser for a server with definitions of access points (CCL qualifiers) and their mapping to RPN.

To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function.

Parameters

id

The connection resource returned by yaz_connect().

config

An array of configuration. Each key of the array is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN.

The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

Additional information can be found on the CCL page.

Return Values

No value is returned.

Examples

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.

Example 1. CCL configuration

&#60;?php
$fields = array(
  "ti" =&#62; "1=4",
  "au"   =&#62; "1=1",
  "isbn" =&#62; "1=7"
);
yaz_ccl_conf($id, $fields);
?&#62;

See Also

yaz_ccl_parse()

Prev | Home | Next
yaz_addinfo | Up | yaz_ccl_parse


yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL)

yaz_ccl_parse -- Invoke CCL Parser

Description

bool yaz_ccl_parse ( resource id, string query, array &result )

This function invokes a CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search.

To define a set of valid CCL fields call yaz_ccl_conf() prior to this function.

Parameters

id

The connection resource returned by yaz_connect().

query

The CCL FIND query.

result

If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.

Upon failure, three indexes are set in this array to indicate the cause of failure:

  • errorcode - the CCL error code (integer)

  • errorstring - the CCL error string

  • errorpos - approximate position in query of failure (integer is character position)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. CCL Parsing

We will try to search using CCL. In the example below, $ccl is a CCL query.

&#60;?php

yaz_ccl_conf($id, $fields);  // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &#38;$cclresult)) {
    echo 'Error: ' . $cclresult["errorstring"];
} else {
    $rpn = $cclresult["rpn"];
    yaz_search($id, "rpn", $rpn);
}
?&#62;

Prev | Home | Next
yaz_ccl_conf | Up | yaz_close


yaz_close

(PHP 4 >= 4.0.1, PECL)

yaz_close -- Close YAZ connection

Description

bool yaz_close ( resource id )

Closes the connection given by parameter id.

Note: This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

yaz_connect()

Prev | Home | Next
yaz_ccl_parse | Up | yaz_connect


yaz_connect

(PHP 4 >= 4.0.1, PECL)

yaz_connect -- Prepares for a connection to a Z39.50 server

Description

mixed yaz_connect ( string zurl [, mixed options] )

This function returns a connection resource on success, zero on failure.

yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.

Note: The YAZ proxy is a freely available Z39.50 proxy.

Parameters

zurl

A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.

options

If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).

If given as an array, the contents of the array serves as options.

user

Username for authentication.

group

Group for authentication.

password

Password for authentication.

cookie

Cookie for session (YAZ proxy).

proxy

Proxy for connection (YAZ proxy).

persistent

A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.

Note: If you open a persistent connection, you won't be able to close it later with yaz_close().

piggyback

A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled.

Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.

charset

A string that specifies character set to be used in Z39.50 language and character set negotiation. Use strings such as: ISO-8859-1, UTF-8, UTF-16.

Most Z39.50 servers do not support this feature (and thus, this is ignored). Many servers use the ISO-8859-1 encoding for queries and messages. MARC21/USMARC records are not affected by this setting.

preferredMessageSize

An integer that specifies the maximum byte size of all records to be returned by a target during retrieval. See the Z39.50 standard for more information.

Note: This option is supported in PECL YAZ 1.0.5 or later.

maximumRecordSize

An integer that specifies the maximum byte size of a single record to be returned by a target during retrieval. This entity is referred to as Exceptional-record-size in the Z39.50 standard.

Note: This option is supported in PECL YAZ 1.0.5 or later.

Return Values

A connection resource on success, FALSE on error.

ChangeLog

Version | Description
4.1.0 | The parameter options was added.

See Also

yaz_close()

Prev | Home | Next
yaz_close | Up | yaz_database


yaz_database

(PHP 4 >= 4.0.6, PECL)

yaz_database -- Specifies the databases within a session

Description

bool yaz_database ( resource id, string databases )

This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
yaz_connect | Up | yaz_element


yaz_element

(PHP 4 >= 4.0.1, PECL)

yaz_element -- Specifies Element-Set Name for retrieval

Description

bool yaz_element ( resource id, string elementset )

This function sets the element set name for retrieval.

Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.

Note: If this function seems effectless, see the description of the piggybacking option in yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
yaz_database | Up | yaz_errno


yaz_errno

(PHP 4 >= 4.0.1, PECL)

yaz_errno -- Returns error number

Description

int yaz_errno ( resource id )

Returns an error number for the server (last request) identified by id.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

See Also

yaz_error()
yaz_addinfo()

Prev | Home | Next
yaz_element | Up | yaz_error


yaz_error

(PHP 4 >= 4.0.1, PECL)

yaz_error -- Returns error description

Description

string yaz_error ( resource id )

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

See Also

yaz_errno()
yaz_addinfo()

Prev | Home | Next
yaz_errno | Up | yaz_es_result


yaz_es_result

(PHP 4 >= 4.2.0, PECL)

yaz_es_result -- Inspects Extended Services Result

Description

array yaz_es_result ( resource id )

This function inspects the last returned Extended Service result from a server. An Extended Service is initiated by either yaz_item_order() or yaz_es().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns array with element targetReference for the reference for the extended service operation (generated and returned from the server).

See Also

yaz_es()

Prev | Home | Next
yaz_error | Up | yaz_es


yaz_get_option

(PECL)

yaz_get_option -- Returns value of option for connection

Description

string yaz_get_option ( resource id, string name )

Returns the value of the option specified with name.

Parameters

id

The connection resource returned by yaz_connect().

name

The option name.

Return Values

Returns the value of the specified option or an empty string if the option wasn't set.

See Also

The description of yaz_set_option() for available options

Prev | Home | Next
yaz_es | Up | yaz_hits


yaz_hits

(PHP 4 >= 4.0.1, PECL)

yaz_hits -- Returns number of hits for last search

Description

int yaz_hits ( resource id [, array searchresult] )

yaz_hits() returns the number of hits for the last search.

Parameters

id

The connection resource returned by yaz_connect().

searchresult

Result array for detailed search result information.

Return Values

Returns the number of hits for the last search or 0 if no search was performed.

The search result array (if supplied) holds information that is returned by a Z39.50 server in the SearchResult-1 format part of a search response. The SearchResult-1 format can be used to obtain information about hit counts for various parts of the query (subquery). In particular, it is possible to obtain hit counts for the individual search terms in a query. Information for first subquery is in $array[0], second subquery in $array[1], and so forth.

Table 1. searchresult members

Element | Description
id | Sub query ID2 (string)
count | Result count / hits (integer)
subquery.term | Sub query term (string)
interpretation.term | Interpretated sub query term (string)
recommendation.term | Recommended sub query term (string)

Note: The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Note: Very few Z39.50 implementations support the SearchResult facility.

Prev | Home | Next
yaz_get_option | Up | yaz_itemorder


yaz_itemorder

(PHP 4 >= 4.0.5, PECL)

yaz_itemorder -- Prepares for Z39.50 Item Order with an ILL-Request package

Description

void yaz_itemorder ( resource id, array args )

This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification.

Parameters

id

The connection resource returned by yaz_connect().

args

Must be an associative array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:

protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:

package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item

Return Values

No value is returned.

Prev | Home | Next
yaz_hits | Up | yaz_present


yaz_present

(PHP 4 >= 4.0.5, PECL)

yaz_present -- Prepares for retrieval (Z39.50 present)

Description

bool yaz_present ( resource id )

This function prepares for retrieval of records after a successful search.

The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
yaz_itemorder | Up | yaz_range


yaz_range

(PHP 4 >= 4.0.1, PECL)

yaz_range -- Specifies a range of records to retrieve

Description

void yaz_range ( resource id, int start, int number )

Specifies a range of records to retrieve.

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

start

Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().

number

Specifies the number of records to be retrieved.

Return Values

No value is returned.

Prev | Home | Next
yaz_present | Up | yaz_record


yaz_record

(PHP 4 >= 4.0.1, PECL)

yaz_record -- Returns a record

Description

string yaz_record ( resource id, int pos, string type )

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.

Parameters

id

The connection resource returned by yaz_connect().

pos

The record position. Records positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

type

The type specifies the form of the returned record.

Note: It is the application which is responsible for actually ensuring that the records are returned from the Z39.50/SRW server in the proper format. The type given only specifies a conversion to take place on the client side (in PHP/YAZ).

Besides conversion of the transfer record to a string/array, PHP/YAZ it is also possible to perform a character set conversion of the record. Especially for USMARC/MARC21 that is recommended since these are typically returned in the character set MARC-8 that is not supported by browsers, etc. To specify a conversion, add ; charset=from, to where from is the original character set of the record and to is the resulting character set (as seen by PHP).

string

The record is returned as a string for simple display. In this mode, all MARC records are converted to a line-by-line format since ISO2709 is hardly readable. XML records and SUTRS are returned in their original format. GRS-1 are returned in a (ugly) line-by-line format.

This format is suitable if records are to be displayed in a quick way - for debugging - or because it is not feasible to perform proper display.

xml

The record is returned as an XML string if possible. In this mode, all MARC records are converted to MARCXML. XML records and SUTRS are returned in their original format. GRS-1 is not supported.

This format is similar to string except that MARC records are converted to MARCXML

This format is suitable if records are processed by an XML parser or XSLT processor afterwards.

raw

The record is returned as a string in its original form. This type is suitable for MARC, XML and SUTRS. It does not work for GRS-1.

MARC records are returned as a ISO2709 string. XML and SUTRS are returned as strings.

syntax

The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.

database

The name of database associated with record at the position is returned as a string.

array

The record is returned as an array that reflects the GRS-1 structure. This type is suitable for MARC and GRS-1. XML, SUTRS are not supported and if the actual record is XML or SUTRS an empty string will be returned.

The array returned consists of a list corresponding to each leaf/internal node of GRS-1. Each list item consists a sub list with first element path and data (if data is available).

The path which is a string holds a list of each tree component (of the structured GRS-1 record) from root to leaf. Each component is a tag type, tag value pair of the form (type, value

String tags normally has a corresponding tag type 3. MARC can also be returned as an array (they are converted to GRS-1 internally).

Return Values

Returns the record at position pos or an empty string if no record exists at the given position.

If no database record exists at the given position an empty string is returned.

Examples

Example 1. Array for GRS-1 record

Consider this GRS-1 record:

(4,52)Robert M. Pirsig
(4,70)
      (4,90)
            (2,7)Transworld Publishers, ltd.
This record has two nodes at root level. First element at root level is (4,52) [tag type 4, tag value 52], and has data Robert M. Pirsig. Second element at root level (4,70) has a subtree with a single element (4,90). (4,90) has yet another sub tree (2,7) with data Transworld Publishers, ltd..

If this record is present at position $p, then

&#60;?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?&#62;
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Example 2. Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).

&#60;?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?&#62;

The record $rec can be processed with the Sablotron XSLT processor as follows:

&#60;?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' =&#62; $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'&#60;/?html[^&#62;]*&#62;'", '', $res);
echo $res;

?&#62;

For PHP 5 the XSL extension must be used instead of Sablotron XSLT.

Prev | Home | Next
yaz_range | Up | yaz_scan_result


yaz_scan_result

(PHP 4 >= 4.0.5, PECL)

yaz_scan_result -- Returns Scan Response result

Description

array yaz_scan_result ( resource id [, array &result] )

yaz_scan_result() returns terms and associated information as received from the server in the last performed yaz_scan().

Parameters

id

The connection resource returned by yaz_connect().

result

If given, this array will be modified to hold additional information taken from the Scan Response:

  • number - Number of entries returned

  • stepsize - Step size

  • position - Position of term

  • status - Scan status

Return Values

Returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where the first item is the term, and the second item is the result-count.

Prev | Home | Next
yaz_record | Up | yaz_scan


yaz_scan

(PHP 4 >= 4.0.5, PECL)

yaz_scan -- Prepares for a scan

Description

void yaz_scan ( resource id, string type, string startterm [, array flags] )

This function prepares for a Z39.50 Scan Request on the specified connection.

To actually transfer the Scan Request to the server and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.

Parameters

id

The connection resource returned by yaz_connect().

type

Currently only type rpn is supported.

startterm

Starting term point for the scan.

The form in which the starting term is specified is given by parameter type.

The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.

flags

This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).

Return Values

No value is returned.

Examples

Example 1. PHP function that scans titles

&#60;?php
function scan_titles($id, $startterm)
{
  yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
  yaz_wait();
  $errno = yaz_errno($id);
  if ($errno == 0) {
    $ar = yaz_scan_result($id, &#38;$options);
    echo 'Scan ok; ';
    foreach ($options as $key =&#62; $val) {
      echo "$key = $val &#38;nbsp;";
    }
    echo '&#60;br /&#62;&#60;table&#62;';
    while (list($key, list($k, $term, $tcount)) = each($ar)) {
      if (empty($k)) continue;
      echo "&#60;tr&#62;&#60;td&#62;$term&#60;/td&#62;&#60;td&#62;$tcount&#60;/td&#62;&#60;/tr&#62;";
    }
    echo '&#60;/table&#62;';
  } else {
    echo "Scan failed. Error: " . yaz_error($id) . "&#60;br /&#62;";
  }
}
?&#62;

Prev | Home | Next
yaz_scan_result | Up | yaz_schema


yaz_schema

(PHP 4 >= 4.2.0, PECL)

yaz_schema -- Specifies schema for retrieval

Description

void yaz_schema ( resource id, string schema )

yaz_schema() specifies the schema for retrieval.

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

schema

Must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ...

Return Values

No value is returned.

Prev | Home | Next
yaz_scan | Up | yaz_search


yaz_search

(PHP 4 >= 4.0.1, PECL)

yaz_search -- Prepares for a search

Description

bool yaz_search ( resource id, string type, string query )

yaz_search() prepares for a search on the given connection.

Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

Parameters

id

The connection resource returned by yaz_connect().

type

This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.

query

The RPN query is a textual representation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

Table 1. RPN Operators

Construct | Description
@and query1 query2 | intersection of query1 and query2
@or query1 query2 | union of query1 and query2
@not query1 query2 | query1 and not query2
@set name | result set reference
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set.

You can find information about attributes at the Z39.50 Maintenance Agency site.

Note: If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Query Examples

You can search for simple terms, like this:

computer
which matches documents where "computer" occur. No attributes are specified.

The query

"knuth donald"
matches documents where "knuth donald" occur (provided that the server supports phrase search).

This query applies two attributes for the same phrase.

@attr 1=1003 @attr 4=1 "knuth donald"
First attribute is type 1 (Bib-1 use), attribute value is 1003 (Author). Second attribute has is type 4 (structure), value 1 (phrase), so this should match documents where Donald Knuth is author.

The query

@and @or a b @not @or c d e
would in infix notation look like (a or b) and ((c or d) not e).

Another, more complex, one:

@attrset gils @and @attr 1=4 art @attr 1=2000 company
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title (GILS,BIB-1) and in which company occur as Distributor (GILS).

Prev | Home | Next
yaz_schema | Up | yaz_set_option


yaz_set_option

(PECL)

yaz_set_option -- Sets one or more options for connection

Description

void yaz_set_option ( resource id, string name, string value )

void yaz_set_option ( resource id, array options )

Sets one or more options on the given connection.

Parameters

id

The connection resource returned by yaz_connect().

name or options

May be either a string or an array.

If given as a string, this will be the name of the option to set. You'll need to give it's value.

If given as an array, this will be an associative array (option name => option value).

Table 1. PHP/YAZ Connection Options

Name | Description
implementationName | implementation name of server
implementationVersion | implementation version of server
implementationId | implementation ID of server
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
start | offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range()
count | maximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element().
value

The new value of the option. Use this only if the previous argument is a string.

Return Values

No value is returned.

Prev | Home | Next
yaz_search | Up | yaz_sort


yaz_sort

(PHP 4 >= 4.1.0, PECL)

yaz_sort -- Sets sorting criteria

Description

void yaz_sort ( resource id, string criteria )

This function sets sorting criteria and enables Z39.50 Sort.

Call this function before yaz_search(). Using this function alone does not have any effect. When used in conjunction with yaz_search(), a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present (yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

criteria

A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..

The field specifies either a numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequence of the following characters which may not be separated by any white space.

Sort Flags

a

Sort ascending

d

Sort descending

i

Case insensitive sorting

s

Case sensitive sorting

Return Values

No value is returned.

Examples

Example 1. Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you would use the following sort criteria:

1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you would use:

1=4 ia 1=1003 sa

Prev | Home | Next
yaz_set_option | Up | yaz_syntax


yaz_syntax

(PHP 4 >= 4.0.1, PECL)

yaz_syntax -- Specifies the preferred record syntax for retrieval

Description

void yaz_syntax ( resource id, string syntax )

yaz_syntax() specifies the preferred record syntax for retrieval

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

syntax

The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.).

Return Values

No value is returned.

Prev | Home | Next
yaz_sort | Up | yaz_wait


yaz_wait

(PHP 4 >= 4.0.1, PECL)

yaz_wait -- Wait for Z39.50 requests to complete

Description

mixed yaz_wait ( [array &options] )

This function carries out networked (blocked) activity for outstanding
requests which have been prepared by the functions
yaz_connect(), yaz_search(),
yaz_present(), yaz_scan() and
yaz_itemorder().

yaz_wait() returns when all servers have either completed all requests or aborted (in case of errors).

Parameters

options

An associative array of options:

timeout

Sets timeout in seconds. If a server has not responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

event

A boolean.

Return Values

Returns TRUE on success or FALSE on failure. In event mode, returns resource or FALSE in case of an error.

Prev | Home | Next
yaz_syntax | Up | YP/NIS Functions


Zip File Functions

PHP Manual
Prev Next

CLXXXV. Zip File Functions

Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

Requirements

PHP 4

The bundled PHP4 version requires ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2 or later

This extension uses the functions of zlib by Jean-loup Gailly and Mark Adler.

Installation

PHP4

Note: Zip support before PHP 4.1.0 is experimental.

Warning

Because the PHP4 zip extension is unmaintained we recommend that the PECL extension is used rather than the bundled one.

Linux systems

In order to use these functions you must compile PHP with zip support by using the --with-zip[=DIR] configure option, where [DIR] is the prefix of the ZZIPlib library install.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

PHP5.2 and later

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

Installation via PECL

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/zip.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

There are two resource types used in the Zip module. The first one is the Zip directory for the Zip archive, the second Zip Entry for the archive entries.

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.

ZipArchive uses class constants. There is three types of constants, Flags (FL_) errors (ER_) or mode (no prefix).

ZIPARCHIVE::CREATE (integer)

Create the archive if it does not exist.

ZIPARCHIVE::OVERWRITE (integer)

Always start a new archive, this mode will overwrite the file if it already exists.

ZIPARCHIVE::EXCL (integer)

Error if archive already exists.

ZIPARCHIVE::CHECKCONS (integer)

Perform additional consistency checks on the archive, and error if they fail.

ZIPARCHIVE::FL_NOCASE (integer)

Ignore case on name lookup

ZIPARCHIVE::FL_NODIR (integer)

Ignore directory component

ZIPARCHIVE::FL_COMPRESSED (integer)

Read compressed data

ZIPARCHIVE::FL_UNCHANGED (integer)

Use original data, ignoring changes.

ZIPARCHIVE::CM_DEFAULT (integer)

better of deflate or store.

ZIPARCHIVE::CM_STORE (integer)

stored (uncompressed).

ZIPARCHIVE::CM_SHRINK (integer)

shrunk

ZIPARCHIVE::CM_REDUCE_1 (integer)

reduced with factor 1

ZIPARCHIVE::CM_REDUCE_2 (integer)

reduced with factor 2

ZIPARCHIVE::CM_REDUCE_3 (integer)

reduced with factor 3

ZIPARCHIVE::CM_REDUCE_4 (integer)

reduced with factor 4

ZIPARCHIVE::CM_IMPLODE (integer)

imploded

ZIPARCHIVE::CM_DEFLATE (integer)

deflated

ZIPARCHIVE::CM_DEFLATE64 (integer)

deflate64

ZIPARCHIVE::CM_PKWARE_IMPLODE (integer)

PKWARE imploding

ZIPARCHIVE::CM_BZIP2 (integer)

BZIP2 algorithm

ZIPARCHIVE::ER_OK (integer)

No error.

ZIPARCHIVE::ER_MULTIDISK (integer)

Multi-disk zip archives not supported.

ZIPARCHIVE::ER_RENAME (integer)

Renaming temporary file failed.

ZIPARCHIVE::ER_CLOSE (integer)

Closing zip archive failed

ZIPARCHIVE::ER_SEEK (integer)

Seek error

ZIPARCHIVE::ER_READ (integer)

Read error

ZIPARCHIVE::ER_WRITE (integer)

Write error

ZIPARCHIVE::ER_CRC (integer)

CRC error

ZIPARCHIVE::ER_ZIPCLOSED (integer)

Containing zip archive was closed

ZIPARCHIVE::ER_NOENT (integer)

No such file.

ZIPARCHIVE::ER_EXISTS (integer)

File already exists

ZIPARCHIVE::ER_OPEN (integer)

Can't open file

ZIPARCHIVE::ER_TMPOPEN (integer)

Failure to create temporary file.

ZIPARCHIVE::ER_ZLIB (integer)

Zlib error

ZIPARCHIVE::ER_MEMORY (integer)

Memory allocation failure

ZIPARCHIVE::ER_CHANGED (string)

Entry has been changed

ZIPARCHIVE::ER_COMPNOTSUPP (integer)

Compression method not supported.

ZIPARCHIVE::ER_EOF (integer)

Premature EOF

ZIPARCHIVE::ER_INVAL (integer)

Invalid argument

ZIPARCHIVE::ER_NOZIP (integer)

Not a zip archive

ZIPARCHIVE::ER_INTERNAL (integer)

Internal error

ZIPARCHIVE::ER_INCONS (integer)

Zip archive inconsistent

ZIPARCHIVE::ER_REMOVE (integer)

Can't remove file

ZIPARCHIVE::ER_DELETED (integer)

Entry has been deleted

Examples

Example 1. Create a Zip archive

&#60;?php

$zip = new ZipArchive();
$filename = "./test112.zip";

if ($zip-&#62;open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
    exit("cannot open &#60;$filename&#62;\n");
}

$zip-&#62;addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip-&#62;addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip-&#62;addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip-&#62;numFiles . "\n";
echo "status:" . $zip-&#62;status . "\n";
$zip-&#62;close();
?&#62;

Example 2. Dump the archive details and listing

&#60;?php
$za = new ZipArchive();

$za-&#62;open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za-&#62;numFiles . "\n";
echo "status: " . $za-&#62;status  . "\n";
echo "statusSys: " . $za-&#62;statusSys . "\n";
echo "filename: " . $za-&#62;filename . "\n";
echo "comment: " . $za-&#62;comment . "\n";

for ($i=0; $i&#60;$za-&#62;numFiles;$i++) {
    echo "index: $i\n";
    print_r($za-&#62;statIndex($i));
}
echo "numFile:" . $za-&#62;numFiles . "\n";
?&#62;

Example 3. Zip stream wrapper, read an OpenOffice meta info

&#60;?php
$reader = new XMLReader();

$reader-&#62;open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader-&#62;read()) {
    if ($reader-&#62;nodeType == XMLREADER::ELEMENT) {
        $elm = $reader-&#62;name;
    } else {
        if ($reader-&#62;nodeType == XMLREADER::END_ELEMENT &#38;&#38; $reader-&#62;name == 'office:meta') {
            break;
        }
        if (!trim($reader-&#62;value)) {
            continue;
        }
        $odt_meta[$elm] = $reader-&#62;value;
    }
}
print_r($odt_meta);
?&#62;

This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example 4. Zip Usage Example

&#60;?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        echo "Name:               " . zip_entry_name($zip_entry) . "\n";
        echo "Actual Filesize:    " . zip_entry_filesize($zip_entry) . "\n";
        echo "Compressed Size:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "File Contents:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}
?&#62;
Table of Contents
zip_close -- Close a ZIP file archive
zip_entry_close -- Close a directory entry
zip_entry_compressedsize -- Retrieve the compressed size of a directory entry
zip_entry_compressionmethod -- Retrieve the compression method of a directory entry
zip_entry_filesize -- Retrieve the actual file size of a directory entry
zip_entry_name -- Retrieve the name of a directory entry
zip_entry_open -- Open a directory entry for reading
zip_entry_read -- Read from an open directory entry
zip_open -- Open a ZIP file archive
zip_read -- Read next entry in a ZIP file archive
ZipArchive::addFile -- Adds a file to a ZIP archive from the given path
ZipArchive::addFromString -- Add a file to a ZIP archive using its contents
ZipArchive::close -- Close the active archive (opened or newly created)
ZipArchive::deleteIndex -- delete an entry in the archive using its index
ZipArchive::deleteName -- delete an entry in the archive using its name
ZipArchive::extractTo -- Extract the archive contents
ZipArchive::getArchiveComment -- Returns the Zip archive comment
ZipArchive::getCommentIndex -- Returns the comment of an entry using the entry index
ZipArchive::getCommentName -- Returns the comment of an entry using the entry name
ZipArchive::getFromIndex -- Returns the entry contents using its index.
ZipArchive::getFromName -- Returns the entry contents using its name.
ZipArchive::getNameIndex -- Returns the name of an entry using its index
ZipArchive::getStream -- Get a file handler to the entry defined by its name (read only).
ZipArchive::locateName -- Returns the index of the entry in the archive
ZipArchive::open -- Open a ZIP file archive
ZipArchive::renameIndex -- Renames an entry defined by its index
ZipArchive::renameName -- Renames an entry defined by its name
ZipArchive::setArchiveComment -- Set the comment of a ZIP archive
ZipArchive::setCommentIndex -- Set the comment of an entry defined by its index
ZipArchive::setCommentName -- Set the comment of an entry defined by its name
ZipArchive::statIndex -- Get the details of an entry defined by its index.
ZipArchive::statName -- Get the details of an entry defined by its name.
ZipArchive::unchangeAll -- Undo all changes done in the archive.
ZipArchive::unchangeArchive -- Revert all global changes done in the archive.
ZipArchive::unchangeIndex -- Revert all changes done to an entry at the given index.
ZipArchive::unchangeName -- Revert all changes done to an entry with the given name.

Prev | Home | Next
yp_order | Up | zip_close


zip_close

(PHP 4 >= 4.1.0, PECL)

zip_close -- Close a ZIP file archive

Description

void zip_close ( resource zip )

Closes the given ZIP file archive.

Parameters

zip

A ZIP file previously opened with zip_open().

Return Values

No value is returned.

See Also

zip_open()
zip_read()

Prev | Home | Next
Zip File Functions | Up | zip_entry_close


zip_entry_close

(PHP 4 >= 4.1.0, PECL)

zip_entry_close -- Close a directory entry

Description

bool zip_entry_close ( resource zip_entry )

Closes the specified directory entry.

Parameters

zip_entry

A directory entry previously opened zip_entry_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

zip_entry_open()
zip_entry_read()

Prev | Home | Next
zip_close | Up | zip_entry_compressedsize


zip_entry_compressedsize

(PHP 4 >= 4.1.0, PECL)

zip_entry_compressedsize -- Retrieve the compressed size of a directory entry

Description

int zip_entry_compressedsize ( resource zip_entry )

Returns the compressed size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compressed size.

See Also

zip_open()
zip_read()

Prev | Home | Next
zip_entry_close | Up | zip_entry_compressionmethod


zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PECL)

zip_entry_compressionmethod -- Retrieve the compression method of a directory entry

Description

string zip_entry_compressionmethod ( resource zip_entry )

Returns the compression method of the directory entry specified by zip_entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compression method.

See Also

zip_open()
zip_read()

Prev | Home | Next
zip_entry_compressedsize | Up | zip_entry_filesize


zip_entry_filesize

(PHP 4 >= 4.1.0, PECL)

zip_entry_filesize -- Retrieve the actual file size of a directory entry

Description

int zip_entry_filesize ( resource zip_entry )

Returns the actual size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The size of the directory entry.

See Also

zip_open()
zip_read()

Prev | Home | Next
zip_entry_compressionmethod | Up | zip_entry_name


zip_entry_name

(PHP 4 >= 4.1.0, PECL)

zip_entry_name -- Retrieve the name of a directory entry

Description

string zip_entry_name ( resource zip_entry )

Returns the name of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The name of the directory entry.

See Also

zip_open()
zip_read()

Prev | Home | Next
zip_entry_filesize | Up | zip_entry_open


zip_entry_open

(PHP 4 >= 4.1.0, PECL)

zip_entry_open -- Open a directory entry for reading

Description

bool zip_entry_open ( resource zip, resource zip_entry [, string mode] )

Opens a directory entry in a zip file for reading.

Parameters

zip

A valid resource handle returned by zip_open().

zip_entry

A directory entry returned by zip_read().

mode

Any of the modes specified in the documentation of fopen().

Note: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access.

Return Values

Returns TRUE on success or FALSE on failure.

Note: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.

See Also

zip_entry_close()
zip_entry_read()

Prev | Home | Next
zip_entry_name | Up | zip_entry_read


zip_entry_read

(PHP 4 >= 4.1.0, PECL)

zip_entry_read -- Read from an open directory entry

Description

string zip_entry_read ( resource zip_entry [, int length] )

Reads from an open directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return. If not specified, this function will attempt to read 1024 bytes.

Note: This should be the uncompressed length you wish to read.

Return Values

Returns the data read, or FALSE if the end of the file is reached.

See Also

zip_entry_open()
zip_entry_close()
zip_entry_filesize()

Prev | Home | Next
zip_entry_open | Up | zip_open


zip_open

(PHP 4 >= 4.1.0, PECL)

zip_open -- Open a ZIP file archive

Description

mixed zip_open ( string filename )

Opens a new zip archive for reading.

Parameters

filename

The file name of the ZIP archive to open.

Return Values

Returns a resource handle for later use with zip_read() and zip_close() or returns the number of error if filename does not exist or in case of other error.

See Also

zip_read()
zip_close()

Prev | Home | Next
zip_entry_read | Up | zip_read


zip_read

(PHP 4 >= 4.1.0, PECL)

zip_read -- Read next entry in a ZIP file archive

Description

mixed zip_read ( resource zip [, int flags] )

Reads the next entry in a zip file archive.

Parameters

zip

A ZIP file previously opened with zip_open().

flags

Bitmask of ZIP constants.

Return Values

Returns a directory entry resource for later use with the zip_entry_... functions or FALSE if there's no more entries to read or number of error in case of other error.

See Also

zip_open()
zip_close()
zip_entry_open()
zip_entry_read()

Prev | Home | Next
zip_open | Up | ZipArchive::addFile


Zlib Compression Functions

PHP Manual
Prev Next

CLXXXVI. Zlib Compression Functions

Introduction

This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).

Note: Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special zlib: URL to access compressed files transparently using the normal f*() file access functions if you prefix the filename or path with zlib: when calling fopen(). This feature requires a C runtime library that provides the fopencookie() function. Up to now the GNU libc seems to be the only library that provides this feature.

In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent ambiguities with filenames containing ':' characters. The fopencookie() function is not longer required. More information is available in the section about the Section called Compression Streams in Appendix M.

Requirements

This module uses the functions of zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module.

Installation

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

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 zlib on Windows is available with PHP 4.3.0.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

Table 1. Zlib Configuration Options

Name | Default | Changeable | Changelog
zlib.output_compression | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

zlib.output_compression boolean/integer

Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output. In runtime, it can be set only before sending any output.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

Note: output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level integer

Compression level used for transparent output compression.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

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.

FORCE_GZIP (integer)

FORCE_DEFLATE (integer)

Examples

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example 1. Small Zlib Example

&#60;?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "&#60;html&#62;\n&#60;head&#62;&#60;/head&#62;\n&#60;body&#62;\n&#60;pre&#62;\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file
gzclose($zp);

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);

echo "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
        echo "Error with zlib functions!";
}
unlink($filename);
echo "&#60;/pre&#62;\n&#60;/body&#62;\n&#60;/html&#62;\n";

?&#62;
Table of Contents
gzclose -- Close an open gz-file pointer
gzcompress -- Compress a string
gzdecode -- Decodes a gzip compressed string
gzdeflate -- Deflate a string
gzencode -- Create a gzip compressed string
gzeof -- Test for end-of-file on a gz-file pointer
gzfile -- Read entire gz-file into an array
gzgetc -- Get character from gz-file pointer
gzgets -- Get line from file pointer
gzgetss -- Get line from gz-file pointer and strip HTML tags
gzinflate -- Inflate a deflated string
gzopen -- Open gz-file
gzpassthru -- Output all remaining data on a gz-file pointer
gzputs -- Alias of gzwrite()
gzread -- Binary-safe gz-file read
gzrewind -- Rewind the position of a gz-file pointer
gzseek -- Seek on a gz-file pointer
gztell -- Tell gz-file pointer read/write position
gzuncompress -- Uncompress a compressed string
gzwrite -- Binary-safe gz-file write
readgzfile -- Output a gz-file
zlib_get_coding_type -- Returns the coding type used for output compression

Prev | Home | Next
ZipArchive::unchangeName | Up | gzclose


gzclose

(PHP 3, PHP 4, PHP 5)

gzclose -- Close an open gz-file pointer

Description

bool gzclose ( resource zp )

Closes the given gz-file pointer.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. gzclose() example

&#60;?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?&#62;

See Also

gzopen()

Prev | Home | Next
Zlib Compression Functions | Up | gzcompress


gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress -- Compress a string

Description

string gzcompress ( string data [, int level] )

This function compress the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Note: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Parameters

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

Return Values

The compressed string or FALSE if an error occurred.

Examples

Example 1. gzcompress() example

&#60;?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?&#62;

See Also

gzdeflate()
gzinflate()
gzuncompress()
gzencode()

Prev | Home | Next
gzclose | Up | gzdecode


gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate -- Deflate a string

Description

string gzdeflate ( string data [, int level] )

This function compress the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

Parameters

data

The data to deflate.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

Return Values

The deflated string or FALSE if an error occurred.

Examples

Example 1. gzdeflate() example

&#60;?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?&#62;

See Also

gzinflate()
gzcompress()
gzuncompress()
gzencode()

Prev | Home | Next
gzdecode | Up | gzencode


gzencode

(PHP 4 >= 4.0.4, PHP 5)

gzencode -- Create a gzip compressed string

Description

string gzencode ( string data [, int level [, int encoding_mode]] )

This function returns a compressed version of the input data compatible with the output of the gzip program.

For more information on the GZIP file format, see the document: GZIP file format specification version 4.3 (RFC 1952).

Parameters

data

The data to encode.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

encoding_mode

The encoding mode. Can be FORCE_GZIP (the default) or FORCE_DEFLATE.

If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

Return Values

The encoded string, or FALSE if an error occurred.

Examples

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Example 1. Creating a gzip file

&#60;?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?&#62;

ChangeLog

Version | Description
4.2 | level was added. gzencode() only had the data and the optional encoding_mode parameters before.

See Also

gzdecode()
gzdeflate()
gzinflate()
gzuncompress()
gzcompress()

Prev | Home | Next
gzdeflate | Up | gzeof


gzeof

(PHP 3, PHP 4, PHP 5)

gzeof -- Test for end-of-file on a gz-file pointer

Description

int gzeof ( resource zp )

Tests the given GZ file pointer for EOF (end-of-file).

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

Examples

Example 1. gzeof() example

&#60;?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?&#62;

Prev | Home | Next
gzencode | Up | gzfile


gzfile

(PHP 3, PHP 4, PHP 5)

gzfile -- Read entire gz-file into an array

Description

array gzfile ( string filename [, int use_include_path] )

This function is identical to readgzfile(), except that it returns the file in an array.

Parameters

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

An array containing the file, one line per cell.

Examples

Example 1. gzfile() example

&#60;?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?&#62;

See Also

readgzfile()
gzopen()

Prev | Home | Next
gzeof | Up | gzgetc


gzgetc

(PHP 3, PHP 4, PHP 5)

gzgetc -- Get character from gz-file pointer

Description

string gzgetc ( resource zp )

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The uncompressed character or FALSE on EOF (unlike gzeof()).

Examples

Example 1. gzgetc() example

&#60;?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?&#62;

See Also

gzopen()
gzgets()

Prev | Home | Next
gzfile | Up | gzgets


gzgets

(PHP 3, PHP 4, PHP 5)

gzgets -- Get line from file pointer

Description

string gzgets ( resource zp, int length )

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

Return Values

The uncompressed string, or FALSE on error.

Examples

Example 1. gzgets() example

&#60;?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?&#62;

See Also

gzopen()
gzgetc()
gzwrite()

Prev | Home | Next
gzgetc | Up | gzgetss


gzgetss

(PHP 3, PHP 4, PHP 5)

gzgetss -- Get line from gz-file pointer and strip HTML tags

Description

string gzgetss ( resource zp, int length [, string allowable_tags] )

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

allowable_tags

You can use this optional parameter to specify tags which should not be stripped.

Return Values

The uncompressed and striped string, or FALSE on error.

ChangeLog

Version | Description
3.0.13 and 4.0.0 | allowable_tags was added.

Examples

Example 1. gzgetss() example

&#60;?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?&#62;

See Also

gzopen()
gzgets()
strip_tags()

Prev | Home | Next
gzgets | Up | gzinflate


gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate -- Inflate a deflated string

Description

string gzinflate ( string data [, int length] )

This function inflate a deflated string.

Parameters

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Return Values

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Examples

Example 1. gzinflate() example

&#60;?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?&#62;

See Also

gzdeflate()
gzcompress()
gzuncompress()
gzencode()

Prev | Home | Next
gzgetss | Up | gzopen


gzopen

(PHP 3, PHP 4, PHP 5)

gzopen -- Open gz-file

Description

resource gzopen ( string filename, string mode [, int use_include_path] )

Opens a gzip (.gz) file for reading or writing.

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

Parameters

filename

The file name.

mode

As in fopen() (rb or wb) but can also include a compression level (wb9) or a strategy: f for filtered data as in wb6f, h for Huffman only compression as in wb1h. (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

Returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

Examples

Example 1. gzopen() Example

&#60;?php
$fp = gzopen("/tmp/file.gz", "r");
?&#62;

See Also

gzclose()

Prev | Home | Next
gzinflate | Up | gzpassthru


gzpassthru

(PHP 3, PHP 4, PHP 5)

gzpassthru -- Output all remaining data on a gz-file pointer

Description

int gzpassthru ( resource zp )

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

Note: You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Tip: If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.

Examples

Example 1. gzpassthru() example

&#60;?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?&#62;

Prev | Home | Next
gzopen | Up | gzputs


gzputs

(PHP 3, PHP 4, PHP 5)

gzputs -- Alias of gzwrite()

Description

This function is an alias of: gzwrite().

Prev | Home | Next
gzpassthru | Up | gzread


gzread

(PHP 3, PHP 4, PHP 5)

gzread -- Binary-safe gz-file read

Description

string gzread ( resource zp, int length )

gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The number of bytes to read.

Return Values

The data that have been read.

Examples

Example 1. gzread() example

&#60;?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?&#62;

See Also

gzwrite()
gzopen()
gzgets()
gzgetss()
gzfile()
gzpassthru()

Prev | Home | Next
gzputs | Up | gzrewind


gzrewind

(PHP 3, PHP 4, PHP 5)

gzrewind -- Rewind the position of a gz-file pointer

Description

bool gzrewind ( resource zp )

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

gzseek()
gztell()

Prev | Home | Next
gzread | Up | gzseek


gzseek

(PHP 3, PHP 4, PHP 5)

gzseek -- Seek on a gz-file pointer

Description

int gzseek ( resource zp, int offset )

Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

offset

The seeked offset.

Return Values

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Examples

Example 1. gzseek() example

&#60;?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?&#62;

See Also

gztell()
gzrewind()

Prev | Home | Next
gzrewind | Up | gztell


gztell

(PHP 3, PHP 4, PHP 5)

gztell -- Tell gz-file pointer read/write position

Description

int gztell ( resource zp )

Gets the position of the given file pointer; i.e., its offset into the file stream.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The position of the file pointer or FALSE if an error occurs.

See Also

gzopen()
gzseek()
gzrewind()

Prev | Home | Next
gzseek | Up | gzuncompress


gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress -- Uncompress a compressed string

Description

string gzuncompress ( string data [, int length] )

This function uncompress a compressed string.

Parameters

data

The data compressed by gzcompress().

length

The maximum length of data to decode.

Return Values

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Examples

Example 1. gzuncompress() example

&#60;?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?&#62;

See Also

gzcompress()
gzinflate()
gzdeflate()
gzencode()

Prev | Home | Next
gztell | Up | gzwrite


gzwrite

(PHP 3, PHP 4, PHP 5)

gzwrite -- Binary-safe gz-file write

Description

int gzwrite ( resource zp, string string [, int length] )

gzwrite() writes the contents of string to the given gz-file.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

string

The string to write.

length

The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

Note: 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.

Return Values

Returns the number of (uncompressed) bytes written to the given gz-file stream.

Examples

Example 1. gzwrite() example

&#60;?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?&#62;

See Also

gzread()
gzopen()

Prev | Home | Next
gzuncompress | Up | readgzfile


readgzfile

(PHP 3, PHP 4, PHP 5)

readgzfile -- Output a gz-file

Description

int readgzfile ( string filename [, int use_include_path] )

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

Parameters

filename

The file name. This file will be opened from the filesystem and its contents written to standard output.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

See Also

gzpassthru()
gzfile()
gzopen()

Prev | Home | Next
gzwrite | Up | zlib_get_coding_type


zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5)

zlib_get_coding_type -- Returns the coding type used for output compression

Description

string zlib_get_coding_type ( void )

Returns the coding type used for output compression.

Return Values

Possible return values are gzip, deflate, or FALSE.

See Also

The zlib.output_compression directive

Prev | Home | Next
readgzfile | Up | PHP and Zend Engine Internals


Zend API: Hacking the Core of PHP

PHP Manual
Prev Next

Chapter 46. Zend API: Hacking the Core of PHP

Table of Contents
Introduction
Overview
Extension Possibilities
Source Layout
PHP's Automatic Build System
Creating Extensions
Using Extensions
Troubleshooting
Source Discussion
Accepting Arguments
Creating Variables
Duplicating Variable Contents: The Copy Constructor
Returning Values
Printing Information
Startup and Shutdown Functions
Calling User Functions
Initialization File Support
Where to Go from Here
Reference: Some Configuration Macros
API Macros
API Function and Macro reference (work in progress)

Introduction

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.

Warning

This information is currently rather outdated, parts of it only cover early stages of the ZendEngine 1.0 API as it was used in early versions of PHP 4.

More recent information may be found in the various README files that come with the PHP source and the Internals section on the Zend website.

Prev | Home | Next
Error handling | Up | Overview


Overview

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.

What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figure 46-1). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.

Figure 46-1. The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.

Prev | Home | Next
Zend API: Hacking the Core of PHP | Up | Extension Possibilities


Extension Possibilities

As shown in Figure 46-1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.

External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk.
 | Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).

To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.

Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
No need to load the module specifically; the functionality is instantly available. | Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. | The PHP binary grows and consumes more memory.

Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.

The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.

Prev | Home | Next
Overview | Up | Source Layout


Source Layout

Note: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org/) and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

The following table describes the contents of the major directories.

Directory | Contents
php-src | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php-src/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php-src/main | This directory contains the main php macros and definitions. (important)
php-src/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php-src/sapi | Contains the code for the different server abstraction layers.
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
ZendEngine2 | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.

Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.

Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)

Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

Function | Description
emalloc() | Serves as replacement for malloc().
efree() | Serves as replacement for free().
estrdup() | Serves as replacement for strdup().
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc() | Serves as replacement for calloc().
erealloc() | Serves as replacement for realloc().

emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.

Warning

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here.

Directory and File Functions

The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.

Zend Function | Regular C Function
V_GETCWD() | getcwd()
V_FOPEN() | fopen()
V_OPEN() | open()
V_CHDIR() | chdir()
V_GETWD() | getwd()
V_CHDIR_FILE() | Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT() | stat()
V_LSTAT() | lstat()

String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)

Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Note: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.

Prev | Home | Next
Extension Possibilities | Up | PHP's Automatic Build System


PHP's Automatic Build System

PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see http://www.gnu.org/software/m4/manual/m4.html)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:

:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

The default config.m4 shown in Example 46-1 is a bit more complex:

Example 46-1. The default config.m4.

dnl $Id: build.xml,v 1.1 2005/08/21 16:27:06 goba Exp $
dnl config.m4 for extension my_module

dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
dnl [  --with-my_module             Include my_module support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
dnl [  --enable-my_module           Enable my_module support])

if test "$PHP_MY_MODULE" != "no"; then
  dnl Write more examples of tests here...

  dnl # --with-my_module -> check with-path
  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this
  dnl SEARCH_FOR="/include/my_module.h"  # you most likely want to change this
  dnl if test -r $PHP_MY_MODULE/; then # path given as parameter
  dnl   MY_MODULE_DIR=$PHP_MY_MODULE
  dnl else # search default path list
  dnl   AC_MSG_CHECKING([for my_module files in default path])
  dnl   for i in $SEARCH_PATH ; do
  dnl     if test -r $i/$SEARCH_FOR; then
  dnl       MY_MODULE_DIR=$i
  dnl       AC_MSG_RESULT(found in $i)
  dnl     fi
  dnl   done
  dnl fi
  dnl
  dnl if test -z "$MY_MODULE_DIR"; then
  dnl   AC_MSG_RESULT([not found])
  dnl   AC_MSG_ERROR([Please reinstall the my_module distribution])
  dnl fi

  dnl # --with-my_module -> add include path
  dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include)

  dnl # --with-my_module -> chech for lib and symbol presence
  dnl LIBNAME=my_module # you may want to change this
  dnl LIBSYMBOL=my_module # you most likely want to change this

  dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  dnl [
  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
  dnl   AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
  dnl ],[
  dnl   AC_MSG_ERROR([wrong my_module lib version or lib not found])
  dnl ],[
  dnl   -L$MY_MODULE_DIR/lib -lm -ldl
  dnl ])
  dnl
  dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)

  PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":

if test "$PHP_MY_MODULE" == "yes"; then dnl
    Action.. PHP_EXTENSION(my_module, $ext_shared)
    fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.

Prev | Home | Next
Source Layout | Up | Creating Extensions


Creating Extensions

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Example 46-2 shows the source.

Example 46-2. A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Note: The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.

Compiling Modules

There are basically two ways to compile modules:

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:

--enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module

The module shown earlier in Example 46-2 can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually. To compile your modules manually, you need the following commands:

Action | Command
Compiling | cc -fpic -DCOMPILE_DL_FIRST_MODULE=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linking | cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>

The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL_FIRST_MODULE to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)

Prev | Home | Next
PHP's Automatic Build System | Up | Using Extensions


Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in Example 46-3. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Warning

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

Example 46-3. A test file for first_module.so.

&#60;?php

// remove next comment if necessary
// dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent '$param' and got '$return'");

?&#62;

Calling this PHP file should output the following: We sent '2' and got '2'

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.

Prev | Home | Next
Creating Extensions | Up | Troubleshooting


Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.

Prev | Home | Next
Using Extensions | Up | Source Discussion


Source Discussion

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.

Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions

Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.

Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:

ZEND_FUNCTION ( my_function );

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:

void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function( int ht
                    , zval * return_value
                    , zval * this_ptr
                    , int return_value_used
                    , zend_executor_globals * executor_globals
                    );

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Table 46-1 for descriptions).

Table 46-1. Zend's Parameters to Functions Called from PHP

Parameter | Description
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH().

Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Example 46-4.

Example 46-4. Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;

Entry | Description
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.

In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Note: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Table 46-2 shows a list of all the macros that you can use to define functions.

Table 46-2. Macros for Defining Functions

Macro Name | Description
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.

Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Example 46-5.

Example 46-5. Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

    struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;

[ Rest of the structure is not interesting here ]

};

Entry | Description
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions | Points to the Zend function block, discussed in the preceding section.
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:

zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Table 46-3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

Table 46-3. Macros to Declare Startup and Shutdown Functions

Macro | Description
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:

#if COMPILE_DL_FIRSTMOD
     ZEND_GET_MODULE(firstmod)
#endif

The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.

Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:

ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).

Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.

Prev | Home | Next
Troubleshooting | Up | Accepting Arguments


Accepting Arguments

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.

Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:

if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message like: "Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5"

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:

ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."

Retrieving Arguments

New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameters, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:

int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:

Warning - ini_get_all() requires at most 1 parameter, 2 given
     Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:

/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

/* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.

int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:

long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.

Old way of retrieving arguments (deprecated)

Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():

zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
  WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:

zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.

Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:

zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 4)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Example 46-6. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Example 46-6. PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.

Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Table 46-4).

Note: All conversion functions expect a **zval as parameter.

Table 46-4. Argument Conversion Functions

Function | Description
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty.

Note: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figure 46-2 shows the output.

Figure 46-2. Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:

zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in Example 46-7.

Example 46-7. PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;					/* long value */
    double dval;				/* double value */
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;				/* hash table value */
    struct {
        zend_class_entry *ce;
        HashTable *properties;
    } obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;		/* value */
    unsigned char type;	/* active type */
    unsigned char is_ref;
    short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Table 46-5, Table 46-6 and Table 46-7.

Table 46-5. Zend zval Structure

Entry | Description
value | Union containing this variable's contents. See Table 46-6 for a description.
type | Contains this variable's type. For a list of available types, see Table 46-7.
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.

Table 46-6. Zend zvalue_value Structure

Entry | Description
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval | Use this property if the variable is of the type IS_DOUBLE.
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
ht | This entry points to the variable's hash table entry if the variable is an array.
obj | Use this property if the variable is of the type IS_OBJECT.

Table 46-7. Zend Variable Type Constants

Constant | Description
IS_NULL | Denotes a NULL (empty) value.
IS_LONG | A long (integer) value.
IS_DOUBLE | A double (floating point) value.
IS_STRING | A string.
IS_ARRAY | Denotes an array.
IS_OBJECT | An object.
IS_BOOL | A Boolean value.
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT | A constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.

Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:

my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Example 46-8.

Example 46-8. Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(parameter, 10);

Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:

zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.

Prev | Home | Next
Source Discussion | Up | Creating Variables


Creating Variables

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.

Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);

/* the variable is now accessible to the script by using $new_variable_name */

The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Example 46-9 shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

Example 46-9. Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}

Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Example 46-10).

Example 46-10. Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long->type = IS_LONG;
new_long->value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);

Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.

zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double->type = IS_DOUBLE;
new_double->value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);

Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:

zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string->type = IS_STRING;
new_string->value.str.len = strlen(string_contents);
new_string->value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:

new_string->type = IS_STRING;
new_string->value.str.len = 0;
new_string->value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);

Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:

zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool->type = IS_BOOL;
new_bool->value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).

Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().

zval *new_array;

MAKE_STD_ZVAL(new_array);

array_init(new_array);
array_init() always returns SUCCESS.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Table 46-8, Table 46-9 and Table 46-10 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Table 46-8. Zend's API for Associative Arrays

Function | Description
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long.
add_assoc_unset(zval *array, char *key);() | Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

Table 46-9. Zend's API for Indexed Arrays, Part 1

Function | Description
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long.
add_index_unset(zval *array, uint idx);() | Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

Table 46-10. Zend's API for Indexed Arrays, Part 2

Function | Description
add_next_index_long(zval *array, long n);() | Adds an element of type long.
add_next_index_unset(zval *array);() | Adds an unset element.
add_next_index_bool(zval *array, int b);() | Adds a Boolean element.
add_next_index_resource(zval *array, int r);() | Adds a resource to the array.
add_next_index_double(zval *array, double d);() | Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update() for associative arrays (see Example 46-11) and zend_hash_index_update() for indexed arrays (see Example 46-12):

Example 46-11. Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Example 46-12. Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array->value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.

Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():

zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Table 46-11 to add members to your object.

Table 46-11. Zend's API for Object Creation

Function | Description
add_property_long(zval *object, char *key, long l);() | Adds a long to the object.
add_property_unset(zval *object, char *key);() | Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() | Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

Note: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:

ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ld | Normal resource destruction handler callback
pld | Pesistent resource destruction handler callback
type_name | A string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.

The return value is a unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:

void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {

    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:

typedef struct {

    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

Note: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:

int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);

rsrc_result | This is an already initialized zval * container.
rsrc_pointer | Your resource pointer you want to store.
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.

The return value is a unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:

rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquely identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
RETURN_RESOURCE(rsrc_id)

Note: It is common practice that if you want to return the resource immediately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:

ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)

rsrc | This is your pointer which will point to your previously registered resource.
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.

This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.

Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Table 46-12 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Table 46-12. Macros for Global Variable Creation

Macro | Description
SET_VAR_STRING(name, value) | Creates a new string.
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value) | Creates a new long.
SET_VAR_DOUBLE(name, value) | Creates a new double.

Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Table 46-13. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a inary OR:
// register a new constant of type "long"
     REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
     CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

Table 46-13. Macros for Creating Constants

Macro | Description
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

Prev | Home | Next
Accepting Arguments | Up | Duplicating Variable Contents: The Copy Constructor


Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
   return;
}

// do modifications to the parameter here

// now we want to return the modified container:
*return_value = *parameter;
zval_copy_ctor(return_value);

The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.

Prev | Home | Next
Creating Variables | Up | Returning Values


Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Table 46-14 and Table 46-15.

Note: The macros in Table 46-14 automatically return from your function, those in Table 46-15 only set the return value; they don't return from your function.

Table 46-14. Predefined Macros for Returning Values from a Function

Macro | Description
RETURN_RESOURCE(resource) | Returns a resource.
RETURN_BOOL(bool) | Returns a Boolean.
RETURN_NULL() | Returns nothing (a NULL value).
RETURN_LONG(long) | Returns a long.
RETURN_DOUBLE(double) | Returns a double.
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING() | Returns an empty string.
RETURN_FALSE | Returns Boolean false.
RETURN_TRUE | Returns Boolean true.

Table 46-15. Predefined Macros for Setting the Return Value of a Function

Macro | Description
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource.
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value.
RETVAL_NULL | Sets the return value to NULL.
RETVAL_LONG(long) | Sets the return value to the specified long.
RETVAL_DOUBLE(double) | Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING | Sets the return value to an empty string.
RETVAL_FALSE | Sets the return value to Boolean false.
RETVAL_TRUE | Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.

Prev | Home | Next
Duplicating Variable Contents: The Copy Constructor | Up | Printing Information


Printing Information

Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.

zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.

zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.

zend_error(E_WARNING, "This function has been called with empty arguments");
Table 46-16 shows a list of possible values (see Figure 46-3). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.

Table 46-16. Zend's Predefined Error Messages.

Error | Description
E_ERROR | Signals an error and terminates execution of the script immediately .
E_WARNING | Signals a generic warning. Execution continues.
E_PARSE | Signals a parser error. Execution continues.
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules.

Figure 46-3. Display of warning messages in the browser.

Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Example 46-13 shows a source example and its output. To print the table footer, use php_info_print_table_end().

Example 46-13. Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();

Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Example 46-14.

Example 46-14. Printing execution information.

zend_printf("The name of the current function is %s<br>", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(TSRMLS_C));

Prev | Home | Next
Returning Values | Up | Startup and Shutdown Functions


Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.

Prev | Home | Next
Printing Information | Up | Calling User Functions


Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_separation);

Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Example 46-15 shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Example 46-15. Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type\n", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{
    echo "We are in the test function!\n";
    return 'hello';
}

$return_value = call_userland("test_function");

echo "Return value: '$return_value'";
?>

The above example will output:

We are in the test function! We have 3 as type Return value: 'hello'

Prev | Home | Next
Startup and Shutdown Functions | Up | Initialization File Support


Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.

PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:

PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Table 46-17.

Table 46-17. Macros to Access Initialization Entries in PHP

Macro | Description
INI_INT(name) | Returns the current value of entry name as integer (long).
INI_FLT(name) | Returns the current value of entry name as float (double).
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double).
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():

ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}

Prev | Home | Next
Calling User Functions | Up | Where to Go from Here


Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.

Prev | Home | Next
Initialization File Support | Up | Reference: Some Configuration Macros


Reference: Some Configuration Macros

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Table 46-18.

Table 46-18. M4 Macros for config.m4

Macro | Description
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

Prev | Home | Next
Where to Go from Here | Up | API Macros


API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see Table 46-19).

Table 46-19. API Macros for Accessing zval Containers

Macro | Refers to
Z_LVAL(zval) | (zval).value.lval
Z_DVAL(zval) | (zval).value.dval
Z_STRVAL(zval) | (zval).value.str.val
Z_STRLEN(zval) | (zval).value.str.len
Z_ARRVAL(zval) | (zval).value.ht
Z_LVAL_P(zval) | (*zval).value.lval
Z_DVAL_P(zval) | (*zval).value.dval
Z_STRVAL_P(zval_p) | (*zval).value.str.val
Z_STRLEN_P(zval_p) | (*zval).value.str.len
Z_ARRVAL_P(zval_p) | (*zval).value.ht
Z_LVAL_PP(zval_pp) | (**zval).value.lval
Z_DVAL_PP(zval_pp) | (**zval).value.dval
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht

Prev | Home | Next
Reference: Some Configuration Macros | Up | API Function and Macro reference (work in progress)


Streams API for PHP Extension Authors

PHP Manual
Prev Next

Chapter 44. Streams API for PHP Extension Authors

Table of Contents
Overview
Streams Basics
Streams as Resources
Streams Common API Reference
Streams Dir API Reference
Streams File API Reference
Streams Socket API Reference
Streams Structures
Streams Constants

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional context parameter, accepted by most stream creation functions, is passed to the wrapper's stream_opener method to fine-tune the behavior of the wrapper.

Any stream, once opened, can also have any number of filters applied to it, which process data as it is read from/written to the stream.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!

Note: The functions in this chapter are for use in the PHP source code and are not PHP functions. Userland stream functions can be found in the Stream Reference.

Prev | Home | Next
PHP and Zend Engine Internals | Up | Streams Basics


Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

Example 44-1. simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];

        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

Table 44-1. ANSI stdio equivalent functions in the Streams API

ANSI Stdio Function | PHP Streams Function | Notes
fopen | php_stream_open_wrapper | Streams includes additional parameters
fclose | php_stream_close |
fgets | php_stream_gets |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseek | php_stream_seek |
ftell | php_stream_tell |
rewind | php_stream_rewind |
feof | php_stream_eof |
fgetc | php_stream_getc |
fputc | php_stream_putc |
fflush | php_stream_flush |
puts | php_stream_puts | Same semantics as puts, NOT fputs
fstat | php_stream_stat | Streams has a richer stat structure

Prev | Home | Next
Streams API for PHP Extension Authors | Up | Streams as Resources


Streams as Resources

All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:

Example 44-2. How to accept a stream as a parameter

PHP_FUNCTION(example_write_hello)
{
    zval *zstream;
    php_stream *stream;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream))
        return;

    php_stream_from_zval(stream, &zstream);

    /* you can now use the stream.  However, you do not "own" the
        stream, the script does.  That means you MUST NOT close the
        stream, because it will cause PHP to crash! */

    php_stream_write(stream, "hello\n");

    RETURN_TRUE();
}

Example 44-3. How to return a stream from a function

PHP_FUNCTION(example_open_php_home_page)
{
    php_stream *stream;

    stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);

    php_stream_to_zval(stream, return_value);

    /* after this point, the stream is "owned" by the script.
        If you close it now, you will crash PHP! */
}

Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.

Note: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.

In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().

Prev | Home | Next
Streams Basics | Up | Streams Common API Reference


Streams Dir API Reference

Table of Contents
php_stream_opendir -- Open a directory for file enumeration
php_stream_readdir -- Fetch the next directory entry from an opened dir
php_stream_rewinddir -- Rewind a directory stream to the first entry
php_stream_closedir -- Close a directory stream and release resources

The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).

Prev | Home | Next
php_stream_filter_unregister_factory | Up | php_stream_opendir


Streams File API Reference

Table of Contents
php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream
php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream
php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

Prev | Home | Next
php_stream_closedir | Up | php_stream_fopen_from_file


Streams Socket API Reference

Table of Contents
php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream
php_stream_sock_open_host -- Open a connection to a host and return a stream
php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

Prev | Home | Next
php_stream_fopen_temporary_file | Up | php_stream_sock_open_from_socket


Streams Structures

Table of Contents
struct php_stream_statbuf -- Holds information about a file or URL
struct php_stream_dirent -- Holds information about a single file during dir scanning
struct php_stream_ops -- Holds member functions for a stream implementation
struct php_stream_wrapper -- Holds wrapper properties and pointer to operations
struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation
struct php_stream_filter -- Holds filter properties and pointer to operations
struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

Prev | Home | Next
php_stream_sock_open_unix | Up | struct php_stream_statbuf


Streams Constants

Table of Contents
Stream open options -- Affects the operation of stream factory functions

Prev | Home | Next
struct php_stream_filter_ops | Up | Stream open options


FAQ: Frequently Asked Questions

PHP Manual
Prev Next

VIII. FAQ: Frequently Asked Questions

Table of Contents
49. General Information
50. Mailing lists
51. Obtaining PHP
52. Database issues
53. Installation FAQ
54. Build Problems
55. Using PHP
56. PHP and HTML
57. PHP and COM
58. PHP and other languages
59. Migrating from PHP 2 to PHP 3
60. Migrating from PHP 3 to PHP 4
61. Migrating from PHP 4 to PHP 5
62. Miscellaneous Questions

Prev | Home | Next
Reporting Errors |  | General Information


General Information

PHP Manual
Prev Next

Chapter 49. General Information

This section holds the most general questions about PHP: what it is and what it does.

1. What is PHP?
2. What does PHP stand for?
3. What is the relation between the versions?
4. Can I run several versions of PHP at the same time?
5. What are the differences between PHP 3 and PHP 4?
6. I think I found a bug! Who should I tell?

1. What is PHP?

From the preface of the manual:

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

A nice introduction to PHP by Stig Sæther Bakken can be found at http://www.zend.com/zend/art/intro.php on the Zend website. Also, much of the PHP Conference Material is freely available.

2. What does PHP stand for?

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. The curious can visit Free On-Line Dictionary of Computing for more information on recursive acronyms.

3. What is the relation between the versions?

PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOP features.

4. Can I run several versions of PHP at the same time?

Yes. See the INSTALL file that is included in the PHP 4 source distribution. Also, read the related appendix.

5. What are the differences between PHP 3 and PHP 4?

There are a couple of articles written on this by the authors of PHP 4. Here's a list of some of the more important new features:

  • Extended API module

  • Generalized build process under Unix

  • Generic web server interface that also supports multi-threaded web servers

  • Improved syntax highlighter

  • Native HTTP session support

  • Output buffering support

  • More powerful configuration system

  • Reference counting

Please see the What's new in PHP 4 overview for a detailed explanation of these features and more. If you're migrating from PHP 3 to PHP 4, also read the related appendix.

6. I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net/.

Prev | Home | Next
FAQ: Frequently Asked Questions | Up | Mailing lists


Mailing lists

PHP Manual
Prev Next

Chapter 50. Mailing lists

This section holds questions about how to get in touch with the PHP community. The best way is the mailing lists.

1. Are there any PHP mailing lists?
2. Are there any other communities?
3. Help! I can't seem to subscribe/unsubscribe to/from one of the mailing lists!
4. Is there an archive of the mailing lists anywhere?
5. What can I ask the mailing list?
6. What information should I include when posting to the mailing list?

1. Are there any PHP mailing lists?

Of course! There are many mailing lists for several subjects. A whole list of mailing lists can be found on our Support page.

The most general mailing list is php-general. To subscribe, send mail to php-general-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message. To unsubscribe, send mail to php-general-unsubscribe@lists.php.net.

You can also subscribe and unsubscribe using the web interface on our Support page.

2. Are there any other communities?

There are countless of them around the world. We have links for example to some IRC servers and foreign language mailing lists on our Support page.

3. Help! I can't seem to subscribe/unsubscribe to/from one of the mailing lists!

If you have problems subscribing to or unsubscribing from the php-general mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.

4. Is there an archive of the mailing lists anywhere?

Yes, you will find a list of archive sites on the Support page. The mailing list articles are also archived as news messages. You can access the news server at news://news.php.net/ with a news client. There is also an experimental web interface for the news server at http://news.php.net/

5. What can I ask the mailing list?

Since PHP is growing more and more popular by the day the traffic has increased on the php-general mailing list and as of now the list gets about 150 to 200 posts a day. Because of this it is in everyone's interest that you use the list as a last resort when you have looked everywhere else.

Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP please read through all included documentation and README's. If you still can't find any information that helps you out you're more than welcome to use the mailing list.

Before asking questions, you may want to read the paper on How To Ask Questions The Smart Way as this is a good idea for everyone.

6. What information should I include when posting to the mailing list?

Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include what operating system you are running on, what version of PHP you're trying to set up, how you got it (pre-compiled, CVS, RPMs and so on), what you have done so far, where you got stuck and the exact error message.

This goes for any other problem as well. You have to include information on what you have done, where you got stuck, what you're trying to do and, if applicable, exact error messages. If you're having problems with your source code you need to include the part of the code that isn't working. Do not include more code than necessary though! It makes the post hard to read and a lot of people might just skip it all together because of this. If you're unsure about how much information to include in the mail it's better that you include to much than to little.

Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.

And lastly, you're encouraged to read the paper on How To Ask Questions The Smart Way as this will be a great help for everyone, especially yourself.

Prev | Home | Next
General Information | Up | Obtaining PHP


Obtaining PHP

PHP Manual
Prev Next

Chapter 51. Obtaining PHP

This section has details about PHP download locations, and OS issues.

1. Where can I obtain PHP?
2. Are pre-compiled binary versions available?
3. Where can I get libraries needed to compile some of the optional PHP extensions?
4. How do I get these libraries to work?
5. I got the latest version of the PHP source code from the CVS repository on my Windows machine, what do I need to compile it?
6. Where do I find the Browser Capabilities File?

1. Where can I obtain PHP?

You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://www.php.net/anoncvs.php.

2. Are pre-compiled binary versions available?

We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our Downloads page, for Linux binaries, please visit your distribution's website.

3. Where can I get libraries needed to compile some of the optional PHP extensions?

Note: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.

  • LDAP (Unix).

  • LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK

  • free LDAP server.

  • Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.

  • SNMP* (Unix): .

  • GD* (Unix/Win).

  • mSQL* (Unix).

  • PostgreSQL (Unix).

  • IMAP* (Win/Unix).

  • Sybase-CT* (Linux, libc5) : Available locally.

  • FreeType (libttf):.

  • ZLib (Unix/Win32).

  • expat XML parser (Unix/Win32).

  • PDFLib.

  • mcrypt.

  • mhash.

  • t1lib.

  • dmalloc.

  • aspell.

  • readline.

4. How do I get these libraries to work?

You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.

5. I got the latest version of the PHP source code from the CVS repository on my Windows machine, what do I need to compile it?

First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need some support files. See the manual section about building PHP from source on Windows.

6. Where do I find the Browser Capabilities File?

You can find a browscap.ini file at http://browsers.garykeith.com/downloads.asp.

Prev | Home | Next
Mailing lists | Up | Database issues


Database issues

PHP Manual
Prev Next

Chapter 52. Database issues

This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.

1. I heard it's possible to access Microsoft SQL Server from PHP. How?
2. Can I access Microsoft Access databases?
3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?
4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?
5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
6. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?

1. I heard it's possible to access Microsoft SQL Server from PHP. How?

On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.

On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.

2. Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.

If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our website for a free download.

One option that has proved successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

  • Install MySQL on your platform according to instructions with MySQL. Latest available from http://www.mysql.com/ No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.

  • Download the MyODBC for Windows driver from the MySQL site. Install it on your Windows machine. You can test the operation with the utilities included with this program.

  • Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.

  • Install Access with a full install, this makes sure you get the proper add-ins... at the least you will need ODBC support and the linked table manager.

  • Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks:

  • You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.

  • When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access

  • If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.

3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?

Most likely what has happened is, PHP 4 was compiled with the --with-mysql option, without specifying the path to MySQL. This means PHP is using its built-in MySQL client library. If your system is running applications, such as PHP 3 as a concurrent Apache module, or auth-mysql, that use other versions of MySQL clients, then there is a conflict between the two differing versions of those clients.

Recompiling PHP 4, and adding the path to MySQL to the flag, '--with-mysql=/your/path/to/mysql' usually solves the problem.

4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?

Yes. There will always be MySQL support in PHP of one kind or another. The only change in PHP 5 is that we are no longer bundling the client library itself. Some reasons in no particular order:

  • Most systems these days already have the client library installed.

  • Given the above, having multiple versions of the library can get messy. For example, if you link mod_auth_mysql against one version and PHP against another, and then enable both in Apache, you get a nice fat crash. Also, the bundled library didn't always play well with the installed server version. The most obvious symptom of this being disagreement over where to find the mysql.socket Unix domain socket file.

  • Maintenance was somewhat lax and it was falling further and further behind the released version.

  • Future versions of the library are under the GPL and thus we don't have an upgrade path since we cannot bundle a GPL'ed library in a BSD/Apache-style licensed project. A clean break in PHP 5 seemed like the best option.

This won't actually affect that many people. Unix users, at least the ones who know what they are doing, tend to always build PHP against their system's libmyqlclient library simply by adding the --with-mysql=/usr option when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. For more details, see the MySQL Reference for installation instructions. Also, be sure libmysql.dll is available to the systems PATH. For more details on how, read the FAQ on setting up the Windows systems PATH. Because libmysql.dll (and many other PHP related files) exist in the PHP folder, you'll want to add the PHP folder to your systems PATH.

5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?

If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.

6. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:

&#60;?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?&#62;
or
&#60;?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?&#62;

Prev | Home | Next
Obtaining PHP | Up | Installation FAQ


Installation FAQ

PHP Manual
Prev Next

Chapter 53. Installation FAQ

This section holds common questions about the way to install PHP. PHP is available for almost any OS (except maybe for MacOS before OSX), and almost any web server.

To install PHP, follow the instructions in Part II in PHP Manual.

1. Why shouldn't I use Apache2 with a threaded MPM in a production environment?
2. Unix/Windows: Where should my php.ini file be located?
3. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
4. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
5. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! What's going on here?
6. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
7. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
8. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
9. Some operating systems: I have installed PHP without errors, but when I try to start apache I get undefined symbol errors:
[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress
10. Windows: I have installed PHP, but when I to access a PHP script file via my browser, I get the error:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:
11. Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!
12. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..
13. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.
14. How do I add my PHP directory to the PATH on Windows?
15. How do I make the php.ini file available to PHP on windows?
16. Is it possible to use Apache content negotiation (MultiViews option) with PHP?
17. Is PHP limited to process GET and POST request methods only?

1. Why shouldn't I use Apache2 with a threaded MPM in a production environment?

PHP is glue. It is the glue used to build cool web applications by sticking dozens of 3rd-party libraries together and making it all appear as one coherent entity through an intuitive and easy to learn language interface. The flexibility and power of PHP relies on the stability and robustness of the underlying platform. It needs a working OS, a working web server and working 3rd-party libraries to glue together. When any of these stop working PHP needs ways to identify the problems and fix them quickly. When you make the underlying framework more complex by not having completely separate execution threads, completely separate memory segments and a strong sandbox for each request to play in, feet of clay are introduced into PHP's system.

If you feel you have to use a threaded MPM, look at a FastCGI configuration where PHP is running in its own memory space.

And finally, this warning against using a threaded MPM is not as strong for Windows systems because most libraries on that platform tend to be threadsafe.

2. Unix/Windows: Where should my php.ini file be located?

By default on Unix it should be in /usr/local/lib which is <install-path>/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:

--with-config-file-path=/etc
And then you would copy php.ini-dist from the distribution to /etc/php.ini and edit it to make any local changes you want.

--with-config-file-scan-dir=PATH

On Windows the default path for the php.ini file is the Windows directory. If you're using the Apache webserver, php.ini is first searched in the Apaches install directory, e.g. c:\program files\apache group\apache. This way you can have different php.ini files for different versions of Apache on the same machine.

See also the chapter about the configuration file.

3. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?

This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:

  • Stop your httpd processes

  • gdb httpd

  • Stop your httpd processes

  • > run -X -f /path/to/httpd.conf

  • Then fetch the URL causing the problem with your browser

  • > run -X -f /path/to/httpd.conf

  • If you are getting a core dump, gdb should inform you of this now

  • type: bt

  • You should include your backtrace in your bug report. This should be submitted to http://bugs.php.net/

If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x

4. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?

Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your httpd.conf file:

# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php3_module        modules/libphp3.so     # for PHP 3
LoadModule php4_module        modules/libphp4.so     # for PHP 4
LoadModule perl_module        modules/libperl.so
And add:
AddType application/x-httpd-php3 .php3    # for PHP 3
AddType application/x-httpd-php .php      # for PHP 4
... to the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

5. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! What's going on here?

Due to the way PHP 3 built, it is not easy to build a complete flexible PHP RPM. This issue is addressed in PHP 4. For PHP 3, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP 3, read on...

The RPM packagers are setting up the RPMS to install without database support to simplify installations and because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.

This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.

Of course all of this information can be adjusted for any database server that PHP supports. We will assume you installed MySQL and Apache completely with RPMS for this example as well.

  • First remove mod_php3 :

    rpm -e mod_php3

  • Then get the source rpm and INSTALL it, NOT --rebuild

    rpm -Uvh mod_php3-3.0.5-2.src.rpm

  • Then edit the /usr/src/redhat/SPECS/mod_php3.spec file

    In the %build section add the database support you want, and the path.

    For MySQL you would add --with-mysql=/usr The %build section will look something like this:

    ./configure --prefix=/usr \
--with-apxs=/usr/sbin/apxs \
--with-config-file-path=/usr/lib \
--enable-debug=no \
--enable-safe-mode \
--with-exec-dir=/usr/bin \
--with-mysql=/usr \
--with-system-regex

  • Once this modification is made then build the binary rpm as follows:

    rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

  • Then install the rpm

    rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

Make sure you restart Apache, and you now have PHP 3 with MySQL support using RPM's. Note that it is probably much easier to just build from the distribution tarball of PHP 3 and follow the instructions in INSTALL.REDHAT found in that distribution.

6. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.

7. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.

Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.

8. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.

Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.

9. Some operating systems: I have installed PHP without errors, but when I try to start apache I get undefined symbol errors:

[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib, others do not. This is also covered in the MySQL FAQ.

10. Windows: I have installed PHP, but when I to access a PHP script file via my browser, I get the error:

cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working.

Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:

  • File permissions on your PHP script, php.exe, php4ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.

  • The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.

11. Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine. Also, you will want to read this faq.

12. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..

You must set the cgi.force_redirect directive to 0. It defaults to 1 so be sure the directive isn't commented out (with a ;). Like all directives, this is set in php.ini

Because the default is 1, it's critical that you're 100% sure that the correct php.ini file is being read. Read this faq for details.

13. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.

To be sure your php.ini is being read by PHP, make a call to phpinfo() and near the top will be a listing called Configuration File (php.ini). This will tell you where PHP is looking for php.ini and whether or not it's being read. If just a directory PATH exists than it's not being read and you should put your php.ini in that directory. If php.ini is included within the PATH than it is being read.

If php.ini is being read and you're running PHP as a module, then be sure to restart your web server after making changes to php.ini

14. How do I add my PHP directory to the PATH on Windows?

On Windows NT, 2000, XP and 2003:

  • Go to Control Panel and open the System icon (Start -> Settings -> Control Panel -> System, or just Start -> Control Panel -> System for Windows XP/2003)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System Variables' pane

  • Find the Path entry (you may need to scroll to find it)

  • Double click on the Path entry

  • Enter your PHP directory at the end, including ';' before (e.g. ;C:\php)

  • Press OK and restart your computer

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start -> Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Locate the line with PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... and add: ;C:\php to the end of the line

  • Save the file and restart your computer

Note: Be sure to reboot after following the steps above to ensure that the PATH changes are applied.

The PHP manual used to promote the copying of files into the Windows system directory, this is because this directory (C:\Windows, C:\WINNT, etc.) is by default in the systems PATH. Copying files into the Windows system directory has long since been deprecated and may cause problems.

15. How do I make the php.ini file available to PHP on windows?

There are several ways of doing this. If you are using Apache, read their installation specific instructions (Apache 1, Apache 2), otherwise you must set the PHPRC environment variable:

On Windows NT, 2000, XP and 2003:

  • Go to Control Panel and open the System icon (Start -> Settings -> Control Panel -> System, or just Start -> Control Panel -> System for Windows XP/2003)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System variables' pane

  • Click on 'New' and enter 'PHPRC' as the variable name and the directory where php.ini is located as the variable value (e.g. C:\php)

  • Press OK and restart your computer

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start -> Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Add a new line to the end of the file: set PHPRC=C:\php (replace C:\php with the directory where php.ini is located). Please note that the path cannot contain spaces. For instance, if you have installed PHP in C:\Program Files\PHP, you would enter C:\PROGRA~1\PHP instead.

  • Save the file and restart your computer

16. Is it possible to use Apache content negotiation (MultiViews option) with PHP?

If links to PHP files include extension, everything works perfect. This FAQ is only for the case when links to PHP files don't include extension and you want to use content negotiation to choose PHP files from URL with no extension. In this case, replace the line AddType application/x-httpd-php .php with:

# PHP 4
AddHandler php-script php
AddType text/html php

# PHP 5
AddHandler php5-script php
AddType text/html php
This solution doesn't work for Apache 1 as PHP module doesn't catch php-script.

17. Is PHP limited to process GET and POST request methods only?

No, it is possible to handle any request method, e.g. CONNECT. Proper response status can be sent with header(). If only GET and POST methods should be handled, it can be achieved with this Apache configuration:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

Prev | Home | Next
Database issues | Up | Build Problems


Build Problems

PHP Manual
Prev Next

Chapter 54. Build Problems

This section gathers most common errors that occur at build time.

1. I got the latest version of PHP using the anonymous CVS service, but there's no configure script!
2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
3. While configuring PHP (./configure), you come across an error similar to the following:
4. When I try to start Apache, I get the following message:
5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
8. When linking PHP, it complains about a number of undefined references.
9. I can't figure out how to build PHP with Apache 1.3.
10. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.
11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
13. When I try to build PHP using --with-apxs I get strange error messages.
14. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.
15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?
16. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
17. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.
18. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

1. I got the latest version of PHP using the anonymous CVS service, but there's no configure script!

You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)

2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!

You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify --with-apache=/path/to/apache and not --with-apache=/path/to/apache/src.

3. While configuring PHP (./configure), you come across an error similar to the following:

checking lex output file root... ./configure: lex: command not found
       configure: error: cannot find output from lex; giving up

Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.

4. When I try to start Apache, I get the following message:

fatal: relocation error: file /path/to/libphp4.so:
       symbol ap_block_alarms: referenced symbol not found

This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:

--enable-shared=max --enable-rule=SHARED_CORE

For more information, read the top-level Apache INSTALL file or the Apache DSO manual page.

5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!

You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:

CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.

You need to update your version of Bison. You can find the latest version at http://www.gnu.org/software/bison/bison.html.

7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.

Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running cp *.o functions and then re-running make to see if that helps. If it does, you should really upgrade to a recent version of GNU make.

8. When linking PHP, it complains about a number of undefined references.

Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.

If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the installation chapter for more information.

Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.

9. I can't figure out how to build PHP with Apache 1.3.

This is actually quite easy. Follow these steps carefully:

  • Grab the latest Apache 1.3 distribution from http://www.apache.org/dist/httpd/.

  • Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.

  • Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory.

  • Type make followed by make install to build PHP and copy the necessary files to the Apache distribution tree.

  • Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. Add to the file: AddModule modules/php4/libphp4.a.

  • Type: ./configure followed by make.

  • You should now have a PHP-enabled httpd binary!

Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.

10. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.

This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:

  • Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l

    If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.

  • Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3 (for PHP 3)

    or AddType application/x-httpd-php .php (for PHP 4)

    Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.

  • Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.

11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?

Note that the libphp4.a file is not supposed to exist. The apache process will create it!

12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.

This is a misleading error message from Apache that has been fixed in more recent versions.

13. When I try to build PHP using --with-apxs I get strange error messages.

There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command which apxs), it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
If this is what you see, you have found your problem. They may contain just spaces or other incorrect values, such as 'q()'. Change these lines to say:
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
The second possible problem should only be an issue on Red Hat 6.1 and 6.2. The apxs script Red Hat ships is broken. Look for this line:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
If you see the above line, change it to this:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Last, if you reconfigure/reinstall Apache, add a make clean to the process after ./configure and before make.

14. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.

During the make portion of installation, if you encounter problems that look similar to this:

microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

Your system is broken. You need to fix your /usr/include files by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
If that spews out errors, you know your include files are messed up.

15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?

First, it's important to realize that this is a Warning and not a fatal error. Because this is often the last output seen during make, it may seem like a fatal error but it's not. Of course, if you set your compiler to die on Warnings, it will. Also keep in mind that MySQL support is enabled by default.

Note: As of PHP 4.3.2, you'll also see the following text after the build (make) completes:

Build complete.
        (It is safe to ignore warnings about tempnam and tmpnam).

16. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?

Either you look at config.nice file, in the source tree of your current PHP installation or, if this is not available, you simply run a

&#60;?php phpinfo(); ?&#62;
script. On top of the output the ./configure line, that was used to build this PHP installation is shown.

17. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

Make sure your GD library and PHP are linked against the same depending libraries (e.g. libpng).

18. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

Using non-GNU utilities while compiling PHP may cause problems. Be sure to use GNU tools in order to be certain that compiling PHP will work. For example, on Solaris, using either the SunOS BSD-compatible or Solaris versions of sed will not work, but using the GNU or Sun POSIX (xpg4) versions of sed will work. Links: GNU sed, GNU flex, and GNU bison.

Prev | Home | Next
Installation FAQ | Up | Using PHP


Using PHP

PHP Manual
Prev Next

Chapter 55. Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
2. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
3. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?
4. When I do the following, the output is printed in the wrong order:
&#60;?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?&#62;
what's going on?
5. Hey, what happened to my newlines?
&#60;pre&#62;
&#60;?php echo "This should be the first line."; ?&#62;
&#60;?php echo "This should show up after the new line above."; ?&#62;
&#60;/pre&#62;
6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
7. I need to access information in the request header directly. How can I do this?
8. When I try to use authentication with IIS I get 'No Input file specified'.
9. Windows: I can't access files shared on another computer using IIS
10. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
11. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
12. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
13. Where can I find a complete list of variables are available to me in PHP?
14. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.
15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.

&#60;?php
$empty = $post = array();
foreach ($_POST as $varname =&#62; $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "&#60;pre&#62;";
if (empty($empty)) {
    print "None of the POSTed values are empty, posted:\n";
    var_dump($post);
} else {
    print "We have " . count($empty) . " empty values\n";
    print "Posted:\n"; var_dump($post);
    print "Empty:\n";  var_dump($empty);
    exit;
}
?&#62;

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

2. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.

The function addslashes() will do this. See also mysql_escape_string(). You may also strip backslashes with stripslashes().

directive note: magic_quotes_gpc: The PHP directive magic_quotes_gpc defaults to on. It essentially runs addslashes() on all your GET, POST, and COOKIE data. You may use stripslashes() to strip them.

3. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?

The PHP function stripslashes() will strip those backslashes from your string. Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on.

directive note: magic_quotes_gpc: The PHP directive magic_quotes_gpc defaults to on. It essentially runs addslashes() on all your GET, POST, and COOKIE data. You may use stripslashes() to strip them.

4. When I do the following, the output is printed in the wrong order:

&#60;?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?&#62;
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return() the value, not echo() it.

5. Hey, what happened to my newlines?

&#60;pre&#62;
&#60;?php echo "This should be the first line."; ?&#62;
&#60;?php echo "This should show up after the new line above."; ?&#62;
&#60;/pre&#62;

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.

7. I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:

&#60;?php
$headers = getallheaders();
foreach ($headers as $name =&#62; $content) {
    echo "headers[$name] = $content&#60;br /&#62;\n";
}
?&#62;

See also
apache_lookup_uri(),
apache_response_headers(), and
fsockopen()

8. When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/kb/q160422/ and the manual section on HTTP Authentication .

9. Windows: I can't access files shared on another computer using IIS

You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.

You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.

10. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.

Netscape is more strict regarding HTML tags (such as tables) then IE. Running your HTML output through a HTML validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.

Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.

11. How am I supposed to mix XML and PHP? It complains about my <?xml tags!

In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is on.

12. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?

One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.

13. Where can I find a complete list of variables are available to me in PHP?

Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.

register_globals: important note: Since PHP 4.2.0, the default value for the PHP directive register_globals is off, and it is completely removed as of PHP 6.0.0. The PHP community encourages all to not rely on this directive but instead use other means, such as the superglobals.

14. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.

There are a few alternatives written in PHP such as http://www.ros.co.nz/pdf/, http://www.fpdf.org/, http://www.gnuvox.com/pdf4php/, and http://www.potentialtech.com/ppl.php. There is also the Panda module.

15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?

It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.

If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.

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

16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), these are case insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. You may not use these shorthand notations outside of php.ini, instead use an integer value of bytes. See the ini_get() documentation for an example on how to convert these values.

Prev | Home | Next
Build Problems | Up | PHP and HTML


PHP and HTML

PHP Manual
Prev Next

Chapter 56. PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.

1. What encoding/decoding do I need when I pass a value through a form/URL?
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
3. How do I create arrays in a HTML <form>?
4. How do I get all the results from a select multiple HTML tag?
5. How can I pass a variable from Javascript to PHP?

1. What encoding/decoding do I need when I pass a value through a form/URL?

There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:

  • HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.

  • URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().

Example 56-1. A hidden HTML form element

&#60;?php
    echo "&#60;input type='hidden' value='" . htmlspecialchars($data) . "' /&#62;\n";
?&#62;

Note: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.

Example 56-2. Data to be edited by the user

&#60;?php
    echo "&#60;textarea name='mydata'&#62;\n";
    echo htmlspecialchars($data)."\n";
    echo "&#60;/textarea&#62;";
?&#62;

Note: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols.

Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.

Example 56-3. In a URL

&#60;?php
    echo "&#60;a href='" . htmlspecialchars("/nextpage.php?stage=23&#38;data=" .
        urlencode($data)) . "'&#62;\n";
?&#62;

Note: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Note: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencoded() the data.

You'll notice that the & in the URL is replaced by &amp;. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.

2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

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="foo" />
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from outside of PHP. For example, $_GET['foo_x'].

Note: Spaces in request variable names are converted to underscores.

3. How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
The AnotherArray array will now contain the keys 0, 1, email and phone.

Note: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables from outside PHP.

4. How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.

<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

variable = documents.forms[0].elements['var[]'];

5. How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

&#60;?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."&#60;br /&#62;\n";
  echo "Screen height is: ". $_GET['height'] ."&#60;br /&#62;\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "&#60;script language='javascript'&#62;\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&#38;width=\" + screen.width + \"&#38;height=\" + screen.height;\n";
  echo "&#60;/script&#62;\n";
  exit();
}
?&#62;

Prev | Home | Next
Using PHP | Up | PHP and COM


PHP and COM

PHP Manual
Prev Next

Chapter 57. PHP and COM

PHP can be used to access COM and DCOM objects on Win32 platforms.

1. I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?
2. What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?
3. Is it possible manipulate visual objects in PHP ?
4. Can I store a COM object in a session ?
5. How can I trap COM errors ?
6. Can I generate DLL files from PHP scripts like i can in Perl ?
7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
8. How can I run COM object from remote server ?
9. I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?
10. Is it possible to load/manipulate an ActiveX object in a page with PHP ?
11. Is it possible to get a running instance of a component ?
12. Is there a way to handle an event sent from COM object ?
13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?
14. So PHP works with COM, how about COM+ ?
15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?

1. I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?

If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.

2. What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?

There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.

3. Is it possible manipulate visual objects in PHP ?

Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.

4. Can I store a COM object in a session ?

No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.

5. How can I trap COM errors ?

In PHP 5, the COM extension throws com_exception exceptions, which you can catch and then inspect the code member to determine what to do next.

In PHP 4 it's not possible to trap COM errors beside the ways provided by PHP itself (@, track_errors, ..).

6. Can I generate DLL files from PHP scripts like i can in Perl ?

No, unfortunately there is no such tool available for PHP.

7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?

This error can have multiple reasons:

  • the CLSID is wrong

  • the requested DLL is missing

  • the requested component doesn't implement the IDispatch interface

8. How can I run COM object from remote server ?

Exactly like you run local objects. You only have to pass the IP of the remote machine as second parameter to the COM constructor.

Make sure that you have set com.allow_dcom =TRUE in your php.ini.

9. I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?

Edit your php.ini and set com.allow_dcom =TRUE.

10. Is it possible to load/manipulate an ActiveX object in a page with PHP ?

This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.

11. Is it possible to get a running instance of a component ?

This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:

&#60;?php
$word = new COM("C:\docs\word.doc");
?&#62;

This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.

12. Is there a way to handle an event sent from COM object ?

You can define an event sink and bind it using com_event_sink(). You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.

13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?

The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let me know :)

14. So PHP works with COM, how about COM+ ?

COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.

15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?

PHP itself doesn't handle transactions yet. Thus if an error occurs no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.

Prev | Home | Next
PHP and HTML | Up | PHP and other languages


PHP and other languages

PHP Manual
Prev Next

Chapter 58. PHP and other languages

PHP is the best language for web programing, but what about other languages?

1. PHP vs. ASP?
2. Is there an ASP to PHP converter?
3. PHP vs. Cold Fusion?
4. PHP vs. Perl?

1. PHP vs. ASP?

ASP is not really a language in itself, it's an acronym for Active Server Pages, the actual language used to program ASP with is Visual Basic Script or JScript. The biggest drawback of ASP is that it's a proprietary system that is natively used only on Microsoft Internet Information Server (IIS). This limits it's availability to Win32 based servers. There are a couple of projects in the works that allows ASP to run in other environments and webservers: InstantASP from Halcyon (commercial), Chili!Soft ASP from Chili!Soft (commercial). ASP is said to be a slower and more cumbersome language than PHP, less stable as well. Some of the pros of ASP is that since it primarily uses VBScript it's relatively easy to pick up the language if you're already know how to program in Visual Basic. ASP support is also enabled by default in the IIS server making it easy to get up and running. The components built in ASP are really limited, so if you need to use "advanced" features like interacting with FTP servers, you need to buy additional components.

2. Is there an ASP to PHP converter?

Yes, the server-side asp2php is the one most often referred to as well as this client-side option.

3. PHP vs. Cold Fusion?

PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. Cold Fusion has better error handling, database abstraction and date parsing although database abstraction is addressed in PHP 4. Another thing that is listed as one of Cold Fusion's strengths is its excellent search engine, but it has been mentioned that a search engine is not something that should be included in a web scripting language. PHP runs on almost every platform there is; Cold Fusion is only available on Win32, Solaris, Linux and HP/UX. Cold Fusion has a good IDE and is generally easier to get started with, whereas PHP initially requires more programming knowledge. Cold Fusion is designed with non-programmers in mind, while PHP is focused on programmers.

A great summary by Michael J Sheldon on this topic has been posted to the PHP mailing list. A copy can be found at http://marc.theaimsgroup.com/?l=php-general&m=95602167412542&w=1.

4. PHP vs. Perl?

The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and can because of this get very complicated. The flexibility / complexity of Perl makes it easier to write code that another author / coder has a hard time reading. PHP has a less confusing and stricter format without losing flexibility. PHP is easier to integrate into existing HTML than Perl. PHP has pretty much all the 'good' functionality of Perl: constructs, syntax and so on, without making it as complicated as Perl can be. Perl is a very tried and true language, it's been around since the late eighties, but PHP is maturing very quickly.

Prev | Home | Next
PHP and COM | Up | Migrating from PHP 2 to PHP 3


Migrating from PHP 2 to PHP 3

PHP Manual
Prev Next

Chapter 59. Migrating from PHP 2 to PHP 3

PHP has already a long history behind him: Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.

1. Migrating from PHP 2 to PHP 3?

1. Migrating from PHP 2 to PHP 3?

PHP/FI 2.0 is no longer supported. Please see appropriate manual section for information about migration from PHP/FI 2.0.

If you are still working with PHP 2, we strongly recommend you to upgrade straight to PHP 4.

Prev | Home | Next
PHP and other languages | Up | Migrating from PHP 3 to PHP 4


Migrating from PHP 3 to PHP 4

PHP Manual
Prev Next

Chapter 60. Migrating from PHP 3 to PHP 4

PHP has already a long history behind him : Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.

1. Migrating from PHP 3 to PHP 4
2. Do sessions work in PHP 3?
3. Incompatible functions?

1. Migrating from PHP 3 to PHP 4

PHP 4 was designed to be as compatible with earlier versions of PHP as possible and very little functionality was broken in the process. If you're really unsure about compatibility you should install PHP 4 in a test environment and run your scripts there.

Also see the appropriate migration appendix of this manual.

2. Do sessions work in PHP 3?

Although native session support didn't exist in PHP 3, there are third-party applications that did (and still do) offer session functionality. The most common method was by using PHPLIB.

3. Incompatible functions?

Since PHP 4 is basically a rewrite of the entire PHP engine there were very few functions that were altered and only then some of the more exotic ones.

Prev | Home | Next
Migrating from PHP 2 to PHP 3 | Up | Migrating from PHP 4 to PHP 5


Migrating from PHP 4 to PHP 5

PHP Manual
Prev Next

Chapter 61. Migrating from PHP 4 to PHP 5

This faq section will help you migrate from PHP 4 to PHP 5.

1. Migrating from PHP 4 to PHP 5
2. Does MySQL work in PHP 5? It seemed to have disappeared.
3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?
4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?

1. Migrating from PHP 4 to PHP 5

Although PHP 5 offers many new features, it's designed to be as compatible with earlier versions of PHP as possible with little functionality being broken in the process.

Be sure to read the appropriate PHP 5 migration appendix of this manual as it contains even more information on the topic of migrating to PHP 5.

2. Does MySQL work in PHP 5? It seemed to have disappeared.

MySQL is supported with the only change being that MySQL support is no longer enabled by default in PHP 5. This essentially means that PHP doesn't include the --with-mysql option in the configure line so that you must now manually do this when compiling PHP. Windows users will edit php.ini and enable the php_mysql.dll DLL as in PHP 4 no such DLL existed, it was simply built into your Windows PHP binaries.

Also, the MySQL client libraries are no longer bundled with PHP. More details on this topic are covered in the following FAQ and be sure to read the MySQL section for details on installing MySQL. An example configure line would be --with-mysql=/usr while Windows users will need the libmySQL.dll available to the system.

3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?

The main change in PHP 5 is to the OOP model as PHP 5 now uses the Zend Engine 2.0. The zend.ze1_compatibility_mode directive enables compatability with the Zend Engine 1.0 (PHP 4).

The new OOP model is documented in the OOP language reference and OOP migration appendix sections.

4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?

Few other changes exist, see the migration 5 appendix for details. There won't be a PHP 5 specific version of the manual as the bulk of PHP remains the same.

Prev | Home | Next
Migrating from PHP 3 to PHP 4 | Up | Miscellaneous Questions


Miscellaneous Questions

PHP Manual
Prev Next

Chapter 62. Miscellaneous Questions

There can be some questions we can't put into other categories. Here you can find them.

1. How can I handle the bz2 compressed manuals on Windows?
2. What does & beside argument mean in function declaration of e.g. asort()?
3. How do I deal with register_globals?

1. How can I handle the bz2 compressed manuals on Windows?

If you don't have an archiver-tool to handle bz2 files download the commandline tool from Redhat (please find further information below).

If you would not like to use a command line tool, you can try free tools like Stuffit Expander, UltimateZip, 7-Zip, or Quick Zip. If you have tools like WinRAR or Power Archiver, you can easily decompress the bz2 files with it. If you use Total Commander (formerly Windows Commander), a bz2 plugin for that program is available freely from the Total Commander site.

The bzip2 commandline tool from Redhat:

Win2k Sp2 users grab the latest version 1.0.2, all other Windows user should grab version 1.00. After downloading rename the executable to bzip2.exe. For convenience put it into a directory in your path, e.g. C:\Windows where C represents your windows installation drive.

Note: lang stands for your language and x for the desired format, e.g.: pdf. To uncompress the php_manual_lang.x.bz2 follow these simple instructions:

  • open a command prompt window

  • cd to the folder where you stored the downloaded php_manual_lang.x.bz2

  • invoke bzip2 -d php_manual_lang.x.bz2, extracting php_manual_lang.x in the same folder

In case you downloaded the php_manual_lang.tar.bz2 with many html-files in it, the procedure is the same. The only difference is that you got a file php_manual_lang.tar. The tar format is known to be treated with most common archivers on Windows like e.g. WinZip.

2. What does & beside argument mean in function declaration of e.g. asort()?

It means that the argument is passed by reference and the function will likely modify it corresponding to the documentation. You can pass only variables this way and you don't need to pass them with & in function call (it's even deprecated).

3. How do I deal with register_globals?

For information about the security implications of register_globals, read the security chapter on Using register_globals.

It's preferred to use superglobals, rather than relying upon register_globals being on.

If you are on a shared host with register_globals turned off and need to use some legacy applications, which require this option to be turned on, or you are on some hosting server, where this feature is turned on, but you would like to eliminate security risks, you might need to emulate the opposite setting with PHP. It is always a good idea to first ask if it would be possible to change the option somehow in PHP's configuration, but if it is not possible, then you can use these compatibility snippets.

Example 62-1. Emulating Register Globals

This will emulate register_globals On. If you altered your variables_order directive, consider changing the $superglobals accordingly.

&#60;?php
// Emulate register_globals on
if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}
?&#62;

This will emulate register_globals Off. Keep in mind, that this code should be called at the very beginning of your script, or after session_start() if you use it to start your session.

&#60;?php
// Emulate register_globals off
function unregister_GLOBALS()
{
    if (!ini_get('register_globals')) {
        return;
    }

    // Might want to change this perhaps to a nicer error
    if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
        die('GLOBALS overwrite attempt detected');
    }

    // Variables that shouldn't be unset
    $noUnset = array('GLOBALS',  '_GET',
                     '_POST',    '_COOKIE',
                     '_REQUEST', '_SERVER',
                     '_ENV',     '_FILES');

    $input = array_merge($_GET,    $_POST,
                         $_COOKIE, $_SERVER,
                         $_ENV,    $_FILES,
                         isset($_SESSION) &#38;&#38; is_array($_SESSION) ? $_SESSION : array());

    foreach ($input as $k =&#62; $v) {
        if (!in_array($k, $noUnset) &#38;&#38; isset($GLOBALS[$k])) {
            unset($GLOBALS[$k]);
        }
    }
}

unregister_GLOBALS();

?&#62;

Prev | Home | Next
Migrating from PHP 4 to PHP 5 | Up | Appendixes


Appendixes

PHP Manual
Prev Next

IX. Appendixes

Table of Contents
A. History of PHP and related projects
B. Migrating from PHP 4 to PHP 5
C. Migrating from PHP 3 to PHP 4
D. Migrating from PHP/FI 2 to PHP 3
E. Debugging PHP
F. Configure options
G. php.ini directives
H. List of Supported Timezones
I. Extension Categorization
J. List of Function Aliases
K. List of Reserved Words
L. List of Resource Types
M. List of Supported Protocols/Wrappers
N. List of Available Filters
O. List of Supported Socket Transports
P. PHP type comparison tables
Q. List of Parser Tokens
R. Userland Naming Guide
S. About the manual
T. Open Publication License
U. Function Index

Prev | Home | Next
Miscellaneous Questions |  | History of PHP and related projects


History of PHP and related projects

PHP Manual
Prev Next

Appendix A. History of PHP and related projects

Table of Contents
History of PHP
History of PHP related projects
Books about PHP
Publications about PHP

PHP has come a long way in the last few years. Growing to be one of the most prominent languages powering the Web was not an easy task. Those of you interested in briefly seeing how PHP grew out to what it is today, read on. Old PHP releases can be found at the PHP Museum.

History of PHP

PHP/FI

PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code.

PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.

By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.

PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.

PHP 3

PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax.

The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.

By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet.

PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. To get more information on this engine, see its webpage.

Prev | Home | Next
Appendixes | Up | History of PHP related projects


History of PHP related projects

PEAR

PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in the manual.

PHP Quality Assurance Initiative

The PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.

PHP-GTK

PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.

Prev | Home | Next
History of PHP and related projects | Up | Books about PHP


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. Both of these books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 40 books in English, 50 books in German, and over 20 books in French! In addition, you can find books about PHP in many other languages, including Spanish, Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.

Prev | Home | Next
History of PHP related projects | Up | Publications about PHP


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!

Prev | Home | Next
Books about PHP | Up | Migrating from PHP 4 to PHP 5


Migrating from PHP 4 to PHP 5

PHP Manual
Prev Next

Appendix B. Migrating from PHP 4 to PHP 5

Table of Contents
What has changed in PHP 5
Backward Incompatible Changes
CLI and CGI
Migrating Configuration Files
New Functions
New Directives
Databases
New Object Model
Error Reporting

What has changed in PHP 5

PHP 5 and the integrated Zend Engine 2 have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 4 to 5 should be very easy. Most existing PHP 4 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments.

Prev | Home | Next
Publications about PHP | Up | Backward Incompatible Changes


Backward Incompatible Changes

Although most existing PHP 4 code should work without changes, you should pay attention to the following backward incompatible changes:

  • There are some new reserved keywords.

  • strrpos() and strripos() now use the entire string as a needle.

  • Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = 'abc'; unset($str[0]);.

  • array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.

  • PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the CGI specification. Please refer to bug #23610 for further information, and see also the $_SERVER['PATH_TRANSLATED'] description in the manual. This issue also affects PHP versions >= 4.3.2.

  • The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.

  • $_SERVER should be populated with argc and argv if variables_order includes "S". If you have specifically configured your system to not create $_SERVER, then of course it shouldn't be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.

  • An object with no properties is no longer considered "empty".

  • In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used. Otherwise the behaviour is the old.

  • get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower().

    This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they're declared (case-sensitive).

  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.

  • 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 it. It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

  • include_once() and require_once() first normalize the path of included file on Windows so that including A.php and a.php include the file just once.

Example B-1. strrpos() and strripos() now use the entire string as a needle

&#60;?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?&#62;

Example B-2. An object with no properties is no longer considered "empty"

&#60;?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Will be executed
}
?&#62;

Example B-3. In some cases classes must be declared before used

&#60;?php

//works with no errors:
$a = new a();
class a {
}

//throws an error:
$a = new b();

interface c{
}
class b implements c {
}

?&#62;

Prev | Home | Next
Migrating from PHP 4 to PHP 5 | Up | CLI and CGI


CLI and CGI

In PHP 5 there were some changes in CLI and CGI filenames. In PHP 5, the CGI version was renamed to php-cgi.exe (previously php.exe) and the CLI version now sits in the main directory (previously cli/php.exe).

In PHP 5 it was also introduced a new mode: php-win.exe. 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.

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.

See also the commandline reference.

Prev | Home | Next
Backward Incompatible Changes | Up | Migrating Configuration Files


Migrating Configuration Files

Since the ISAPI modules changed their names, from php4xxx to php5xxx, you need to make some changes in the configuration files. There were also changes in the CLI and CGI filenames. Please refer to the corresponding section for more information.

Migrate the Apache configuration is extremely easy. See the example below to check the change you need to do:

Example B-4. Migrating Apache configuration files for PHP 5

# change this line:
LoadModule php4_module /php/sapi/php4apache2.dll

# with this one:
LoadModule php5_module /php/php5apache2.dll

If your webserver is running PHP in CGI mode, you should note that the CGI version has changed its name from php.exe to php-cgi.exe. In Apache, you should do something like this:

Example B-5. Migrating Apache configuration files for PHP 5, CGI mode

# change this line:
Action application/x-httpd-php "/php/php.exe"

# with this one:
Action application/x-httpd-php "/php/php-cgi.exe"

In other webservers you need to change either the CGI or the ISAPI module filenames.

Prev | Home | Next
CLI and CGI | Up | New Functions


New Functions

In PHP 5 there are some new functions. Here is the list of them:

Arrays:

  • array_combine() - Creates an array by using one array for keys and another for its values

  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function

  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison

  • array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function

  • array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also

  • array_walk_recursive() - Apply a user function recursively to every member of an array

  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function

  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using a callback functions

  • array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function

InterBase:

  • 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_commit_ret() - Commit a transaction without closing it

  • ibase_db_info() - Request statistics about a database

  • ibase_drop_db() - Drops a database

  • ibase_errcode() - Return an error code

  • ibase_free_event_handler() - Cancels a registered event handler

  • ibase_gen_id() - Increments the named generator and returns its new value

  • ibase_maintain_db() - Execute a maintenance command on the database server

  • ibase_name_result() - Assigns a name to 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_restore() - Initiates a restore task in the service manager and returns immediately

  • ibase_rollback_ret() - Rollback transaction and retain the transaction context

  • ibase_server_info() - Request statistics about a database

  • 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_wait_event() - Wait for an event to be posted by the database

iconv:

  • iconv_mime_decode() - Decodes a MIME header field

  • iconv_mime_decode_headers() - Decodes multiple MIME header fields at once

  • iconv_mime_encode() - Composes a MIME header field

  • iconv_strlen() - Returns the character count of string

  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack

  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack

  • iconv_substr() - Cut out part of a string

Streams:

  • stream_copy_to_stream() - Copies data from one stream to another

  • stream_get_line() - Gets line from stream resource up to a given delimiter

  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server()

  • stream_socket_client() - Open Internet or Unix domain socket connection

  • stream_socket_get_name() - Retrieve the name of the local or remote sockets

  • stream_socket_recvfrom() - Receives data from a socket, connected or not

  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not

  • stream_socket_server() - Create an Internet or Unix domain server socket

Date and time related:

  • idate() - Format a local time/date as integer

  • date_sunset() - Time of sunset for a given day and location

  • date_sunrise() - Time of sunrise for a given day and location

  • time_nanosleep() - Delay for a number of seconds and nanoseconds

Strings:

  • str_split() - Convert a string to an array

  • strpbrk() - Search a string for any of a set of characters

  • substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters

Other:

  • convert_uudecode() - decode a uuencoded string

  • convert_uuencode() - uuencode a string

  • curl_copy_handle() - Copy a cURL handle along with all of its preferences

  • dba_key_split() - Splits a key in string representation into array representation

  • dbase_get_header_info() - Get the header info of a dBase database

  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

  • fbsql_set_password() - Change the password for a given user

  • file_put_contents() - Write a string to a file

  • ftp_alloc() - Allocates space for a file to be uploaded

  • get_declared_interfaces() - Returns an array of all declared interfaces

  • get_headers() - Fetches all the headers sent by the server in response to a HTTP request

  • headers_list() - Returns a list of response headers sent (or ready to send)

  • http_build_query() - Generate URL-encoded query string

  • image_type_to_extension() - Get file extension for
image-type returned by getimagesize(),
exif_read_data(),
exif_thumbnail(),
exif_imagetype()

  • imagefilter() - Applies a filter to an image using custom arguments

  • imap_getacl() - Gets the ACL for a given mailbox

  • ldap_sasl_bind() - Bind to LDAP directory using SASL

  • mb_list_encodings() - Returns an array of all supported encodings

  • pcntl_getpriority() - Get the priority of any process

  • pcntl_wait() - Waits on or returns the status of a forked child as defined by the waitpid() system call

  • pg_version() - Returns an array with client, protocol and server version (when available)

  • php_check_syntax() - Check the syntax of the specified file

  • php_strip_whitespace() - Return source with stripped comments and whitespace

  • proc_nice() - Change the priority of the current process

  • pspell_config_data_dir() - Change location of language data files

  • pspell_config_dict_dir() - Change location of the main word list

  • setrawcookie() - Send a cookie without URL-encoding the value

  • scandir() - List files and directories inside the specified path

  • snmp_read_mib() - Reads and parses a MIB file into the active MIB tree

  • sqlite_fetch_column_types() - Return an array of column types from a particular table

Note: The Tidy extension has also changed its API completely.

Prev | Home | Next
Migrating Configuration Files | Up | New Directives


New Directives

There were some new php.ini directives introduced in PHP 5. Here is a list of them:

  • mail.force_extra_parameters - Force the addition of the specified parameters to be passed as extra parameters to the sendmail binary. These parameters will always replace the value of the 5th parameter to mail(), even in safe mode

  • register_long_arrays - allow/disallow PHP to register the deprecated long $HTTP_*_VARS

  • session.hash_function - select a hash function (MD5 or SHA-1)

  • session.hash_bits_per_character - define how many bits are stored in each character when converting the binary hash data to something readable (from 4 to 6)

  • zend.ze1_compatibility_mode - Enable compatibility mode with Zend Engine 1 (PHP 4)

Prev | Home | Next
New Functions | Up | Databases


Databases

There were some changes in PHP 5 regarding databases (MySQL and SQLite).

In PHP 5 the MySQL client libraries are not bundled, because of license problems and some others. For more information, read the FAQ entry.

There is also a new extension, MySQLi (Improved MySQL), which is designed to work with MySQL 4.1 and above.

Since PHP 5, the SQLite extension is built-in PHP. SQLite is an embeddable SQL database engine and is not a client library used to connect to a big database server (like MySQL or PostgreSQL). The SQLite library reads and writes directly to and from the database files on disk.

Prev | Home | Next
New Directives | Up | New Object Model


New Object Model

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. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Many PHP programmers aren't even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

The new Object Model is documented at the Language Reference.

See also the zend.ze1_compatibility_mode directive for compatability with PHP 4.

Prev | Home | Next
Databases | Up | Error Reporting


Error Reporting

As of PHP 5 new error reporting constant E_STRICT was introduced with value 2048. It enables run-time PHP suggestions on your code interoperability and forward compatibility, that will help you to keep latest and greatest suggested method of coding. E.g. STRICT message will warn you on using deprecated functions.

Note: E_ALL does not include E_STRICT so it's not enabled by default

Prev | Home | Next
New Object Model | Up | Migrating from PHP 3 to PHP 4


Migrating from PHP 3 to PHP 4

PHP Manual
Prev Next

Appendix C. Migrating from PHP 3 to PHP 4

Table of Contents
What has changed in PHP 4
Running PHP 3 and PHP 4 concurrently
Migrating Configuration Files
Parser behavior
Error reporting
Initializers
empty("0")
Missing functions
PHP 3 extension
Variable substitution in strings
Cookies
Handling of global variables

What has changed in PHP 4

PHP 4 and the integrated Zend engine have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.

Prev | Home | Next
Error Reporting | Up | Running PHP 3 and PHP 4 concurrently


Running PHP 3 and PHP 4 concurrently

Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.

This feature is known to work on the following platforms:

  • Linux with recent binutils (binutils 2.9.1.0.25 tested)

  • Solaris 2.5 or better

  • FreeBSD (3.2, 4.0 tested)

To enable it, configure PHP 3 and PHP 4 to use APXS (--with-apxs) and the necessary link extensions (--enable-versioning). Otherwise, all standard installations instructions apply. For example:

$ ./configure \
  --with-apxs=/apache/bin/apxs \
  --enable-versioning \
  --with-mysql \
  --enable-track-vars

Prev | Home | Next
Migrating from PHP 3 to PHP 4 | Up | Migrating Configuration Files


Migrating Configuration Files

The global configuration file, php3.ini, has changed its name to php.ini.

For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.

application/x-httpd-php3        -->    application/x-httpd-php
application/x-httpd-php3-source -->    application/x-httpd-php-source

You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:

AddType  application/x-httpd-php3        .php3
AddType  application/x-httpd-php3-source .php3s

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

In addition, the PHP directive names for Apache have changed.

Starting with PHP 4.0, there are only four Apache directives that relate to PHP:

php_value [PHP directive name] [value]
php_flag [PHP directive name] [On|Off]
php_admin_value [PHP directive name] [value]
php_admin_flag [PHP directive name] [On|Off]

There are two differences between the Admin values and the non admin values:

  • Admin values (or flags) can only appear in the server-wide Apache configuration files (e.g., httpd.conf).

  • Standard values (or flags) cannot control certain PHP directives, for example: safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe mode's purpose). In contrast, Admin values can modify the value of any PHP directive.

To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.

To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:

~/php4/scripts/apache:#  ./apconf-conv.sh /usr/local/apache/conf/httpd.conf

Your original configuration file will be saved in httpd.conf.orig.

To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):

~/php4/scripts/apache:#  find / -name .htaccess -exec ./aphtaccess-conv.sh {} \;

Likewise, your old .htaccess files will be saved with an .orig prefix.

The conversion scripts require awk to be installed.

Prev | Home | Next
Running PHP 3 and PHP 4 concurrently | Up | Parser behavior


Parser behavior

Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.

One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.

It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).

This should not harm too much as spreading code like this should be considered as very bad style anyway.

Another thing no longer possible, though rarely seen in PHP 3 code is returning values from a required file. Returning a value from an included file is still possible.

Prev | Home | Next
Migrating Configuration Files | Up | Error reporting


Error reporting

Configuration changes

With PHP 3 the error reporting level was set as a simple numeric value formed by summing up the numbers related to different error levels. Usual values were 15 for reporting all errors and warnings or 7 for reporting everything but simple notice messages reporting bad style and things like that.

PHP 4 has a larger set of error and warning levels and comes with a configuration parser that now allows for symbolic constants to be used for setting the intended behavior.

Error reporting level should now be configured by explicitly taking away the warning levels you do not want to generate error messages by x-oring them from the symbolic constant E_ALL. Sounds complicated? Well, lets say you want the error reporting system to report all but the simple style warnings that are categorized by the symbolic constant E_NOTICE. Then you'll put the following into your php.ini: error_reporting = E_ALL & ~ ( E_NOTICE ). If you want to suppress warnings too you add up the appropriate constant within the braces using the binary or operator '|': error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING ).

Warning

When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem.

Warning

Using the old values 7 and 15 for setting up error reporting is a very bad idea as this suppresses some of the newly added error classes including parse errors. This may lead to very strange behavior as scripts might no longer work without error messages showing up anywhere.

This has lead to a lot of unreproducible bug reports in the past where people reported script engine problems they were not capable to track down while the TRUE case was usually some missing '}' in a required file that the parser was not able to report due to a misconfigured error reporting system.

So checking your error reporting setup should be the first thing to do whenever your scripts silently die. The Zend engine can be considered mature enough nowadays to not cause this kind of strange behavior.

Additional warning messages

A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.

The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $_SERVER[REQUEST_METHOD]. Changing it to $_SERVER['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.

Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.

Prev | Home | Next
Parser behavior | Up | Initializers


Initializers

Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.

For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.

Prev | Home | Next
Error reporting | Up | empty("0")


empty("0")

The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.

This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other hand it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.

Prev | Home | Next
Initializers | Up | Missing functions


Missing functions

While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.

Functions missing due to conceptual changes

As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.

Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.

Deprecate functions and extensions

The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.

Changed status for unset()

unset(), although still available, is implemented as a language construct rather than a function.

This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().

Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.

Prev | Home | Next
empty("0") | Up | PHP 3 extension


PHP 3 extension

Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.

Prev | Home | Next
Missing functions | Up | Variable substitution in strings


Variable substitution in strings

PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.

To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}

To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".

This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.

Prev | Home | Next
PHP 3 extension | Up | Cookies


Cookies

PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.

This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.

Prev | Home | Next
Variable substitution in strings | Up | Handling of global variables


Handling of global variables

While handling of global variables had the focus on to be easy in PHP 3 and early versions of PHP 4, the focus has changed to be more secure. While in PHP 3 the following example worked fine, in PHP 4 it has to be unset(unset($GLOBALS["id"]));. This is only one issue of global variable handling. You should always have used $GLOBALS, with newer versions of PHP 4 you are forced to do so in most cases. Read more on this subject in the global references section.

Example C-1. Migration of global variables

&#60;?php
$id = 1;
function test()
{
    global $id;
    unset($id);
}
test();
echo($id); // This will print out 1 in PHP 4
?&#62;

Prev | Home | Next
Cookies | Up | Migrating from PHP/FI 2 to PHP 3


Migrating from PHP/FI 2 to PHP 3

PHP Manual
Prev Next

Appendix D. Migrating from PHP/FI 2 to PHP 3

Table of Contents
About the incompatibilities in 3.0
old_function
Start/end tags
if..endif syntax
while syntax
Expression types
Error messages have changed
Short-circuited boolean evaluation
Function TRUE/FALSE return values
Other incompatibilities

About the incompatibilities in 3.0

PHP 3.0 is rewritten from the ground up. It has a proper parser that is much more robust and consistent than 2.0's. 3.0 is also significantly faster, and uses less memory. However, some of these improvements have not been possible without compatibility changes, both in syntax and functionality.

In addition, PHP's developers have tried to clean up both PHP's syntax and semantics in version 3.0, and this has also caused some incompatibilities. In the long run, we believe that these changes are for the better.

This chapter will try to guide you through the incompatibilities you might run into when going from PHP/FI 2.0 to PHP 3.0 and help you resolve them. New features are not mentioned here unless necessary.

A conversion program that can automatically convert your old PHP/FI 2.0 scripts exists. It can be found in the convertor subdirectory of the PHP 3.0 distribution. This program only catches the syntax changes though, so you should read this chapter carefully anyway.

Prev | Home | Next
Handling of global variables | Up | old_function


old_function

The old_function statement allows you to declare a function using a syntax identical to PHP/FI2 (except you must replace 'function' with 'old_function'.

This is a deprecated feature, and should only be used by the PHP/FI2->PHP 3 convertor.

Warning

Functions declared as old_function cannot be called from PHP's internal code. Among other things, this means you can't use them in functions such as usort(), array_walk(), and register_shutdown_function(). You can get around this limitation by writing a wrapper function (in normal PHP 3 form) to call the old_function.

Prev | Home | Next
Migrating from PHP/FI 2 to PHP 3 | Up | Start/end tags


Start/end tags

The first thing you probably will notice is that PHP's start and end tags have changed. The old <? > form has been replaced by three new possible forms:

Example D-1. Migration: old start/end tags

&#60;? echo "This is PHP/FI 2.0 code.\n"; &#62;
As of version 2.0, PHP/FI also supports this variation:

Example D-2. Migration: first new start/end tags

&#60;? echo "This is PHP 3.0 code!\n"; ?&#62;
Notice that the end tag now consists of a question mark and a greater-than character instead of just greater-than. However, if you plan on using XML on your server, you will get problems with the first new variant, because PHP may try to execute the XML markup in XML documents as PHP code. Because of this, the following variation was introduced:

Example D-3. Migration: second new start/end tags

&#60;?php echo "This is PHP 3.0 code!\n"; ?&#62;
Some people have had problems with editors that don't understand the processing instruction tags at all. Microsoft FrontPage is one such editor, and as a workaround for these, the following variation was introduced as well:

Example D-4. Migration: third new start/end tags

&#60;script language="php"&#62;

  echo "This is PHP 3.0 code!\n";

&#60;/script&#62;

Prev | Home | Next
old_function | Up | if..endif syntax


if..endif syntax

The `alternative' way to write if/elseif/else statements, using if(); elseif(); else; endif; cannot be efficiently implemented without adding a large amount of complexity to the 3.0 parser. Because of this, the syntax has been changed:

Example D-5. Migration: old if..endif syntax

if ($foo);
    echo "yep\n";
elseif ($bar);
    echo "almost\n";
else;
    echo "nope\n";
endif;

Example D-6. Migration: new if..endif syntax

if ($foo):
    echo "yep\n";
elseif ($bar):
    echo "almost\n";
else:
    echo "nope\n";
endif;
Notice that the semicolons have been replaced by colons in all statements but the one terminating the expression (endif).

Prev | Home | Next
Start/end tags | Up | while syntax


while syntax

Just like with if..endif, the syntax of while..endwhile has changed as well:

Example D-7. Migration: old while..endwhile syntax

while ($more_to_come);
    ...
endwhile;

Example D-8. Migration: new while..endwhile syntax

while ($more_to_come):
    ...
endwhile;

Warning

If you use the old while..endwhile syntax in PHP 3.0, you will get a never-ending loop.

Prev | Home | Next
if..endif syntax | Up | Expression types


Expression types

PHP/FI 2.0 used the left side of expressions to determine what type the result should be. PHP 3.0 takes both sides into account when determining result types, and this may cause 2.0 scripts to behave unexpectedly in 3.0.

Consider this example:

$a[0]=5;
$a[1]=7;

$key = key($a);
while ("" != $key) {
    echo "$keyn";
    next($a);
}

In PHP/FI 2.0, this would display both of $a's indices. In PHP 3.0, it wouldn't display anything. The reason is that in PHP 2.0, because the left argument's type was string, a string comparison was made, and indeed "" does not equal "0", and the loop went through. In PHP 3.0, when a string is compared with an integer, an integer comparison is made (the string is converted to an integer). This results in comparing atoi("") which is 0, and variablelist which is also 0, and since 0==0, the loop doesn't go through even once.

The fix for this is simple. Replace the while statement with:

while ((string)$key != "") {

Prev | Home | Next
while syntax | Up | Error messages have changed


Error messages have changed

PHP 3.0's error messages are usually more accurate than 2.0's were, but you no longer get to see the code fragment causing the error. You will be supplied with a file name and a line number for the error, though.

Prev | Home | Next
Expression types | Up | Short-circuited boolean evaluation


Short-circuited boolean evaluation

In PHP 3.0 boolean evaluation is short-circuited. This means that in an expression like (1 || test_me()), the function test_me() would not be executed since nothing can change the result of the expression after the 1.

This is a minor compatibility issue, but may cause unexpected side-effects.

Prev | Home | Next
Error messages have changed | Up | Function TRUE/FALSE return values


Function TRUE/FALSE return values

Most internal functions have been rewritten so they return TRUE when successful and FALSE when failing, as opposed to 0 and -1 in PHP/FI 2.0, respectively. The new behaviour allows for more logical code, like $fp = fopen("/your/file") or fail("darn!");. Because PHP/FI 2.0 had no clear rules for what functions should return when they failed, most such scripts will probably have to be checked manually after using the 2.0 to 3.0 convertor.

Example D-9. Migration from 2.0: return values, old code

$fp = fopen($file, "r");
if ($fp == -1);
    echo("Could not open $file for reading&#60;br /&#62;\n");
endif;

Example D-10. Migration from 2.0: return values, new code

$fp = @fopen($file, "r") or print("Could not open $file for reading&#60;br /&#62;\n");

Prev | Home | Next
Short-circuited boolean evaluation | Up | Other incompatibilities


Other incompatibilities

  • The PHP 3.0 Apache module no longer supports Apache versions prior to 1.2. Apache 1.2 or later is required.

  • echo() no longer supports a format string. Use the printf() function instead.

  • In PHP/FI 2.0, an implementation side-effect caused $foo[0] to have the same effect as $foo. This is not true for PHP 3.0.

  • Reading arrays with $array[] is no longer supported

    That is, you cannot traverse an array by having a loop that does $data = $array[]. Use current() and next() instead.

    Also, $array1[] = $array2 does not append the values of $array2 to $array1, but appends $array2 as the last entry of $array1. See also multidimensional array support.

  • "+" is no longer overloaded as a concatenation operator for strings, instead it converts it's arguments to numbers and performs numeric addition. Use "." instead.

Example D-11. Migration from 2.0: concatenation for strings

echo "1" + "1";

In PHP 2.0 this would echo 11, in PHP 3.0 it would echo 2. Instead use:

echo "1"."1";
$a = 1;
$b = 1;
echo $a + $b;

This would echo 2 in both PHP 2.0 and 3.0.

$a = 1;
$b = 1;
echo $a.$b;
This will echo 11 in PHP 3.0.

Prev | Home | Next
Function TRUE/FALSE return values | Up | Debugging PHP


Debugging PHP

PHP Manual
Prev Next

Appendix E. Debugging PHP

Table of Contents
About the debugger
Using the Debugger
Debugger Protocol

About the debugger

PHP 3 includes support for a network-based debugger.

PHP 4 does not have an internal debugging facility. You can use one of the external debuggers though. The Zend IDE includes a debugger, and there are also some free debugger extensions like DBG at http://dd.cron.ru/dbg/, the Advanced PHP Debugger (APD) or Xdebug which even has a compatible debugger interface as PHP 3's debugging functionality as is described in this section.

Prev | Home | Next
Other incompatibilities | Up | Using the Debugger


Using the Debugger

The internal debugger in PHP 3 is useful for tracking down evasive bugs. The debugger works by connecting to a TCP port for every time PHP 3 starts up. All error messages from that request will be sent to this TCP connection. This information is intended for "debugging server" that can run inside an IDE or programmable editor (such as Emacs).

How to set up the debugger:

  1. Set up a TCP port for the debugger in the configuration file (debugger.port) and enable it (debugger.enabled).

  2. Set up a TCP listener on that port somewhere (for example socket -l -s 1400 on Unix systems).

  3. In your code, run "debugger_on(host)", where host is the IP number or name of the host running the TCP listener.

Now, all warnings, notices etc. will show up on that listener socket, even if you turned them off with error_reporting().

Prev | Home | Next
Debugging PHP | Up | Debugger Protocol


Debugger Protocol

The PHP 3 debugger protocol is line-based. Each line has a type, and several lines compose a message. Each message starts with a line of the type start and terminates with a line of the type end. PHP 3 may send lines for different messages simultaneously.

A line has this format:

date time host(pid) type: message-data

date

Date in ISO 8601 format (yyyy-mm-dd)

time

Time including microseconds: hh:mm:uuuuuu

host

DNS name or IP address of the host where the script error was generated.

pid

PID (process id) on host of the process with the PHP 3 script that generated this error.

type

Type of line. Tells the receiving program about what it should treat the following data as:

Table E-1. Debugger Line Types

Name | Meaning
start | Tells the receiving program that a debugger message starts here. The contents of data will be the type of error message, listed below.
message | The PHP 3 error message.
location | File name and line number where the error occurred. The first location line will always contain the top-level location. data will contain file:line. There will always be a location line after message and after every function.
frames | Number of frames in the following stack dump. If there are four frames, expect information about four levels of called functions. If no "frames" line is given, the depth should be assumed to be 0 (the error occurred at top-level).
function | Name of function where the error occurred. Will be repeated once for every level in the function call stack.
end | Tells the receiving program that a debugger message ends here.

data

Line data.

Table E-2. Debugger Error Types

Debugger | PHP 3 Internal
warning | E_WARNING
error | E_ERROR
parse | E_PARSE
notice | E_NOTICE
core-error | E_CORE_ERROR
core-warning | E_CORE_WARNING
unknown | (any other)

Example E-1. Example Debugger Message

1998-04-05 23:27:400966 lucifer.guardian.no(20481) start: notice
1998-04-05 23:27:400966 lucifer.guardian.no(20481) message: Uninitialized variable
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: (null):7
1998-04-05 23:27:400966 lucifer.guardian.no(20481) frames: 1
1998-04-05 23:27:400966 lucifer.guardian.no(20481) function: display
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: /home/ssb/public_html/test.php3:10
1998-04-05 23:27:400966 lucifer.guardian.no(20481) end: notice

Prev | Home | Next
Using the Debugger | Up | Configure options


Extending PHP 3

PHP Manual
Prev Next

Chapter 48. Extending PHP 3

Table of Contents
Adding functions to PHP
Calling User Functions
Reporting Errors

This section is rather outdated and demonstrates how to extend PHP 3. If you're interested in PHP 4, please read the section on the Zend API.

Adding functions to PHP

Function Prototype

All functions look like this:

void php3_foo(INTERNAL_FUNCTION_PARAMETERS) {

}
Even if your function doesn't take any arguments, this is how it is called.

Function Arguments

Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:

Example 48-1. Fetching function arguments

pval *arg1, *arg2;
if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) {
   WRONG_PARAM_COUNT;
}
NOTE: Arguments can be passed either by value or by reference. In both cases you will need to pass &(pval *) to getParameters. If you want to check if the n'th parameter was sent to you by reference or not, you can use the function, ParameterPassedByReference(ht,n). It will return either 1 or 0.

When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.

Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.

Variable Function Arguments

A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:

Example 48-2. Variable function arguments

pval *arg1, *arg2, *arg3;
int arg_count = ARG_COUNT(ht);

if (arg_count < 2 || arg_count > 3 ||
    getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) {
    WRONG_PARAM_COUNT;
}

Using the Function Arguments

The type of each argument is stored in the pval type field. This type can be any of the following:

Table 48-1. PHP Internal Types

IS_STRING | String
IS_DOUBLE | Double-precision floating point
IS_LONG | Long integer
IS_ARRAY | Array
IS_EMPTY | None
IS_USER_FUNCTION | ??
IS_INTERNAL_FUNCTION | ?? (if some of these cannot be passed to a function - delete)
IS_CLASS | ??
IS_OBJECT | ??

If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:

convert_to_long(arg1);
convert_to_double(arg1);
convert_to_string(arg1);
convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */
convert_string_to_number(arg1);  /* Converts string to either LONG or DOUBLE depending on string */

These function all do in-place conversion. They do not return anything.

The actual argument is stored in a union; the members are:

  • IS_STRING: arg1->value.str.val

  • IS_LONG: arg1->value.lval

  • IS_DOUBLE: arg1->value.dval

Memory Management in Functions

Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().

There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).

For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.

If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.

Setting Variables in the Symbol Table

A number of macros are available which make it easier to set a variable in the symbol table:

  • SET_VAR_STRING(name,value)

  • SET_VAR_DOUBLE(name,value)

  • SET_VAR_LONG(name,value)

Warning

Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING.

Symbol tables in PHP are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).

The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.

Example 48-3. Checking whether $foo exists in a symbol table

if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... }
else { doesn't exist }

Example 48-4. Finding a variable's size in a symbol table

hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue);
check(pvalue.type);
Arrays in PHP are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.

If you want to define a new array in a symbol table, you should do the following.

First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().

Next, initialize the array:

Example 48-5. Initializing a new array

pval arr;

if (array_init(&arr) == FAILURE) { failed... };
hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL);
This code declares a new array, named $foo, in the active symbol table. This array is empty.

Here's how to add new entries to it:

Example 48-6. Adding entries to a new array

pval entry;

entry.type = IS_LONG;
entry.value.lval = 5;

/* defines $foo["bar"] = 5 */
hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL);

/* defines $foo[7] = 5 */
hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL);

/* defines the next free place in $foo[],
 * $foo[8], to be 5 (works like php2)
 */
hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL);
If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is NULL (like in all of the above examples) - that parameter is ignored.

hash_next_index_insert() uses more or less the same logic as $foo[] = bar; in PHP 2.0.

If you are building an array to return from a function, you can initialize the array just like above by doing:

if (array_init(return_value) == FAILURE) { failed...; }

...and then adding values with the helper functions:

add_next_index_long(return_value,long_value);
add_next_index_double(return_value,double_value);
add_next_index_string(return_value,estrdup(string_value));

Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:

pval *arr;

if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... }
else { use arr->value.ht... }

Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.

Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).

Returning simple values

A number of macros are available to make returning values from a function easier.

The RETURN_* macros all set the return value and return from the function:

  • RETURN

  • RETURN_FALSE

  • RETURN_TRUE

  • RETURN_LONG(l)

  • RETURN_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETURN_DOUBLE(d)

The RETVAL_* macros set the return value, but do not return.

  • RETVAL_FALSE

  • RETVAL_TRUE

  • RETVAL_LONG(l)

  • RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETVAL_DOUBLE(d)

The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.

If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.

Returning complex values

Your function can also return a complex data type such as an object or an array.

Returning an object:

  1. Call object_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

  3. Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:

    add_method( return_value, function_name, function_ptr );

The functions used to populate an object are:

  • add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'

  • add_property_double( return_value, property_name, d ) - Same, only adds a double

  • add_property_string( return_value, property_name, str ) - Same, only adds a string

  • add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'

Returning an array:

  1. Call array_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

The functions used to populate an array are:

  • add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'

  • add_assoc_double(return_value,key,d)

  • add_assoc_string(return_value,key,str,duplicate)

  • add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length

  • add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'

  • add_index_double(return_value,index,d)

  • add_index_string(return_value,index,str)

  • add_index_stringl(return_value,index,str,length) - specify the string length

  • add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'

  • add_next_index_double(return_value,d)

  • add_next_index_string(return_value,str)

  • add_next_index_stringl(return_value,str,length) - specify the string length

Using the resource list

PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.

Available functions:

  • php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_list_delete(id) - delete the resource with the specified id

  • php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.

Typical list code would look like this:

Example 48-7. Adding a new resource

RESOURCE *resource;

/* ...allocate memory for resource and acquire resource... */
/* add a new resource to the list */
return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE);
return_value->type = IS_LONG;

Example 48-8. Using an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
resource = php3_list_find(resource_id->value.lval, &type);
if (type != LE_RESOURCE_TYPE) {
    php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval);
    RETURN_FALSE;
}
/* ...use resource... */

Example 48-9. Deleting an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
php3_list_delete(resource_id->value.lval);
The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).

Using the persistent resource table

PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:

php3_mysql_do_connect
php3_mysql_connect()
php3_mysql_pconnect()

The general idea of persistence modules is this:

  1. Code all of your module to work with the regular resource list mentioned in section (9).

  2. Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).

If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.

The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':

  • php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_plist_delete(id) - delete the resource with the specified id

  • php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.

Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.

One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.

When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.

Adding runtime configuration directives

Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.

The steps required to add a new directive:

  1. Add directive to php3_ini_structure struct in mod_php3.h.

  2. In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.

  3. Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.

  4. In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.

  5. In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.

  6. And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.

Prev | Home | Next
VCWD_UTIME | Up | Calling User Functions


Calling User Functions

To call user functions from an internal function, you should use the call_user_function() function.

call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.

All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.

call_user_function() takes six arguments:

HashTable *function_table

This is the hash table in which the function is to be looked up.

pval *object

This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.

pval *function_name

The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.

pval *retval

A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.

int param_count

The number of parameters being passed to the function.

pval *params[]

An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.

Prev | Home | Next
Extending PHP 3 | Up | Reporting Errors


Reporting Errors

To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:

E_NOTICE

Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.

E_WARNING

Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.

E_ERROR

Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.

E_PARSE

Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.

E_CORE_ERROR

This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.

E_CORE_WARNING

This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.

E_COMPILE_ERROR

This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.

E_COMPILE_WARNING

This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.

E_USER_ERROR

This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.

E_USER_WARNING

This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.

E_USER_NOTICE

This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.

E_ALL

All of the above. Using this error_reporting level will show all error types.

Prev | Home | Next
Calling User Functions | Up | FAQ: Frequently Asked Questions


Configure options

PHP Manual
Prev Next

Appendix F. Configure options

Table of Contents
List of core configure options

List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

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

  • Miscellaneous

  • PHP Behaviour

  • Server

Configure Options in PHP 4

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

Misc options

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

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

--with-pear=DIR

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

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

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

--with-zlib-dir[=DIR]

Define the location of zlib install directory.

--enable-trans-sid

Enable transparent session id propagation. Only valid for PHP 4.1.2 or less. From PHP 4.2.0, trans-sid feature is always compiled.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

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

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

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

--enable-memory-limit

Compile with memory limit support.

--disable-url-fopen-wrapper

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

--enable-versioning

Export only required symbols. See INSTALL for more information.

--with-imsp[=DIR]

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

--with-mck[=DIR]

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

--with-mod-dav=DIR

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

--enable-debugger

Compile with remote debugging functions. PHP 3 only!

--enable-versioning

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

PHP options

--enable-maintainer-mode

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

--with-config-file-path=PATH

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

--enable-safe-mode

Enable safe mode by default.

--with-exec-dir[=DIR]

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

--enable-magic-quotes

Enable magic quotes by default.

--disable-short-tags

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

SAPI options

The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

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

--with-apache[=DIR]

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

--with-mod_charset

Enable transfer tables for mod_charset (Russian Apache).

--with-apxs2[=FILE]

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

--with-caudium=DIR

Build PHP as a Pike module for use with Caudium. DIR is the Caudium server dir, with the default value /usr/local/caudium/server.

--disable-cli

Available with PHP 4.3.0. Disable building the CLI version of PHP (this forces --without-pear). More information is available in the section about Using PHP from the command line.

--enable-embed[=TYPE]

Enable building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared. Available with PHP 4.3.0.

--with-fhttpd[=DIR]

Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd. No longer available as of PHP 4.3.0.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape/iPlanet/SunONE Webserver.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

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

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

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

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).

--with-webjames=SRCDIR

Build PHP as a WebJames module (RISC OS only)

--disable-cgi

Disable building CGI version of PHP. Available with PHP 4.3.0.

--enable-force-cgi-redirect

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

--enable-discard-path

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

--with-fastcgi

Build PHP as FastCGI application. No longer available as of PHP 4.3.0, instead you should use --enable-fastcgi.

--enable-fastcgi

If this is enabled, the CGI module will be built with support for FastCGI also. Available since PHP 4.3.0

--disable-path-info-check

If this is disabled, paths such as /info.php/test?a=b will fail to work. Available since PHP 4.3.0. For more information see the Apache Manual.

Prev | Home | Next
Debugger Protocol | Up | php.ini directives


List of Function Aliases

PHP Manual
Prev Next

Appendix J. List of Function Aliases

There are quite a few functions in PHP which you can call with more than one name. In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. However there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.

This list is consistent with PHP 4.0.6. For an alias list that updates daily, have a look at http://www.zend.com/phpfunc/all_aliases.php.

Table J-1. Aliases

Alias | Master function | Extension used
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
add_root | domxml_add_root() | DOM XML
addaction | swfbutton_addAction() | Ming (flash)
addcolor | swfdisplayitem_addColor() | Ming (flash)
addentry | swfgradient_addEntry() | Ming (flash)
addfill | swfshape_addfill() | Ming (flash)
addshape | swfbutton_addShape() | Ming (flash)
addstring | swftext_addString() | Ming (flash)
addstring | swftextfield_addString() | Ming (flash)
align | swftextfield_align() | Ming (flash)
attributes | domxml_attributes() | DOM XML
children | domxml_children() | DOM XML
chop | rtrim() | Base syntax
close | closedir() | Base syntax
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
cv_add | ccvs_add() | CCVS
cv_auth | ccvs_auth() | CCVS
cv_command | ccvs_command() | CCVS
cv_count | ccvs_count() | CCVS
cv_delete | ccvs_delete() | CCVS
cv_done | ccvs_done() | CCVS
cv_init | ccvs_init() | CCVS
cv_lookup | ccvs_lookup() | CCVS
cv_new | ccvs_new() | CCVS
cv_report | ccvs_report() | CCVS
cv_return | ccvs_return() | CCVS
cv_reverse | ccvs_reverse() | CCVS
cv_sale | ccvs_sale() | CCVS
cv_status | ccvs_status() | CCVS
cv_textvalue | ccvs_textvalue() | CCVS
cv_void | ccvs_void() | CCVS
die | exit() | Miscellaneous functions
dir | getdir() | Base syntax
diskfreespace | disk_free_space() | Filesystem
domxml_getattr | domxml_get_attribute() | DOM XML
domxml_setattr | domxml_set_attribute() | DOM XML
doubleval | floatval() | Base syntax
drawarc | swfshape_drawarc() | Ming (flash)
drawcircle | swfshape_drawcircle() | Ming (flash)
drawcubic | swfshape_drawcubic() | Ming (flash)
drawcubicto | swfshape_drawcubicto() | Ming (flash)
drawcurve | swfshape_drawcurve() | Ming (flash)
drawcurveto | swfshape_drawcurveto() | Ming (flash)
drawglyph | swfshape_drawglyph() | Ming (flash)
drawline | swfshape_drawline() | Ming (flash)
drawlineto | swfshape_drawlineto() | Ming (flash)
dtd | domxml_intdtd() | DOM XML
dumpmem | domxml_dumpmem() | DOM XML
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Base syntax
get_attribute | domxml_get_attribute() | DOM XML
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
getattr | domxml_get_attribute() | DOM XML
getdescent | swffont_getDescent() | Ming (flash)
getdescent | swftext_getDescent() | Ming (flash)
getheight | swfbitmap_getHeight() | Ming (flash)
getleading | swffont_getLeading() | Ming (flash)
getleading | swftext_getLeading() | Ming (flash)
getshape1 | swfmorph_getShape1() | Ming (flash)
getshape2 | swfmorph_getShape2() | Ming (flash)
getwidth | swfbitmap_getWidth() | Ming (flash)
getwidth | swffont_getWidth() | Ming (flash)
getwidth | swftext_getWidth() | Ming (flash)
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Multi-bytes Strings
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings
i18n_http_input | mb_http_input() | Multi-bytes Strings
i18n_http_output | mb_http_output() | Multi-bytes Strings
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Base syntax
is_double | is_float() | Base syntax
is_integer | is_int() | Base syntax
is_long | is_int() | Base syntax
is_real | is_float() | Base syntax
is_writeable | is_writable() | Base syntax
join | implode() | Base syntax
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
last_child | domxml_last_child() | DOM XML
lastchild | domxml_last_child() | DOM XML
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax
mbstrcut | mb_strcut() | Multi-bytes Strings
mbstrlen | mb_strlen() | Multi-bytes Strings
mbstrpos | mb_strpos() | Multi-bytes Strings
mbstrrpos | mb_strrpos() | Multi-bytes Strings
mbsubstr | mb_substr() | Multi-bytes Strings
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash)
ming_setscale | ming_setScale() | Ming (flash)
move | swfdisplayitem_move() | Ming (flash)
movepen | swfshape_movepen() | Ming (flash)
movepento | swfshape_movepento() | Ming (flash)
moveto | swfdisplayitem_moveTo() | Ming (flash)
moveto | swffill_moveTo() | Ming (flash)
moveto | swftext_moveTo() | Ming (flash)
msql | msql_db_query() | mSQL
msql_createdb | msql_create_db() | mSQL
msql_dbname | msql_result() | mSQL
msql_dropdb | msql_drop_db() | mSQL
msql_fieldflags | msql_field_flags() | mSQL
msql_fieldlen | msql_field_len() | mSQL
msql_fieldname | msql_field_name() | mSQL
msql_fieldtable | msql_field_table() | mSQL
msql_fieldtype | msql_field_type() | mSQL
msql_freeresult | msql_free_result() | mSQL
msql_listdbs | msql_list_dbs() | mSQL
msql_listfields | msql_list_fields() | mSQL
msql_listtables | msql_list_tables() | mSQL
msql_numfields | msql_num_fields() | mSQL
msql_numrows | msql_num_rows() | mSQL
msql_regcase | sql_regcase() | mSQL
msql_selectdb | msql_select_db() | mSQL
msql_tablename | msql_result() | mSQL
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_close | sybase_close() | Sybase
mssql_close | sybase_close() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_min_client_severity | sybase_min_client_severity() | Sybase
mssql_min_error_severity | sybase_min_error_severity() | Sybase
mssql_min_message_severity | sybase_min_message_severity() | Sybase
mssql_min_server_severity | sybase_min_server_severity() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_query | sybase_query() | Sybase
mssql_query | sybase_query() | Sybase
mssql_result | sybase_result() | Sybase
mssql_result | sybase_result() | Sybase
mssql_select_db | sybase_select_db() | Sybase
mssql_select_db | sybase_select_db() | Sybase
multcolor | swfdisplayitem_multColor() | Ming (flash)
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
name | domxml_attrname() | DOM XML
new_child | domxml_new_child() | DOM XML
new_xmldoc | domxml_new_xmldoc() | DOM XML
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
node | domxml_node() | DOM XML
oci8append | ocicollappend() | OCI8
oci8assign | ocicollassign() | OCI8
oci8assignelem | ocicollassignelem() | OCI8
oci8close | ocicloselob() | OCI8
oci8free | ocifreecoll() | OCI8
oci8free | ocifreedesc() | OCI8
oci8getelem | ocicollgetelem() | OCI8
oci8load | ociloadlob() | OCI8
oci8max | ocicollmax() | OCI8
oci8ocifreecursor | ocifreestatement() | OCI8
oci8save | ocisavelob() | OCI8
oci8savefile | ocisavelobfile() | OCI8
oci8size | ocicollsize() | OCI8
oci8trim | ocicolltrim() | OCI8
oci8writetemporary | ociwritetemporarylob() | OCI8
oci8writetofile | ociwritelobtofile() | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
output | swfmovie_output() | Ming (flash)
parent | domxml_parent() | DOM XML
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Base syntax
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
rewind | rewinddir() | Base syntax
root | domxml_root() | DOM XML
rotate | swfdisplayitem_rotate() | Ming (flash)
rotateto | swfdisplayitem_rotateTo() | Ming (flash)
rotateto | swffill_rotateTo() | Ming (flash)
save | swfmovie_save() | Ming (flash)
savetofile | swfmovie_saveToFile() | Ming (flash)
scale | swfdisplayitem_scale() | Ming (flash)
scaleto | swfdisplayitem_scaleTo() | Ming (flash)
scaleto | swffill_scaleTo() | Ming (flash)
set_attribute | domxml_set_attribute() | DOM XML
set_content | domxml_set_content() | DOM XML
setaction | swfbutton_setAction() | Ming (flash)
setattr | domxml_set_attribute() | DOM XML
setbackground | swfmovie_setBackground() | Ming (flash)
setbounds | swftextfield_setBounds() | Ming (flash)
setcolor | swftext_setColor() | Ming (flash)
setcolor | swftextfield_setColor() | Ming (flash)
setdepth | swfdisplayitem_setDepth() | Ming (flash)
setdimension | swfmovie_setDimension() | Ming (flash)
setdown | swfbutton_setDown() | Ming (flash)
setfont | swftext_setFont() | Ming (flash)
setfont | swftextfield_setFont() | Ming (flash)
setframes | swfmovie_setFrames() | Ming (flash)
setframes | swfsprite_setFrames() | Ming (flash)
setheight | swftext_setHeight() | Ming (flash)
setheight | swftextfield_setHeight() | Ming (flash)
sethit | swfbutton_setHit() | Ming (flash)
setindentation | swftextfield_setIndentation() | Ming (flash)
setleftfill | swfshape_setleftfill() | Ming (flash)
setleftmargin | swftextfield_setLeftMargin() | Ming (flash)
setline | swfshape_setline() | Ming (flash)
setlinespacing | swftextfield_setLineSpacing() | Ming (flash)
setmargins | swftextfield_setMargins() | Ming (flash)
setmatrix | swfdisplayitem_setMatrix() | Ming (flash)
setname | swfdisplayitem_setName() | Ming (flash)
setname | swftextfield_setName() | Ming (flash)
setover | swfbutton_setOver() | Ming (flash)
setrate | swfmovie_setRate() | Ming (flash)
setratio | swfdisplayitem_setRatio() | Ming (flash)
setrightfill | swfshape_setrightfill() | Ming (flash)
setrightmargin | swftextfield_setRightMargin() | Ming (flash)
setspacing | swftext_setSpacing() | Ming (flash)
setup | swfbutton_setUp() | Ming (flash)
show_source | highlight_file() | Base syntax
sizeof | count() | Base syntax
skewx | swfdisplayitem_skewX() | Ming (flash)
skewxto | swfdisplayitem_skewXTo() | Ming (flash)
skewxto | swffill_skewXTo() | Ming (flash)
skewy | swfdisplayitem_skewY() | Ming (flash)
skewyto | swfdisplayitem_skewYTo() | Ming (flash)
skewyto | swffill_skewYTo() | Ming (flash)
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Base syntax
streammp3 | swfmovie_streamMp3() | Ming (flash)
swfaction | swfaction_init() | Ming (flash)
swfbitmap | swfbitmap_init() | Ming (flash)
swfbutton | swfbutton_init() | Ming (flash)
swffill | swffill_init() | Ming (flash)
swffont | swffont_init() | Ming (flash)
swfgradient | swfgradient_init() | Ming (flash)
swfmorph | swfmorph_init() | Ming (flash)
swfmovie | swfmovie_init() | Ming (flash)
swfshape | swfshape_init() | Ming (flash)
swfsprite | swfsprite_init() | Ming (flash)
swftext | swftext_init() | Ming (flash)
swftextfield | swftextfield_init() | Ming (flash)
unlink | domxml_unlink_node() | DOM XML
xptr_new_context | xpath_new_context() | DOM XML

Prev | Home | Next
State | Up | List of Reserved Words


List of Reserved Words

PHP Manual
Prev Next

Appendix K. List of Reserved Words

Table of Contents
List of Keywords
Predefined Variables
Predefined Classes
Predefined Constants

The following is a listing of predefined identifiers in PHP. None of the identifiers listed here should be used as identifiers in any of your scripts. These lists include keywords and predefined variable, constant, and class names. These lists are neither exhaustive or complete.

List of Keywords

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on--but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.

Table K-1. PHP Keywords

and | or | xor | __FILE__ | exception (PHP 5)
__LINE__ | array() | as | break | case
class | const | continue | declare | default
die() | do | echo() | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
for | foreach | function | global | if
include() | include_once() | isset() | list() | new
print() | require() | require_once() | return() | static
switch | unset() | use | var | while
__FUNCTION__ | __CLASS__ | __METHOD__ | final (PHP 5) | php_user_filter (PHP 5)
interface (PHP 5) | implements (PHP 5) | extends | public (PHP 5) | private (PHP 5)
protected (PHP 5) | abstract (PHP 5) | clone (PHP 5) | try (PHP 5) | catch (PHP 5)
throw (PHP 5) | cfunction (PHP 4 only) | old_function (PHP 4 only) | this (PHP 5 only) |

Prev | Home | Next
List of Function Aliases | Up | Predefined Variables


Predefined Variables

Since PHP 4.1.0, the preferred method for retrieving external variables is with the superglobals mentioned below. Before this time, people relied on either register_globals or the long predefined PHP arrays ($HTTP_*_VARS). As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

Server variables: $_SERVER

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_SERVER_VARS.

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the webserver. There is no guarantee that every webserver will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the CGI 1.1 specification, so you should be able to expect those.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SERVER; to access it within functions or methods, as you do with $HTTP_SERVER_VARS.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SERVER and $HTTP_SERVER_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'

The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

'argv'

Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.

'argc'

Contains the number of command line parameters passed to the script (if run on the command line).

'GATEWAY_INTERFACE'

What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.

'SERVER_ADDR'

The IP address of the server under which the current script is executing.

'SERVER_NAME'

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_SOFTWARE'

Server identification string, given in the headers when responding to requests.

'SERVER_PROTOCOL'

Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';

'REQUEST_METHOD'

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Note: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'

The timestamp of the start of the request. Available since PHP 5.1.0.

'QUERY_STRING'

The query string, if any, via which the page was accessed.

'DOCUMENT_ROOT'

The document root directory under which the current script is executing, as defined in the server's configuration file.

'HTTP_ACCEPT'

Contents of the Accept: header from the current request, if there is one.

'HTTP_ACCEPT_CHARSET'

Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.

'HTTP_ACCEPT_ENCODING'

Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.

'HTTP_ACCEPT_LANGUAGE'

Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.

'HTTP_CONNECTION'

Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.

'HTTP_HOST'

Contents of the Host: header from the current request, if there is one.

'HTTP_REFERER'

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

'HTTP_USER_AGENT'

Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

'HTTPS'

Set to a non-empty value if the script was queried through the HTTPS protocol.

Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

'REMOTE_ADDR'

The IP address from which the user is viewing the current page.

'REMOTE_HOST'

The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'

The port being used on the user's machine to communicate with the web server.

'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'

The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_PORT'

The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

'SERVER_SIGNATURE'

String containing the server version and virtual host name which are added to server-generated pages, if enabled.

'PATH_TRANSLATED'

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

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.

'SCRIPT_NAME'

Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

'PHP_AUTH_DIGEST'

When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).

'PHP_AUTH_USER'

When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.

'PHP_AUTH_PW'

When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.

'AUTH_TYPE'

When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.

Environment variables: $_ENV

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS.

These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_ENV; to access it within functions or methods, as you do with $HTTP_ENV_VARS.

$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_ENV and $HTTP_ENV_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

HTTP Cookies: $_COOKIE

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_COOKIE_VARS.

An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_COOKIE; to access it within functions or methods, as you do with $HTTP_COOKIE_VARS.

$HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_COOKIE and $HTTP_COOKIE_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

HTTP GET variables: $_GET

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS.

An associative array of variables passed to the current script via the HTTP GET method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_GET; to access it within functions or methods, as you do with $HTTP_GET_VARS.

$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_GET and $HTTP_GET_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

HTTP POST variables: $_POST

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS.

An associative array of variables passed to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_POST; to access it within functions or methods, as you do with $HTTP_POST_VARS.

$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_POST and $HTTP_POST_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

HTTP File upload variables: $_FILES

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_FILES.

An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_FILES; to access it within functions or methods, as you do with $HTTP_POST_FILES.

$HTTP_POST_FILES contains the same information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_FILES and $HTTP_POST_FILES arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

Request variables: $_REQUEST

Note: Introduced in 4.1.0. There is no equivalent array in earlier versions.

Note: Prior to PHP 4.3.0, $_FILES information was also included in $_REQUEST.

An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_REQUEST; to access it within functions or methods.

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_REQUEST array. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

Session variables: $_SESSION

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SESSION; to access it within functions or methods, as you do with $HTTP_SESSION_VARS.

$HTTP_SESSION_VARS contains the same information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SESSION and $HTTP_SESSION_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.

Global variables: $GLOBALS

Note: $GLOBALS has been available since PHP 3.0.0.

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.

The previous error message: $php_errormsg

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).

Prev | Home | Next
List of Reserved Words | Up | Predefined Classes


Predefined Classes

This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference.

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory

The class from which dir is instantiated.

stdClass

__PHP_Incomplete_Class

Predefined classes as of PHP 5

These additional predefined classes were introduced in PHP 5.0.0

exception

php_user_filter

Prev | Home | Next
Predefined Variables | Up | Predefined Constants


Predefined Constants

Core Predefined Constants

These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.

PHP_VERSION (string)

PHP_OS (string)

PHP_SAPI (string)

Available since PHP 4.2.0. See also php_sapi_name().

PHP_EOL (string)

Available since PHP 4.3.10 and PHP 5.0.2

PHP_INT_MAX (integer)

Available since PHP 4.4.0 and PHP 5.0.5

PHP_INT_SIZE (integer)

Available since PHP 4.4.0 and PHP 5.0.5

DEFAULT_INCLUDE_PATH (string)

PEAR_INSTALL_DIR (string)

PEAR_EXTENSION_DIR (string)

PHP_EXTENSION_DIR (string)

PHP_PREFIX (string)

Available since PHP 4.3.0

PHP_BINDIR (string)

PHP_LIBDIR (string)

PHP_DATADIR (string)

PHP_SYSCONFDIR (string)

PHP_LOCALSTATEDIR (string)

PHP_CONFIG_FILE_PATH (string)

PHP_CONFIG_FILE_SCAN_DIR (string)

PHP_SHLIB_SUFFIX (string)

Available since PHP 4.3.0

PHP_OUTPUT_HANDLER_START (integer)

PHP_OUTPUT_HANDLER_CONT (integer)

PHP_OUTPUT_HANDLER_END (integer)

E_ERROR (integer)

E_WARNING (integer)

E_PARSE (integer)

E_NOTICE (integer)

E_CORE_ERROR (integer)

E_CORE_WARNING (integer)

E_COMPILE_ERROR (integer)

E_COMPILE_WARNING (integer)

E_USER_ERROR (integer)

E_USER_WARNING (integer)

E_USER_NOTICE (integer)

E_ALL (integer)

E_STRICT (integer)

Available since PHP 5.0.0

__COMPILER_HALT_OFFSET__ (integer)

Available since PHP 5.1.0

See also: Magic constants.

Standard Predefined Constants

These constants are defined in PHP by default.

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

SORT_ASC (integer)

SORT_DESC (integer)

SORT_REGULAR (integer)

SORT_NUMERIC (integer)

SORT_STRING (integer)

CASE_LOWER (integer)

CASE_UPPER (integer)

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

INI_USER (integer)

INI_PERDIR (integer)

INI_SYSTEM (integer)

INI_ALL (integer)

M_E (float)

M_LOG2E (float)

M_LOG10E (float)

M_LN2 (float)

M_LN10 (float)

M_PI (float)

M_PI_2 (float)

M_PI_4 (float)

M_1_PI (float)

M_2_PI (float)

M_2_SQRTPI (float)

M_SQRT2 (float)

M_SQRT1_2 (float)

CRYPT_SALT_LENGTH (integer)

CRYPT_STD_DES (integer)

CRYPT_EXT_DES (integer)

CRYPT_MD5 (integer)

CRYPT_BLOWFISH (integer)

DIRECTORY_SEPARATOR (string)

SEEK_SET (integer)

SEEK_CUR (integer)

SEEK_END (integer)

LOCK_SH (integer)

LOCK_EX (integer)

LOCK_UN (integer)

LOCK_NB (integer)

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

INFO_GENERAL (integer)

INFO_CREDITS (integer)

INFO_CONFIGURATION (integer)

INFO_MODULES (integer)

INFO_ENVIRONMENT (integer)

INFO_VARIABLES (integer)

INFO_LICENSE (integer)

INFO_ALL (integer)

CREDITS_GROUP (integer)

CREDITS_GENERAL (integer)

CREDITS_SAPI (integer)

CREDITS_MODULES (integer)

CREDITS_DOCS (integer)

CREDITS_FULLPAGE (integer)

CREDITS_QA (integer)

CREDITS_ALL (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

PATH_SEPARATOR (string)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

ABDAY_1 (integer)

ABDAY_2 (integer)

ABDAY_3 (integer)

ABDAY_4 (integer)

ABDAY_5 (integer)

ABDAY_6 (integer)

ABDAY_7 (integer)

DAY_1 (integer)

DAY_2 (integer)

DAY_3 (integer)

DAY_4 (integer)

DAY_5 (integer)

DAY_6 (integer)

DAY_7 (integer)

ABMON_1 (integer)

ABMON_2 (integer)

ABMON_3 (integer)

ABMON_4 (integer)

ABMON_5 (integer)

ABMON_6 (integer)

ABMON_7 (integer)

ABMON_8 (integer)

ABMON_9 (integer)

ABMON_10 (integer)

ABMON_11 (integer)

ABMON_12 (integer)

MON_1 (integer)

MON_2 (integer)

MON_3 (integer)

MON_4 (integer)

MON_5 (integer)

MON_6 (integer)

MON_7 (integer)

MON_8 (integer)

MON_9 (integer)

MON_10 (integer)

MON_11 (integer)

MON_12 (integer)

AM_STR (integer)

PM_STR (integer)

D_T_FMT (integer)

D_FMT (integer)

T_FMT (integer)

T_FMT_AMPM (integer)

ERA (integer)

ERA_YEAR (integer)

ERA_D_T_FMT (integer)

ERA_D_FMT (integer)

ERA_T_FMT (integer)

ALT_DIGITS (integer)

INT_CURR_SYMBOL (integer)

CURRENCY_SYMBOL (integer)

CRNCYSTR (integer)

MON_DECIMAL_POINT (integer)

MON_THOUSANDS_SEP (integer)

MON_GROUPING (integer)

POSITIVE_SIGN (integer)

NEGATIVE_SIGN (integer)

INT_FRAC_DIGITS (integer)

FRAC_DIGITS (integer)

P_CS_PRECEDES (integer)

P_SEP_BY_SPACE (integer)

N_CS_PRECEDES (integer)

N_SEP_BY_SPACE (integer)

P_SIGN_POSN (integer)

N_SIGN_POSN (integer)

DECIMAL_POINT (integer)

RADIXCHAR (integer)

THOUSANDS_SEP (integer)

THOUSEP (integer)

GROUPING (integer)

YESEXPR (integer)

NOEXPR (integer)

YESSTR (integer)

NOSTR (integer)

CODESET (integer)

LOG_EMERG (integer)

LOG_ALERT (integer)

LOG_CRIT (integer)

LOG_ERR (integer)

LOG_WARNING (integer)

LOG_NOTICE (integer)

LOG_INFO (integer)

LOG_DEBUG (integer)

LOG_KERN (integer)

LOG_USER (integer)

LOG_MAIL (integer)

LOG_DAEMON (integer)

LOG_AUTH (integer)

LOG_SYSLOG (integer)

LOG_LPR (integer)

LOG_NEWS (integer)

LOG_UUCP (integer)

LOG_CRON (integer)

LOG_AUTHPRIV (integer)

LOG_LOCAL0 (integer)

LOG_LOCAL1 (integer)

LOG_LOCAL2 (integer)

LOG_LOCAL3 (integer)

LOG_LOCAL4 (integer)

LOG_LOCAL5 (integer)

LOG_LOCAL6 (integer)

LOG_LOCAL7 (integer)

LOG_PID (integer)

LOG_CONS (integer)

LOG_ODELAY (integer)

LOG_NDELAY (integer)

LOG_NOWAIT (integer)

LOG_PERROR (integer)

Prev | Home | Next
Predefined Classes | Up | List of Resource Types


List of Resource Types

PHP Manual
Prev Next

Appendix L. List of Resource Types

The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.

Table L-1. Resource Types

Resource Type Name | Created By | Used By | Destroyed By | Definition
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference
VARIANT
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib
cpdf outline
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Curl session
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object | dbx_query() | None | dbx result
domxml attribute
domxml document
domxml node
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Link to fbsql database
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | FTP stream
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | GD Image
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server
imap chain persistent
imap persistent
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
java
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result
ldap result entry
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsoft SQL Server database
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsoft SQL Server result
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result
oci8 collection
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database
oci8 descriptor
oci8 server
oci8 session
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close()
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
dir | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fsockopen(), pfsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file

Prev | Home | Next
Predefined Constants | Up | List of Supported Protocols/Wrappers


List of Supported Protocols/Wrappers

PHP Manual
Prev Next

Appendix M. List of Supported Protocols/Wrappers

Table of Contents
Filesystem
Socket
HTTP and HTTPS
FTP and FTPS
PHP input/output streams
Compression Streams
Data (RFC 2397)
Secure Shell 2
Audio Streams
Process Interaction Streams

The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3.0, you can write your own wrappers using PHP script and stream_wrapper_register().

Filesystem

All versions of PHP. Explicitly using file:// since PHP 4.3.0

  • /path/to/file.ext

  • relative/path/to/file.ext

  • fileInCwd.ext

  • C:/path/to/winfile.ext

  • C:\path\to\winfile.ext

  • \\smbserver\share\path\to\winfile.ext

  • file:///path/to/file.ext

Filesystem is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with /, \, \\, or a windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI sapi, this defaults to the directory from which the script was called.

With some functions, such as fopen() and file_get_contents(), include_path may be optionally searched for relative paths as well.

Table M-1. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | Yes
Supports stat() | Yes
Supports unlink() | Yes
Supports rename() | Yes
Supports mkdir() | Yes
Supports rmdir() | Yes

Prev | Home | Next
List of Resource Types | Up | Socket


HTTP and HTTPS

PHP 3, PHP 4, PHP 5. https:// since PHP 4.3.0

  • http://example.com

  • http://example.com/file.php?var1=val1&var2=val2

  • http://user:password@example.com

  • https://example.com

  • https://example.com/file.php?var1=val1&var2=val2

  • https://user:password@example.com

Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your ini file or the stream context, it will also be included in the request.

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.

Redirects have been supported since PHP 4.0.5; if you are using an earlier version you will need to include trailing slashes in your URLs. If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.

&#60;?php
$url = 'http://www.example.com/redirecting_page.php';

$fp = fopen($url, 'r');

/* Prior to PHP 4.3.0 use $http_response_header
   instead of stream_get_meta_data() */
$meta_data = stream_get_meta_data($fp);
foreach($meta_data['wrapper_data'] as $response) {

  /* Were we redirected? */
  if (substr(strtolower($response), 0, 10) == 'location: ') {
    /* update $url with where we were redirected to */
    $url = substr($response, 18);
  }

}

?&#62;

Example M-2. Fetch a page and send POST data

&#60;?php

$postdata = http_build_query(
    array(
        'var1' =&#62; 'some content',
        'var2' =&#62; 'doh'
    )
);

$opts = array('http' =&#62;
    array(
        'method'  =&#62; 'POST',
        'header'  =&#62; 'Content-type: application/x-www-form-urlencoded',
        'content' =&#62; $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?&#62;

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data().

HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.

Note: HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Table M-2. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | Yes
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | N/A
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Table M-3. Context options

Name | Usage | Default
method | GET, POST, or any other HTTP method supported by the remote server. | GET
header | Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:). |
user_agent | Value to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above. | php.ini setting: user_agent
content | Additional data to be sent after the headers. Typically used with POST or PUT requests. |
proxy | URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100). HTTPS proxying (through HTTP proxies) only works in PHP 5.1.0 or greater. |
request_fulluri | When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it. | FALSE
max_redirects | The max number of redirects to follow. Value 1 or less means that no redirects are followed. Added in PHP 5.1.0. | 20
protocol_version | HTTP protocol version. Added in PHP 5.1.0. | 1.0
timeout | Read timeout in seconds, specified by a float (e.g. 10.5). Added in PHP 5.2.1. | default_socket_timeout

Underlying socket stream context options: Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.

Custom headers may be sent with an HTTP request prior to version 5 by taking advantage of a side-effect in the handling of the user_agent INI setting. Set user_agent to any valid string (such as the default PHP/version setting) followed by a carriage-return/line-feed pair and any additional headers. This method works in PHP4 and all later versions.

Example M-3. Sending custom headers with an HTTP request

&#60;?php
ini_set('user_agent', "PHP\r\nX-MyCustomHeader: Foo");

$fp = fopen('http://www.example.com/index.php', 'r');
?&#62;

Results in the following request being sent:

GET /index.php HTTP/1.0
Host: www.example.com
User-Agent: PHP
X-MyCustomHeader: Foo

Prev | Home | Next
Socket | Up | FTP and FTPS


FTP and FTPS

PHP 3, PHP 4, PHP 5. ftps:// since PHP 4.3.0

  • ftp://example.com/pub/file.txt

  • ftp://user:password@example.com/pub/file.txt

  • ftps://example.com/pub/file.txt

  • ftps://user:password@example.com/pub/file.txt

Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.

You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.

Appending: As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In prior versions, attempting to append to a file via ftp:// will result in failure.

ftps:// was introduced in PHP 4.3.0. It is the same as ftp://, but attempts to negotiate a secure connection with the ftp server. If the server does not support SSL, then the connection falls back to regular unencrypted ftp.

Note: FTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Table M-4. Wrapper Summary

Attribute | PHP 4 | PHP 5
Restricted by allow_url_fopen | Yes | Yes
Allows Reading | Yes | Yes
Allows Writing | Yes (new files only) | Yes (new files/existing files with overwrite)
Allows Appending | No | Yes
Allows Simultaneous Reading and Writing | No | No
Supports stat() | No | As of PHP 5.0.0: filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only. As of PHP 5.1.0: filemtime().
Supports unlink() | No | Yes
Supports rename() | No | Yes
Supports mkdir() | No | Yes
Supports rmdir() | No | Yes

Table M-5. Context options (as of PHP 5.0.0)

Name | Usage | Default
overwrite | Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only. | FALSE (Disabled)
resume_pos | File offset at which to begin transfer. Applies to read mode (downloading) only. | 0 (Beginning of File)
proxy (PHP 5.1.0 or greater) | Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000 |

Underlying socket stream context options: Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.

Prev | Home | Next
HTTP and HTTPS | Up | PHP input/output streams


PHP input/output streams

  • php://stdin

  • php://stdout

  • php://stderr

  • php://output

  • php://input

  • php://filter (available since PHP 5.0.0)

  • php://memory (available since PHP 5.1.0)

  • php://temp (available since PHP 5.1.0)

php://stdin, php://stdout and php://stderr allow access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor--the actual stream referenced by STDIN is unaffected. Note that PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.

php://output allows you to write to the output buffer mechanism in the same way as print() and echo().

php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype="multipart/form-data".

php://stdin and php://input are read-only, whereas php://stdout, php://stderr and php://output are write-only.

php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as readfile(), file(), and file_get_contents() where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.

The php://filter target takes the following 'parameters' as parts of its 'path'.

  • /resource=<stream to be filtered> (required) This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.

    &#60;?php
    /* This is equivalent to simply:
       readfile("http://www.example.com");
       since no filters are actually specified */

    readfile("php://filter/resource=http://www.example.com");
    ?&#62;

  • /read=<filter list to apply to read chain> (optional) This parameter takes one or more filternames separated by the pipe character |.

    &#60;?php
    /* This will output the contents of
       www.example.com entirely in uppercase */
    readfile("php://filter/read=string.toupper/resource=http://www.example.com");

    /* This will do the same as above
       but will also ROT13 encode it */
    readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
    ?&#62;

  • /write=<filter list to apply to write chain> (optional) This parameter takes one or more filternames separated by the pipe character |.

    &#60;?php
    /* This will filter the string "Hello World"
       through the rot13 filter, then write to
       example.txt in the current directory */
    file_put_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
    ?&#62;

  • /<filter list to apply to both chains> (optional) Any filter lists which are not prefixed specifically by read= or write= will be applied to both the read and write chains (as appropriate).

The php://memory wrapper stores the data in the memory. php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory limit is reached (the default is 2 MB).

The php://temp wrapper takes the following 'parameters' as parts of its 'path':

  • /maxmemory:<number of bytes> (optional). This parameter allows changing the default value for the memory limit (when the data is moved to a temporary file).

    &#60;?php
    $fiveMBs = 5 * 1024 * 1024;
    $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');

    fputs($fp, "hello\n");

    // read what we have written
    rewind($fp);
    echo stream_get_contents($fp);
    ?&#62;

Table M-6. Wrapper Summary (For php://filter, refer to summary of wrapper being filtered.)

Attribute | Supported
Restricted by allow_url_fopen | No
Restricted by allow_url_include | php://input, php://stdin, php://memory and php://temp only.
Allows Reading | php://stdin, php://input, php://memory and php://temp only.
Allows Writing | php://stdout, php://stderr, php://output, php://memory and php://temp only.
Allows Appending | php://stdout, php://stderr, php://output, php://memory and php://temp only. (Equivalent to writing)
Allows Simultaneous Reading and Writing | php://memory and php://temp only.
Supports stat() | php://memory and php://temp only.
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Prev | Home | Next
FTP and FTPS | Up | Compression Streams


Compression Streams

zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)

compress.zlib:// and compress.bzip2:// PHP 4.3.0 and up

  • zlib:

  • compress.zlib://

  • compress.bzip2://

zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3.0 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.

compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and bzopen() respectively, and operate even on systems that do not support fopencookie.

Table M-7. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | No, use the normal file:// wrapper to stat compressed files.
Supports unlink() | No, use the normal file:// wrapper to unlink compressed files.
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Prev | Home | Next
PHP input/output streams | Up | Data (RFC 2397)


Secure Shell 2

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)

  • ssh2.shell://user:pass@example.com:22/xterm

  • ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd

  • ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14

  • ssh2.sftp://user:pass@example.com:22/path/to/filename

This wrapper is not enabled by default: In order to use the ssh2.*:// wrappers you must install the SSH2 extension available from PECL.

In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.

Example M-6. Opening a stream from an active connection

&#60;?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
                                            '/home/username/.ssh/id_rsa', 'secret');
$stream = fopen("ssh2.tunnel://$session/remote.example.com:1234", 'r');
?&#62;

Table M-9. Wrapper Summary

Attribute | ssh2.shell | ssh2.exec | ssh2.tunnel | ssh2.sftp | ssh2.scp
Restricted by allow_url_fopen | Yes | Yes | Yes | Yes | Yes
Allows Reading | Yes | Yes | Yes | Yes | Yes
Allows Writing | Yes | Yes | Yes | Yes | No
Allows Appending | No | No | No | Yes (When supported by server) | No
Allows Simultaneous Reading and Writing | Yes | Yes | Yes | Yes | No
Supports stat() | No | No | No | Yes | No
Supports unlink() | No | No | No | Yes | No
Supports rename() | No | No | No | Yes | No
Supports mkdir() | No | No | No | Yes | No
Supports rmdir() | No | No | No | Yes | No

Table M-10. Context options

Name | Usage | Default
session | Preconnected ssh2 resource to be reused |
sftp | Preallocated sftp resource to be reused |
methods | Key exchange, hostkey, cipher, compression, and MAC methods to use |
callbacks |  |
username | Username to connect as |
password | Password to use with password authentication |
pubkey_file | Name of public key file to use for authentication |
privkey_file | Name of private key file to use for authentication |
env | Associate array of environment variables to set |
term | Terminal emulation type to request when allocating a pty |
term_width | Width of terminal requested when allocating a pty |
term_height | Height of terminal requested when allocating a pty |
term_units | Units to use with term_width and term_height | SSH2_TERM_UNIT_CHARS

Prev | Home | Next
Data (RFC 2397) | Up | Audio Streams


Audio Streams

ogg:// PHP 4.3.0 and up (PECL)

  • ogg://soundfile.ogg

  • ogg:///path/to/soundfile.ogg

  • ogg://http://www.example.com/path/to/soundstream.ogg

This wrapper is not enabled by default: In order to use the ogg:// wrapper you must install the OGG/Vorbis extension available from PECL.

Files opened for reading via the ogg:// wrapper are treated as compressed audio encoded using the OGG/Vorbis codec. Similarly, files opened for writing or appending via the ogg:// wrapper are writen as compressed audio data. stream_get_meta_data(), when used on an OGG/Vorbis file opened for reading will return various details about the stream including the vendor tag, any included comments, the number of channels, the sampling rate, and the encoding rate range described by: bitrate_lower, bitrate_upper, bitrate_nominal, and bitrate_window.

Table M-11. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Table M-12. Context options

Name | Usage | Default | Mode
pcm_mode | PCM encoding to apply while reading, one of: OGGVORBIS_PCM_U8, OGGVORBIS_PCM_S8, OGGVORBIS_PCM_U16_BE, OGGVORBIS_PCM_S16_BE, OGGVORBIS_PCM_U16_LE, and OGGVORBIS_PCM_S16_LE. (8 vs 16 bit, signed or unsigned, big or little endian) | OGGVORBIS_PCM_S16_LE | Read
rate | Sampling rate of input data, expressed in Hz | 44100 | Write/Append
bitrate | When given as an integer, the fixed bitrate at which to encode. (16000 to 131072) When given as a float, the variable bitrate quality to use. (-1.0 to 1.0) | 128000 | Write/Append
channels | The number of audio channels to encode, typically 1 (Mono), or 2 (Stero). May range as high as 16. | 2 | Write/Append
comments | An array of string values to encode into the track header. |  | Write/Append

Prev | Home | Next
Secure Shell 2 | Up | Process Interaction Streams


List of Available Filters

PHP Manual
Prev Next

Appendix N. List of Available Filters

Table of Contents
String Filters
Conversion Filters
Compression Filters
Encryption Filters

The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.

It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.

For a list of filters installed in your version of PHP use stream_get_filters().

String Filters

Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.

string.rot13 (since PHP 4.3.0) Use of this filter is equivalent to processing all stream data through the str_rot13() function.

Example N-1. string.rot13

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs:  Guvf vf n grfg.   */
?&#62;

string.toupper (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtoupper() function.

Example N-2. string.toupper

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs:  THIS IS A TEST.   */
?&#62;

string.tolower (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtolower() function.

Example N-3. string.tolower

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs:  this is a test.   */
?&#62;

string.strip_tags (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.

Example N-4. string.strip_tags

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "&#60;b&#62;&#60;i&#62;&#60;u&#62;");
fwrite($fp, "&#60;b&#62;bolded text&#60;/b&#62; enlarged to a &#60;h1&#62;level 1 heading&#60;/h1&#62;\n");
fclose($fp);
/* Outputs:  &#60;b&#62;bolded text&#60;/b&#62; enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "&#60;b&#62;bolded text&#60;/b&#62; enlarged to a &#60;h1&#62;level 1 heading&#60;/h1&#62;\n");
fclose($fp);
/* Outputs:  &#60;b&#62;bolded text&#60;/b&#62; enlarged to a level 1 heading   */
?&#62;

Prev | Home | Next
Process Interaction Streams | Up | Conversion Filters


Conversion Filters

Like the string.* filters, the convert.* filters perform actions similar to their names. The convert filters were added with PHP 5.0.0. For more information on a given filter, refer to the manual page for the corresponding function.

convert.base64-encode and convert.base64-decode Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively. convert.base64-encode supports parameters given as an associative array. If line-length is given, the base64 output will be split into chunks of line-length characters each. If line-break-chars is given, each chunk will be delimited by the characters given. These parameters give the same effect as using base64_encode() with chunk_split().

Example N-5. convert.base64-encode & convert.base64-decode

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' =&#62; 8, 'line-break-chars' =&#62; "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs:  This is a test.  */
?&#62;

convert.quoted-printable-encode and convert.quoted-printable-decode Use of the decode version of this filter is equivalent to processing all stream data through the quoted_printable_decode() functions. There is no function equivalent to convert.quoted-printable-encode. convert.quoted-printable-encode supports parameters given as an associative array. In addition to the parameters supported by convert.base64-encode, convert.quoted-printable-encode also supports boolean arguments binary and force-encode-first. convert.base64-decode only supports the line-break-chars parameter as a type-hint for striping from the encoded payload.

Example N-6. convert.quoted-printable-encode & convert.quoted-printable-decode

&#60;?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs:  =This is a test.=0A  */
?&#62;

Prev | Home | Next
List of Available Filters | Up | Compression Filters


Compression Filters

While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.

Note: Compression filters do not generate headers and trailers used by commandline utilites such as gzip. They only compress and decompress the payload portions of compressed data streams.

zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.

Note: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).

zlib.* compression filters are available with PHP as of version 5.1.0 if zlib support is enabled. They are also available as a backport in version 5.0.x by installing the zlib_filter package from PECL. These filters are not available for PHP 4.

Example N-7. zlib.deflate and zlib.inflate

&#60;?php
$params = array('level' =&#62; 6, 'window' =&#62; 15, 'memory' =&#62; 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

 */
?&#62;

Example N-8. zlib.deflate simple

&#60;?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?&#62;

bzip2.compress and bzip2.decompress work in the same manner as the zlib filters described above. The bzip2.compress filter accepts up to two parameters given as elements of an associative array: blocks is an integer value from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for workspace. work is also an integer value ranging from 0 to 250 indicating how much effort to expend using the normal compression method before falling back on a slower, but more reliable method. Tuning this parameter effects only compression speed. Neither size of compressed output nor memory usage are changed by this setting. A work factor of 0 instructs the bzip library to use an internal default. The bzip2.decompress filter only accepts one parameter, which can be passed as either an ordinary boolean value, or as the small element of an associative array. small, when set to a TRUE value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.

bzip2.* compression filters are available with PHP as of version 5.1.0 if bz2 support is enabled. They are also available as a backport in version 5.0.x by installing the bz2_filter package from PECL. These filters are not available for PHP 4.

Example N-9. bzip2.compress and bzip2.decompress

&#60;?php
$param = array('blocks' =&#62; 9, 'work' =&#62; 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?&#62;

Prev | Home | Next
Conversion Filters | Up | Encryption Filters


Encryption Filters

mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:

Table N-1. mcrypt filter parameters

Parameter | Required? | Default | Sample Values
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules
iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher
key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher

Example N-10. Encrypting file output using 3DES

&#60;?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=&#62;$iv, 'key'=&#62;$key);

$fp = fopen('secert-file.enc', 'wb');
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'Secret secret secret data');
fclose($fp);
?&#62;

Example N-11. Reading an encrypted file

&#60;?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=&#62;$iv, 'key'=&#62;$key);

$fp = fopen('secert-file.enc', 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_WRITE, $opts);
$data = rtrim(stream_get_contents($fp));
fclose($fp);

echo $data;
?&#62;

Prev | Home | Next
Compression Filters | Up | List of Supported Socket Transports


List of Supported Socket Transports

PHP Manual
Prev Next

Appendix O. List of Supported Socket Transports

Table of Contents
Internet Domain: TCP, UDP, SSL, and TLS
Unix Domain: Unix and UDG

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().

Internet Domain: TCP, UDP, SSL, and TLS

PHP 3, PHP 4, PHP 5. ssl:// & tls:// since PHP 4.3.0 sslv2:// & sslv3:// since PHP 5.0.2

Note: If no transport is specified, tcp:// will be assumed.

  • 127.0.0.1

  • fe80::1

  • www.example.com

  • tcp://127.0.0.1

  • tcp://fe80::1

  • tcp://www.example.com

  • udp://www.example.com

  • ssl://www.example.com

  • sslv2://www.example.com

  • sslv3://www.example.com

  • tls://www.example.com

Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80

  • tcp://[fe80::1]:80

  • tcp://www.example.com:80

IPv6 numeric addresses with port numbers: In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.

ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.

Table O-1. Context options for ssl:// and tls:// transports (since PHP 4.3.2)

Name | Usage | Default
verify_peer | TRUE or FALSE. Require verification of SSL certificate used. | FALSE
allow_self_signed | TRUE or FALSE. Allow self-signed certificates. | FALSE
cafile | Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer. |
capath | If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory. |
local_cert | Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers. |
passphrase | Passphrase with which your local_cert file was encoded. |
CN_match | Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail. |

Note: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.

Prev | Home | Next
Encryption Filters | Up | Unix Domain: Unix and UDG


Unix Domain: Unix and UDG

unix:// since PHP 3, udg:// since PHP 5

  • unix:///tmp/mysock

  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.

Prev | Home | Next
List of Supported Socket Transports | Up | PHP type comparison tables


PHP type comparison tables

PHP Manual
Prev Next

Appendix P. PHP type comparison tables

The following tables demonstrate behaviors of PHP types and comparison operators, for both loose and strict comparisons. This supplemental is also related to the manual section on type juggling. Inspiration was provided by various user comments and by the work over at BlueShoes.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an integer. FALSE is a boolean while "false" is a string.

Note: HTML Forms do not pass integers, floats, or booleans; they pass strings. To find out if a string is numeric, you may use is_numeric().

Note: Simply doing if ($x) while $x is undefined will generate an error of level E_NOTICE. Instead, consider using empty() or isset() and/or initialize your variables.

Table P-1. Comparisons of $x with PHP functions

Expression | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | TRUE | FALSE | TRUE | FALSE
$x = NULL | NULL | TRUE | TRUE | FALSE | FALSE
var $x; | NULL | TRUE | TRUE | FALSE | FALSE
$x is undefined | NULL | TRUE | TRUE | FALSE | FALSE
$x = array(); | array | TRUE | FALSE | TRUE | FALSE
$x = false; | boolean | TRUE | FALSE | TRUE | FALSE
$x = true; | boolean | FALSE | FALSE | TRUE | TRUE
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE
$x = 42; | integer | FALSE | FALSE | TRUE | TRUE
$x = 0; | integer | TRUE | FALSE | TRUE | FALSE
$x = -1; | integer | FALSE | FALSE | TRUE | TRUE
$x = "1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "0"; | string | TRUE | FALSE | TRUE | FALSE
$x = "-1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "php"; | string | FALSE | FALSE | TRUE | TRUE
$x = "true"; | string | FALSE | FALSE | TRUE | TRUE
$x = "false"; | string | FALSE | FALSE | TRUE | TRUE

Table P-2. Loose comparisons with ==

 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE
FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE
1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE
-1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
"1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | TRUE
array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | FALSE
"php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE

Table P-3. Strict comparisons with ===

 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
-1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE
array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE
"php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE

PHP 3.0 note: The string value "0" was considered non-empty in PHP 3, this behavior changed in PHP 4 where it's now seen as empty.

Prev | Home | Next
Unix Domain: Unix and UDG | Up | List of Parser Tokens


List of Parser Tokens

PHP Manual
Prev Next

Appendix Q. List of Parser Tokens

Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.

Table Q-1. Tokens

Token | Syntax | Reference
T_ABSTRACT | abstract | the Section called Class Abstraction in Chapter 19 (available since PHP 5.0.0)
T_AND_EQUAL | &= | assignment operators
T_ARRAY | array() | array(), array syntax
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_BAD_CHARACTER |  | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND | && | logical operators
T_BOOLEAN_OR | || | logical operators
T_BOOL_CAST | (bool) or (boolean) | type-casting
T_BREAK | break | break
T_CASE | case | switch
T_CATCH | catch | Chapter 20 (available since PHP 5.0.0)
T_CHARACTER |  |
T_CLASS | class | classes and objects
T_CLONE | clone | classes and objects (available since PHP 5.0.0)
T_CLOSE_TAG | ?> or %> |
T_COMMENT | // or #, and /* */ in PHP 5 | comments
T_CONCAT_EQUAL | .= | assignment operators
T_CONST | const |
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax
T_CONTINUE | continue |
T_CURLY_OPEN |  |
T_DEC | -- | incrementing/decrementing operators
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIV_EQUAL | /= | assignment operators
T_DNUMBER | 0.12, etc | floating point numbers
T_DOC_COMMENT | /** */ | PHPDoc style comments (available since PHP 5.0.0)
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax
T_DOUBLE_ARROW | => | array syntax
T_DOUBLE_CAST | (real), (double) or (float) | type-casting
T_DOUBLE_COLON | :: | see T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO | echo | echo()
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE |  |
T_ENDDECLARE | enddeclare | declare, alternative syntax
T_ENDFOR | endfor | for, alternative syntax
T_ENDFOREACH | endforeach | foreach, alternative syntax
T_ENDIF | endif | if, alternative syntax
T_ENDSWITCH | endswitch | switch, alternative syntax
T_ENDWHILE | endwhile | while, alternative syntax
T_END_HEREDOC |  | heredoc syntax
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, classes and objects
T_FILE | __FILE__ | constants
T_FINAL | final | the Section called Final Keyword in Chapter 19 (available since PHP 5.0.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function or cfunction | functions
T_GLOBAL | global | variable scope
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (available since PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | the Section called Object Interfaces in Chapter 19 (available since PHP 5.0.0)
T_INC | ++ | incrementing/decrementing operators
T_INCLUDE | include() | include()
T_INCLUDE_ONCE | include_once() | include_once()
T_INLINE_HTML |  |
T_INSTANCEOF | instanceof | type operators (available since PHP 5.0.0)
T_INT_CAST | (int) or (integer) | type-casting
T_INTERFACE | interface | the Section called Object Interfaces in Chapter 19 (available since PHP 5.0.0)
T_ISSET | isset() | isset()
T_IS_EQUAL | == | comparison operators
T_IS_GREATER_OR_EQUAL | >= | comparison operators
T_IS_IDENTICAL | === | comparison operators
T_IS_NOT_EQUAL | != or <> | comparison operators
T_IS_NOT_IDENTICAL | !== | comparison operators
T_IS_SMALLER_OR_EQUAL | <= | comparison operators
T_LINE | __LINE__ | constants
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc | integers
T_LOGICAL_AND | and | logical operators
T_LOGICAL_OR | or | logical operators
T_LOGICAL_XOR | xor | logical operators
T_MINUS_EQUAL | -= | assignment operators
T_ML_COMMENT | /* and */ | comments (PHP 4 only)
T_MOD_EQUAL | %= | assignment operators
T_MUL_EQUAL | *= | assignment operators
T_NEW | new | classes and objects
T_NUM_STRING |  |
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | classes and objects
T_OLD_FUNCTION | old_function | old_function
T_OPEN_TAG | <?php, <? or <% | escaping from HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML
T_OR_EQUAL | |= | assignment operators
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Also defined as T_DOUBLE_COLON.
T_PLUS_EQUAL | += | assignment operators
T_PRINT | print() | print()
T_PRIVATE | private | classes and objects (available since PHP 5.0.0)
T_PUBLIC | public | classes and objects (available since PHP 5.0.0)
T_PROTECTED | protected | classes and objects (available since PHP 5.0.0)
T_REQUIRE | require() | require()
T_REQUIRE_ONCE | require_once() | require_once()
T_RETURN | return | returning values
T_SL | << | bitwise operators
T_SL_EQUAL | <<= | assignment operators
T_SR | >> | bitwise operators
T_SR_EQUAL | >>= | assignment operators
T_START_HEREDOC | <<< | heredoc syntax
T_STATIC | static | variable scope
T_STRING |  |
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME |  |
T_SWITCH | switch | switch
T_THROW | throw | Chapter 20 (available since PHP 5.0.0)
T_TRY | try | Chapter 20 (available since PHP 5.0.0)
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | (not documented; casts to NULL)
T_USE | use | (not implemented)
T_VAR | var | classes and objects
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE |  |
T_XOR_EQUAL | ^= | assignment operators
T_FUNC_C | __FUNCTION__ | constants (available since PHP 4.3.0)
T_CLASS_C | __CLASS__ | constants (available since PHP 4.3.0)

See also token_name().

Prev | Home | Next
PHP type comparison tables | Up | Userland Naming Guide


About the manual

PHP Manual
Prev Next

Appendix S. About the manual

Table of Contents
Formats
About user notes
How to read a function definition (prototype)
PHP versions documented in this manual
How to find more information about PHP
How to help improve the documentation
How we generate the formats
Translations

Formats

The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.

Note: Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.

The manual can be read online at the PHP.net website, and on the numerous mirror sites. For best performance, choose the closest mirror. The online version of the PHP manual has currently two CSS stylesheets, web friendly and a printer-friendly stylesheet.

Two notable advantages of the online manual over most of the offline formats is the integration of user-contributed notes and the URL shortcuts that may be used to get to the desired manual parts quickly. An obvious disadvantage is the requirement to be online to view this edition of the manual.

There are several offline formats of the manual, and the most appropriate format for depends on the operating system, and personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.

The most cross-platform format of the manual is the HTML version. This is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). We provide these versions compressed, so a decompression utility is required to retrieve the files contained within the archives.

For Windows platforms, the Windows HTML Help version of the manual enhances the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access. CHM viewers for Linux desktops are also available. Check out xCHM or GnoCHM.

There is also an extended CHM version available, which is updated less frequently, but provides many additional features. It will only work on Microsoft Windows though, because of the technologies used to build the help pages.

Prev | Home | Next
Tips | Up | About user notes


About user notes

The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they may be viewed in their submitted form online, and in some of the offline formats.

Note: The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)

Note: For the purposes of license coverage the user-contributed notes are considered part of the PHP manual, and are therefore covered by the same license that covers this documentation (Open Publication License at the moment). For more details see the Manual's Copyright page.

Prev | Home | Next
About the manual | Up | How to read a function definition (prototype)


How to read a function definition (prototype)

Each function in the manual is documented for quick reference. Knowing how to read and understand the text will make learning PHP much easier. Rather than relying on examples or cut/paste, everyone should know how to read function definitions (prototypes). Let's begin:

Prerequisite: Basic understanding of types: Although PHP is a loosely typed language, it's important to have a basic understanding of types as they have important meaning.

Function definitions tell us what type of value is returned. Let's use the definition for strlen() as our first example:

strlen

(PHP 3, PHP 4, PHP 5)
strlen -- Get string length

Description
int strlen ( string $string )

Returns the length of given string.

Table S-1. Explanation of a function definition

Part | Description
strlen | The function name.
(PHP 3, PHP 4, PHP 5) | strlen() has been around in all versions of PHP 3, PHP 4 and PHP 5
int | Type of value this function returns, which is an integer (i.e. the length of a string is measured in numbers).
( string $string ) | The first (and in this case the only) parameter/argument for this function is named string, and it's a string.

We could rewrite the above function definition in a generic way:

returned type    function name    ( parameter type   parameter name )

Many functions take on multiple parameters, such as in_array(). Its prototype is as follows:

bool in_array ( mixed $needle, array $haystack [, bool $strict])

What does this mean? in_array() returns a boolean value, TRUE on success (if the needle was found in the haystack) or FALSE on failure (if the needle was not found in the haystack). The first parameter is named needle and it can be of many different types, so we call it "mixed". This mixed needle (what we're looking for) can be either a scalar value (string, integer, or float), or an array. haystack (the array we're searching in) is the second parameter. The third optional parameter is named strict. All optional parameters are seen in [ brackets ]. The manual states that the strict parameter defaults to boolean FALSE. See the manual page on each function for details on how they work.

There are also functions with more complex PHP version information. Take html_entity_decode() as an example:

(PHP 4 >= 4.3.0, PHP 5)

This means that this function was not available in PHP 3, and is only available in a released version since PHP 4.3.0.

Prev | Home | Next
About user notes | Up | PHP versions documented in this manual


PHP versions documented in this manual

This documentation contains information about current and future PHP versions, with some added migration and compatibility notes regarding PHP 3. Behaviour, parameter, return value and other changes between different PHP versions are documented in notes and inline text in the manual.

Documentation partly exists for the CVS version of PHP, which always means the very latest development version. This has yet to be released so is only available through the CVS version handling system, or via a snapshot. So be aware that features marked "available in CVS" are typically unavailable. These features, though, will most likely be available in the next stable version of PHP. To download the CVS version, see the anonymous CVS access page.

So, documentation may exist for PHP versions that aren't yet released. (Something like PHP 6.x.x while the latest stable version might be 5.x.x). Most of the time, this is not an error in the documentation. Explanation is often added for features not available in the current PHP release, but will be available as a known future PHP version. Typically, PHP only adds new features in major releases otherwise only bugs are fixed. Using the A.B.C versioning format, a major release increments A or B whereas minor releases increment C. So for example it's not uncommon for a feature to be documented as available in PHP x.1.x when the latest release is PHP x.0.x. Also note that the manual is written in present tense, not future tense.

Many times the PHP manual lists "Default Values" for PHP directives. These values are based on php.ini-dist and not php.ini-recommended. They also refer to the latest version of PHP. See the PHP directive appendix for details on these values and changes.

Prev | Home | Next
How to read a function definition (prototype) | Up | How to find more information about PHP


How to find more information about PHP

This manual does not attempt to provide instruction about general programming practices. First-time - or even just beginning - programmers may find it difficult to learn how to program in PHP using this manual exclusively. Instead, seek out a text more oriented towards beginners.

There are a number of active mailing lists for discussion on all aspects of programming with PHP. If stuck with a problem, consider using these lists. For support options, including mailing lists, view the PHP.net support page. Furthermore, there is a list of websites devoted to PHP articles, forums, and code galleries at the PHP.net links page .

Prev | Home | Next
PHP versions documented in this manual | Up | How to help improve the documentation


How to help improve the documentation

There are three ways everyone can help improve this documentation.

If an error is found in this manual, in any language, please report them using the bug system at http://bugs.php.net/. Classify the bug as "Documentation Problem". All documentation related problems, including those about manual formats, should be submitted as bug reports.

Note: Please don't abuse the bug system by submitting requests for help. Instead, use one of the many support options.

By contributing notes, users may provide additional examples, caveats, and clarifications for other readers. But please do not submit bug reports using the annotation system. For details, see the section titled 'About user notes'.

The PHP manual is translated into many languages. Knowing English and a foreign language allows for another way to help improve the PHP manual by working with a translation team. For information about starting a new translation, or helping a currently translated version, please read http://doc.php.net/php/dochowto/.

The PHP Documentation Project also has an IRC channel where many manual authors hang out. Stop by #php.doc on irc.efnet.org and discuss ways to improve the PHP documentation.

Prev | Home | Next
How to find more information about PHP | Up | How we generate the formats


How we generate the formats

This manual is written in XML using the DocBook XML DTD, using XSLT (Extensible Stylesheet Language Transformations) for maintenance and formatting.

Using XML as a source format gives the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tools used for formatting the online manual are xsltproc and DocBook XSL Stylesheets. The HTML and TeX versions use Jade, written by James Clark; and The Modular DocBook Stylesheets, written by Norman Walsh. We use Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.

The PHP manual is generated in various languages and formats, see http://www.php.net/docs.php for additional details. The XML source code may be downloaded from CVS and viewed at http://cvs.php.net/. The documentation is stored in the phpdoc module.

Prev | Home | Next
How to help improve the documentation | Up | Translations


Translations

The PHP manual is available not only in various formats, but also in various languages. The text of the manual is first written in English, then teams of people across the world take care of translating it to their native languages. If a translation for a specified function or chapter has not yet been made, the manual's build system falls back to the English version of it.

People involved in the translations start from the XML source code available from http://cvs.php.net/ and from it they translate to their mother language. They do not use the generated versions (like HTML or plain text) as it's the build system that takes care of the conversions from XML to human readable formats.

Note: To help translate the documentation, please get in touch with the translation/documentation team by subscribing to the phpdoc mailing list: send an empty mail to phpdoc-subscribe@lists.php.net. The mailing list address is phpdoc@lists.php.net. State in the message an interest in translating the manual and someone will reply with feedback on moving forward by helping start a new language translation, or by contacting the existing team for the desired language.

At the moment the manual is available, partly or not, in the following languages: Brazilian Portuguese, Chinese (Simplified), Chinese (Hong Kong Cantonese), Chinese (Traditional), Czech, Dutch, Finnish, French, German, Greek, Hebrew, Hungarian, Italian, Japanese, Korean, Polish, Romanian, Russian, Slovak, Slovenian, Spanish, Swedish, and Turkish.

They may all be downloaded here: http://www.php.net/docs.php.

Prev | Home | Next
How we generate the formats | Up | Open Publication License


Open Publication License

PHP Manual
Prev Next

Appendix T. Open Publication License

Table of Contents
I. REQUIREMENTS ON BOTH UNMODIFIED AND MODIFIED VERSIONS
II. COPYRIGHT
III. SCOPE OF LICENSE
IV. REQUIREMENTS ON MODIFIED WORKS
V. GOOD-PRACTICE RECOMMENDATIONS
VI. LICENSE OPTIONS

v1.0, 8 June 1999

I. REQUIREMENTS ON BOTH UNMODIFIED AND MODIFIED VERSIONS

The Open Publication works may be reproduced and distributed in whole or in part, in any medium physical or electronic, provided that the terms of this license are adhered to, and that this license or an incorporation of it by reference (with any options elected by the author(s) and/or publisher) is displayed in the reproduction.

Proper form for an incorporation by reference is as follows:

Copyright (c) <year> by <author's name or designee>. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, vX.Y or later (the latest version is presently available at http://www.opencontent.org/openpub/

The reference must be immediately followed with any options elected by the author(s) and/or publisher of the document (see section VI). Commercial redistribution of Open Publication-licensed material is permitted. Any publication in standard (paper) book form shall require the citation of the original publisher and author. The publisher and author's names shall appear on all outer surfaces of the book. On all outer surfaces of the book the original publisher's name shall be as large as the title of the work and cited as possessive with respect to the title.

Prev | Home | Next
Translations | Up | II. COPYRIGHT


II. COPYRIGHT

The copyright to each Open Publication is owned by its author(s) or designee.

Prev | Home | Next
Open Publication License | Up | III. SCOPE OF LICENSE


III. SCOPE OF LICENSE

The following license terms apply to all Open Publication works, unless otherwise explicitly stated in the document.

Mere aggregation of Open Publication works or a portion of an Open Publication work with other works or programs on the same media shall not cause this license to apply to those other works. The aggregate work shall contain a notice specifying the inclusion of the Open Publication material and appropriate copyright notice.

SEVERABILITY. If any part of this license is found to be unenforceable in any jurisdiction, the remaining portions of the license remain in force.

NO WARRANTY. Open Publication works are licensed and provided "as is" without warranty of any kind, express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose or a warranty of non-infringement.

Prev | Home | Next
II. COPYRIGHT | Up | IV. REQUIREMENTS ON MODIFIED WORKS


IV. REQUIREMENTS ON MODIFIED WORKS

All modified versions of documents covered by this license, including translations, anthologies, compilations and partial documents, must meet the following requirements:

  1. The modified version must be labeled as such.

  2. The person making the modifications must be identified and the modifications dated.

  3. Acknowledgement of the original author and publisher if applicable must be retained according to normal academic citation practices.

  4. The location of the original unmodified document must be identified.

  5. The original author's (or authors') name(s) may not be used to assert or imply endorsement of the resulting document without the original author's (or authors') permission.

Prev | Home | Next
III. SCOPE OF LICENSE | Up | V. GOOD-PRACTICE RECOMMENDATIONS


V. GOOD-PRACTICE RECOMMENDATIONS

In addition to the requirements of this license, it is requested from and strongly recommended of redistributors that:

  1. If you are distributing Open Publication works on hardcopy or CD-ROM, you provide email notification to the authors of your intent to redistribute at least thirty days before your manuscript or media freeze, to give the authors time to provide updated documents. This notification should describe modifications, if any, made to the document.

  2. All substantive modifications (including deletions) be either clearly marked up in the document or else described in an attachment to the document.

  3. Finally, while it is not mandatory under this license, it is considered good form to offer a free copy of any hardcopy and CD-ROM expression of an Open Publication-licensed work to its author(s).

Prev | Home | Next
IV. REQUIREMENTS ON MODIFIED WORKS | Up | VI. LICENSE OPTIONS


VI. LICENSE OPTIONS

The author(s) and/or publisher of an Open Publication-licensed document may elect certain options by appending language to the reference to or copy of the license. These options are considered part of the license instance and must be included with the license (or its incorporation by reference) in derived works.

A. To prohibit distribution of substantively modified versions without the explicit permission of the author(s). "Substantive modification" is defined as a change to the semantic content of the document, and excludes mere changes in format or typographical corrections.

To accomplish this, add the phrase `Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.' to the license reference or copy.

B. To prohibit any publication of this work or derivative works in whole or in part in standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder.

To accomplish this, add the phrase '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.' to the license reference or copy.

Prev | Home | Next
V. GOOD-PRACTICE RECOMMENDATIONS | Up | Function Index


Function Index

PHP Manual
Prev Next

Appendix U. Function Index

Table of Contents
Function Index

Prev | Home | Next
VI. LICENSE OPTIONS | Up | Function Index


Function Index

A

abs()
acos()
acosh()
addcslashes()
addslashes()
aggregate()
aggregate_info()
aggregate_methods()
aggregate_methods_by_list()
aggregate_methods_by_regexp()
aggregate_properties()
aggregate_properties_by_list()
aggregate_properties_by_regexp()
aggregation_info()
apache_child_terminate()
apache_get_modules()
apache_get_version()
apache_getenv()
apache_lookup_uri()
apache_note()
apache_request_headers()
apache_reset_timeout()
apache_response_headers()
apache_setenv()
apd_breakpoint()
apd_callstack()
apd_clunk()
apd_continue()
apd_croak()
apd_dump_function_table()
apd_dump_persistent_resources()
apd_dump_regular_resources()
apd_echo()
apd_get_active_symbols()
apd_set_pprof_trace()
apd_set_session()
apd_set_session_trace()
apd_set_socket_session_trace()
array()
array_change_key_case()
array_chunk()
array_combine()
array_count_values()
array_diff()
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array_diff_ukey()
array_fill()
array_filter()
array_flip()
array_intersect()
array_intersect_assoc()
array_intersect_key()
array_intersect_uassoc()
array_intersect_ukey()
array_key_exists()
array_keys()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_pad()
array_pop()
array_push()
array_rand()
array_reduce()
array_reverse()
array_search()
array_shift()
array_slice()
array_splice()
array_sum()
array_udiff()
array_udiff_assoc()
array_udiff_uassoc()
array_uintersect()
array_uintersect_assoc()
array_uintersect_uassoc()
array_unique()
array_unshift()
array_values()
array_walk()
array_walk_recursive()
ArrayIterator::current()
ArrayIterator::key()
ArrayIterator::next()
ArrayIterator::rewind()
ArrayIterator::seek()
ArrayIterator::valid()
ArrayObject::__construct()
ArrayObject::append()
ArrayObject::count()
ArrayObject::getIterator()
ArrayObject::offsetExists()
ArrayObject::offsetGet()
ArrayObject::offsetSet()
ArrayObject::offsetUnset()
arsort()
ascii2ebcdic()
asin()
asinh()
asort()
aspell_check()
aspell_check_raw()
aspell_new()
aspell_suggest()
assert()
assert_options()
atan()
atan2()
atanh()

B

base64_decode()
base64_encode()
base_convert()
basename()
bcadd()
bccomp()
bcdiv()
bcmod()
bcmul()
bcompile_write_file()
bcompiler_load()
bcompiler_load_exe()
bcompiler_parse_class()
bcompiler_read()
bcompiler_write_class()
bcompiler_write_constant()
bcompiler_write_exe_footer()
bcompiler_write_footer()
bcompiler_write_function()
bcompiler_write_functions_from_file()
bcompiler_write_header()
bcpow()
bcpowmod()
bcscale()
bcsqrt()
bcsub()
bin2hex()
bind_textdomain_codeset()
bindec()
bindtextdomain()
bzclose()
bzcompress()
bzdecompress()
bzerrno()
bzerror()
bzerrstr()
bzflush()
bzopen()
bzread()
bzwrite()

C

CachingIterator::__toString()
CachingIterator::hasNext()
CachingIterator::next()
CachingIterator::rewind()
CachingIterator::valid()
CachingRecursiveIterator::getChildren()
CachingRecursiveIterator::hasChildren()
cal_days_in_month()
cal_from_jd()
cal_info()
cal_to_jd()
call_user_func()
call_user_func_array()
call_user_method()
call_user_method_array()
ccvs_add()
ccvs_auth()
ccvs_command()
ccvs_count()
ccvs_delete()
ccvs_done()
ccvs_init()
ccvs_lookup()
ccvs_new()
ccvs_report()
ccvs_return()
ccvs_reverse()
ccvs_sale()
ccvs_status()
ccvs_textvalue()
ccvs_void()
ceil()
chdir()
checkdate()
checkdnsrr()
chgrp()
chmod()
chop()
chown()
chr()
chroot()
chunk_split()
class_exists()
class_implements()
class_parents()
classkit_import()
classkit_method_add()
classkit_method_copy()
classkit_method_redefine()
classkit_method_remove()
classkit_method_rename()
clearstatcache()
closedir()
closelog()
com()
com_addref()
com_create_guid()
com_event_sink()
com_get()
com_get_active_object()
com_invoke()
com_isenum()
com_load()
com_load_typelib()
com_message_pump()
com_print_typeinfo()
com_propget()
com_propput()
com_propset()
com_release()
com_set()
compact()
connection_aborted()
connection_status()
connection_timeout()
constant()
convert_cyr_string()
convert_uudecode()
convert_uuencode()
copy()
cos()
cosh()
count()
count_chars()
cpdf_add_annotation()
cpdf_add_outline()
cpdf_arc()
cpdf_begin_text()
cpdf_circle()
cpdf_clip()
cpdf_close()
cpdf_closepath()
cpdf_closepath_fill_stroke()
cpdf_closepath_stroke()
cpdf_continue_text()
cpdf_curveto()
cpdf_end_text()
cpdf_fill()
cpdf_fill_stroke()
cpdf_finalize()
cpdf_finalize_page()
cpdf_global_set_document_limits()
cpdf_import_jpeg()
cpdf_lineto()
cpdf_moveto()
cpdf_newpath()
cpdf_open()
cpdf_output_buffer()
cpdf_page_init()
cpdf_place_inline_image()
cpdf_rect()
cpdf_restore()
cpdf_rlineto()
cpdf_rmoveto()
cpdf_rotate()
cpdf_rotate_text()
cpdf_save()
cpdf_save_to_file()
cpdf_scale()
cpdf_set_action_url()
cpdf_set_char_spacing()
cpdf_set_creator()
cpdf_set_current_page()
cpdf_set_font()
cpdf_set_font_directories()
cpdf_set_font_map_file()
cpdf_set_horiz_scaling()
cpdf_set_keywords()
cpdf_set_leading()
cpdf_set_page_animation()
cpdf_set_subject()
cpdf_set_text_matrix()
cpdf_set_text_pos()
cpdf_set_text_rendering()
cpdf_set_text_rise()
cpdf_set_title()
cpdf_set_viewer_preferences()
cpdf_set_word_spacing()
cpdf_setdash()
cpdf_setflat()
cpdf_setgray()
cpdf_setgray_fill()
cpdf_setgray_stroke()
cpdf_setlinecap()
cpdf_setlinejoin()
cpdf_setlinewidth()
cpdf_setmiterlimit()
cpdf_setrgbcolor()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor_stroke()
cpdf_show()
cpdf_show_xy()
cpdf_stringwidth()
cpdf_stroke()
cpdf_text()
cpdf_translate()
crack_check()
crack_closedict()
crack_getlastmessage()
crack_opendict()
crc32()
create_function()
crypt()
ctype_alnum()
ctype_alpha()
ctype_cntrl()
ctype_digit()
ctype_graph()
ctype_lower()
ctype_print()
ctype_punct()
ctype_space()
ctype_upper()
ctype_xdigit()
curl_close()
curl_copy_handle()
curl_errno()
curl_error()
curl_exec()
curl_getinfo()
curl_init()
curl_multi_add_handle()
curl_multi_close()
curl_multi_exec()
curl_multi_getcontent()
curl_multi_info_read()
curl_multi_init()
curl_multi_remove_handle()
curl_multi_select()
curl_setopt()
curl_version()
current()
cybercash_base64_decode()
cybercash_base64_encode()
cybercash_decr()
cybercash_encr()
cyrus_authenticate()
cyrus_bind()
cyrus_close()
cyrus_connect()
cyrus_query()
cyrus_unbind()

D

date()
date_sunrise()
date_sunset()
dba_close()
dba_delete()
dba_exists()
dba_fetch()
dba_firstkey()
dba_handlers()
dba_insert()
dba_key_split()
dba_list()
dba_nextkey()
dba_open()
dba_optimize()
dba_popen()
dba_replace()
dba_sync()
dbase_add_record()
dbase_close()
dbase_create()
dbase_delete_record()
dbase_get_header_info()
dbase_get_record()
dbase_get_record_with_names()
dbase_numfields()
dbase_numrecords()
dbase_open()
dbase_pack()
dbase_replace_record()
dblist()
dbmclose()
dbmdelete()
dbmexists()
dbmfetch()
dbmfirstkey()
dbminsert()
dbmnextkey()
dbmopen()
dbmreplace()
dbplus_add()
dbplus_aql()
dbplus_chdir()
dbplus_close()
dbplus_curr()
dbplus_errcode()
dbplus_errno()
dbplus_find()
dbplus_first()
dbplus_flush()
dbplus_freealllocks()
dbplus_freelock()
dbplus_freerlocks()
dbplus_getlock()
dbplus_getunique()
dbplus_info()
dbplus_last()
dbplus_lockrel()
dbplus_next()
dbplus_open()
dbplus_prev()
dbplus_rchperm()
dbplus_rcreate()
dbplus_rcrtexact()
dbplus_rcrtlike()
dbplus_resolve()
dbplus_restorepos()
dbplus_rkeys()
dbplus_ropen()
dbplus_rquery()
dbplus_rrename()
dbplus_rsecindex()
dbplus_runlink()
dbplus_rzap()
dbplus_savepos()
dbplus_setindex()
dbplus_setindexbynumber()
dbplus_sql()
dbplus_tcl()
dbplus_tremove()
dbplus_undo()
dbplus_undoprepare()
dbplus_unlockrel()
dbplus_unselect()
dbplus_update()
dbplus_xlockrel()
dbplus_xunlockrel()
dbx_close()
dbx_compare()
dbx_connect()
dbx_error()
dbx_escape_string()
dbx_fetch_row()
dbx_query()
dbx_sort()
dcgettext()
dcngettext()
deaggregate()
debug_backtrace()
debug_print_backtrace()
debug_zval_dump()
debugger_off()
debugger_on()
decbin()
dechex()
decoct()
define()
define_syslog_variables()
defined()
deg2rad()
delete()
descriptor->free()
dgettext()
die()
dio_close()
dio_fcntl()
dio_open()
dio_read()
dio_seek()
dio_stat()
dio_tcsetattr()
dio_truncate()
dio_write()
dir()
DirectoryIterator::__construct()
DirectoryIterator::current()
DirectoryIterator::getATime()
DirectoryIterator::getChildren()
DirectoryIterator::getCTime()
DirectoryIterator::getFilename()
DirectoryIterator::getGroup()
DirectoryIterator::getInode()
DirectoryIterator::getMTime()
DirectoryIterator::getOwner()
DirectoryIterator::getPath()
DirectoryIterator::getPathname()
DirectoryIterator::getPerms()
DirectoryIterator::getSize()
DirectoryIterator::getType()
DirectoryIterator::isDir()
DirectoryIterator::isDot()
DirectoryIterator::isExecutable()
DirectoryIterator::isFile()
DirectoryIterator::isLink()
DirectoryIterator::isReadable()
DirectoryIterator::isWritable()
DirectoryIterator::key()
DirectoryIterator::next()
DirectoryIterator::rewind()
DirectoryIterator::valid()
dirname()
disk_free_space()
disk_total_space()
diskfreespace()
dl()
dngettext()
dns_check_record()
dns_get_mx()
dns_get_record()
dom_import_simplexml()
DOMAttr->isId()
DomAttribute->name()
DomAttribute->specified()
DomAttribute->value()
DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()
DOMDocument->__construct()
DomDocument->add_root()
DomDocument->create_attribute()
DomDocument->create_cdata_section()
DomDocument->create_comment()
DomDocument->create_element()
DomDocument->create_element_ns()
DomDocument->create_entity_reference()
DomDocument->create_processing_instruction()
DomDocument->create_text_node()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()
DomDocument->doctype()
DomDocument->document_element()
DomDocument->dump_file()
DomDocument->dump_mem()
DomDocument->get_element_by_id()
DomDocument->get_elements_by_tagname()
DOMDocument->getElementById()
DOMDocument->getElementsByTagName()
DOMDocument->getElementsByTagNameNS()()
DomDocument->html_dump_mem()
DOMDocument->importNode()
DOMDocument->load()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()
DOMDocument->loadXML()
DOMDocument->normalize()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->save()
DOMDocument->saveHTML()()
DOMDocument->saveHTMLFile()()
DOMDocument->saveXML()()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()
DOMDocument->xinclude()
DomDocument->xinclude()
DomDocumentType->entities()
DomDocumentType->internal_subset()
DomDocumentType->name()
DomDocumentType->notations()
DomDocumentType->public_id()
DomDocumentType->system_id()
DomElement->get_attribute()
DomElement->get_attribute_node()
DomElement->get_elements_by_tagname()
DOMElement->getAttribute()
DOMElement->getAttributeNode()
DOMElement->getAttributeNodeNS()
DOMElement->getAttributeNS()
DOMElement->getElementsByTagName()
DOMElement->getElementsByTagNameNS()
DomElement->has_attribute()
DOMElement->hasAttribute()
DOMElement->hasAttributeNS()
DomElement->remove_attribute()
DOMElement->removeAttribute()
DOMElement->removeAttributeNode()
DOMElement->removeAttributeNS()
DomElement->set_attribute()
DOMElement->setAttribute()
DOMElement->setAttributeNode()
DOMElement->setAttributeNodeNS()
DOMElement->setAttributeNS()
DomElement->tagname()
DOMImplementation->createDocument()
DOMImplementation->createDocumentType()
DOMImplementation->hasFeature()()
DOMNamedNodeMap->getNamedItem()
DOMNamedNodeMap->getNamedItemNS()
DOMNamedNodeMap->item()
DomNode->add_namespace()
DomNode->append_child()
DomNode->append_sibling()
DOMNode->appendChild()
DomNode->attributes()
DomNode->child_nodes()
DomNode->clone_node()
DOMNode->cloneNode()
DomNode->dump_node()
DomNode->first_child()
DomNode->get_content()
DomNode->has_attributes()
DomNode->has_child_nodes()
DOMNode->hasAttributes()
DOMNode->hasChildNodes()
DomNode->insert_before()
DOMNode->insertBefore()
DomNode->is_blank_node()
DOMNode->isSameNode()
DOMNode->isSupported()
DomNode->last_child()
DOMNode->lookupNamespaceURI()
DOMNode->lookupPrefix()
DomNode->next_sibling()
DomNode->node_name()
DomNode->node_type()
DomNode->node_value()
DOMNode->normalize()
DomNode->owner_document()
DomNode->parent_node()
DomNode->prefix()
DomNode->previous_sibling()
DomNode->remove_child()
DOMNode->removeChild()
DomNode->replace_child()
DomNode->replace_node()
DOMNode->replaceChild()
DomNode->set_content()
DomNode->set_name()
DomNode->set_namespace()
DomNode->unlink_node()
DOMNodelist->item()
DomProcessingInstruction->data()
DomProcessingInstruction->target()
DOMStringList->item()
DOMText->isWhitespaceInElementContent()
DOMText->splitText()
domxml_new_doc()
domxml_open_file()
domxml_open_mem()
domxml_version()
domxml_xmltree()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_doc()
domxml_xslt_stylesheet_file()
DOMXPath->__construct()
DOMXPath->evaluate()()
DOMXPath->query()
DOMXPath->registerNamespace()
DomXsltStylesheet->process()
DomXsltStylesheet->result_dump_file()
DomXsltStylesheet->result_dump_mem()
dotnet()
dotnet_load()
doubleval()

E

each()
easter_date()
easter_days()
ebcdic2ascii()
echo()
empty()
end()
ereg()
ereg_replace()
eregi()
eregi_replace()
error_log()
error_reporting()
escapeshellarg()
escapeshellcmd()
eval()
exec()
exif_imagetype()
exif_read_data()
exif_tagname()
exif_thumbnail()
exit()
exp()
explode()
expm1()
extension_loaded()
extract()
ezmlm_hash()

F

fam_cancel_monitor()
fam_close()
fam_monitor_collection()
fam_monitor_directory()
fam_monitor_file()
fam_next_event()
fam_open()
fam_pending()
fam_resume_monitor()
fam_suspend_monitor()
fbsql_affected_rows()
fbsql_autocommit()
fbsql_blob_size()
fbsql_change_user()
fbsql_clob_size()
fbsql_close()
fbsql_commit()
fbsql_connect()
fbsql_create_blob()
fbsql_create_clob()
fbsql_create_db()
fbsql_data_seek()
fbsql_database()
fbsql_database_password()
fbsql_db_query()
fbsql_db_status()
fbsql_drop_db()
fbsql_errno()
fbsql_error()
fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_field()
fbsql_fetch_lengths()
fbsql_fetch_object()
fbsql_fetch_row()
fbsql_field_flags()
fbsql_field_len()
fbsql_field_name()
fbsql_field_seek()
fbsql_field_table()
fbsql_field_type()
fbsql_free_result()
fbsql_get_autostart_info()
fbsql_hostname()
fbsql_insert_id()
fbsql_list_dbs()
fbsql_list_fields()
fbsql_list_tables()
fbsql_next_result()
fbsql_num_fields()
fbsql_num_rows()
fbsql_password()
fbsql_pconnect()
fbsql_query()
fbsql_read_blob()
fbsql_read_clob()
fbsql_result()
fbsql_rollback()
fbsql_select_db()
fbsql_set_lob_mode()
fbsql_set_password()
fbsql_set_transaction()
fbsql_start_db()
fbsql_stop_db()
fbsql_tablename()
fbsql_username()
fbsql_warnings()
fclose()
fdf_add_doc_javascript()
fdf_add_template()
fdf_close()
fdf_create()
fdf_enum_values()
fdf_errno()
fdf_error()
fdf_get_ap()
fdf_get_attachment()
fdf_get_encoding()
fdf_get_file()
fdf_get_flags()
fdf_get_opt()
fdf_get_status()
fdf_get_value()
fdf_get_version()
fdf_header()
fdf_next_field_name()
fdf_open()
fdf_open_string()
fdf_remove_item()
fdf_save()
fdf_save_string()
fdf_set_ap()
fdf_set_encoding()
fdf_set_file()
fdf_set_flags()
fdf_set_javascript_action()
fdf_set_on_import_javascript()
fdf_set_opt()
fdf_set_status()
fdf_set_submit_form_action()
fdf_set_target_frame()
fdf_set_value()
fdf_set_version()
feof()
fflush()
fgetc()
fgetcsv()
fgets()
fgetss()
file()
file_exists()
file_get_contents()
file_put_contents()
fileatime()
filectime()
filegroup()
fileinode()
filemtime()
fileowner()
fileperms()
filepro()
filepro_fieldcount()
filepro_fieldname()
filepro_fieldtype()
filepro_fieldwidth()
filepro_retrieve()
filepro_rowcount()
filesize()
filetype()
FilterIterator::current()
FilterIterator::getInnerIterator()
FilterIterator::key()
FilterIterator::next()
FilterIterator::rewind()
FilterIterator::valid()
floatval()
flock()
floor()
flush()
fmod()
fnmatch()
fopen()
fpassthru()
fprintf()
fputcsv()
fputs()
fread()
frenchtojd()
fribidi_log2vis()
fscanf()
fseek()
fsockopen()
fstat()
ftell()
ftok()
ftp_alloc()
ftp_cdup()
ftp_chdir()
ftp_chmod()
ftp_close()
ftp_connect()
ftp_delete()
ftp_exec()
ftp_fget()
ftp_fput()
ftp_get()
ftp_get_option()
ftp_login()
ftp_mdtm()
ftp_mkdir()
ftp_nb_continue()
ftp_nb_fget()
ftp_nb_fput()
ftp_nb_get()
ftp_nb_put()
ftp_nlist()
ftp_pasv()
ftp_put()
ftp_pwd()
ftp_quit()
ftp_raw()
ftp_rawlist()
ftp_rename()
ftp_rmdir()
ftp_set_option()
ftp_site()
ftp_size()
ftp_ssl_connect()
ftp_systype()
ftruncate()
func_get_arg()
func_get_args()
func_num_args()
function_exists()
fwrite()

G

gd_info()
get_browser()
get_cfg_var()
get_class()
get_class_methods()
get_class_vars()
get_current_user()
get_declared_classes()
get_declared_interfaces()
get_defined_constants()
get_defined_functions()
get_defined_vars()
get_extension_funcs()
get_headers()
get_html_translation_table()
get_include_path()
get_included_files()
get_loaded_extensions()
get_magic_quotes_gpc()
get_magic_quotes_runtime()
get_meta_tags()
get_object_vars()
get_parent_class()
get_required_files()
get_resource_type()
getallheaders()
getcwd()
getdate()
getenv()
gethostbyaddr()
gethostbyname()
gethostbynamel()
getimagesize()
getlastmod()
getmxrr()
getmygid()
getmyinode()
getmypid()
getmyuid()
getopt()
getprotobyname()
getprotobynumber()
getrandmax()
getrusage()
getservbyname()
getservbyport()
gettext()
gettimeofday()
gettype()
glob()
gmdate()
gmmktime()
gmp_abs()
gmp_add()
gmp_and()
gmp_clrbit()
gmp_cmp()
gmp_com()
gmp_div()
gmp_div_q()
gmp_div_qr()
gmp_div_r()
gmp_divexact()
gmp_fact()
gmp_gcd()
gmp_gcdext()
gmp_hamdist()
gmp_init()
gmp_intval()
gmp_invert()
gmp_jacobi()
gmp_legendre()
gmp_mod()
gmp_mul()
gmp_neg()
gmp_or()
gmp_perfect_square()
gmp_popcount()
gmp_pow()
gmp_powm()
gmp_prob_prime()
gmp_random()
gmp_scan0()
gmp_scan1()
gmp_setbit()
gmp_sign()
gmp_sqrt()
gmp_sqrtrem()
gmp_strval()
gmp_sub()
gmp_xor()
gmstrftime()
gregoriantojd()
gzclose()
gzcompress()
gzdeflate()
gzencode()
gzeof()
gzfile()
gzgetc()
gzgets()
gzgetss()
gzinflate()
gzopen()
gzpassthru()
gzputs()
gzread()
gzrewind()
gzseek()
gztell()
gzuncompress()
gzwrite()

H

header()
headers_list()
headers_sent()
hebrev()
hebrevc()
hexdec()
highlight_file()
highlight_string()
html_entity_decode()
htmlentities()
htmlspecialchars()
http_build_query()
hw_api->checkin()
hw_api->checkout()
hw_api->children()
hw_api->content()
hw_api->copy()
hw_api->dbstat()
hw_api->dcstat()
hw_api->dstanchors()
hw_api->dstofsrcanchor()
hw_api->find()
hw_api->ftstat()
hw_api->hwstat()
hw_api->identify()
hw_api->info()
hw_api->insert()
hw_api->insertanchor()
hw_api->insertcollection()
hw_api->insertdocument()
hw_api->link()
hw_api->lock()
hw_api->move()
hw_api->object()
hw_api->objectbyanchor()
hw_api->parents()
hw_api->remove()
hw_api->replace()
hw_api->setcommittedversion()
hw_api->srcanchors()
hw_api->srcsofdst()
hw_api->unlock()
hw_api->user()
hw_api->userlist()
hw_api_attribute()
hw_api_attribute->key()
hw_api_attribute->langdepvalue()
hw_api_attribute->value()
hw_api_attribute->values()
hw_api_content()
hw_api_content->mimetype()
hw_api_content->read()
hw_api_error->count()
hw_api_error->reason()
hw_api_object()
hw_api_object->assign()
hw_api_object->attreditable()
hw_api_object->count()
hw_api_object->insert()
hw_api_object->remove()
hw_api_object->title()
hw_api_object->value()
hw_api_reason->description()
hw_api_reason->type()
hw_array2objrec()
hw_changeobject()
hw_children()
hw_childrenobj()
hw_close()
hw_connect()
hw_connection_info()
hw_cp()
hw_deleteobject()
hw_docbyanchor()
hw_docbyanchorobj()
hw_document_attributes()
hw_document_bodytag()
hw_document_content()
hw_document_setcontent()
hw_document_size()
hw_dummy()
hw_edittext()
hw_error()
hw_errormsg()
hw_free_document()
hw_getanchors()
hw_getanchorsobj()
hw_getandlock()
hw_getchildcoll()
hw_getchildcollobj()
hw_getchilddoccoll()
hw_getchilddoccollobj()
hw_getobject()
hw_getobjectbyquery()
hw_getobjectbyquerycoll()
hw_getobjectbyquerycollobj()
hw_getobjectbyqueryobj()
hw_getparents()
hw_getparentsobj()
hw_getrellink()
hw_getremote()
hw_getremotechildren()
hw_getsrcbydestobj()
hw_gettext()
hw_getusername()
hw_identify()
hw_incollections()
hw_info()
hw_inscoll()
hw_insdoc()
hw_insertanchors()
hw_insertdocument()
hw_insertobject()
hw_mapid()
hw_modifyobject()
hw_mv()
hw_new_document()
hw_objrec2array()
hw_output_document()
hw_pconnect()
hw_pipedocument()
hw_root()
hw_setlinkroot()
hw_stat()
hw_unlock()
hw_who()
hwapi_hgcsp()
hypot()

I

ibase_add_user()
ibase_affected_rows()
ibase_backup()
ibase_blob_add()
ibase_blob_cancel()
ibase_blob_close()
ibase_blob_create()
ibase_blob_echo()
ibase_blob_get()
ibase_blob_import()
ibase_blob_info()
ibase_blob_open()
ibase_close()
ibase_commit()
ibase_commit_ret()
ibase_connect()
ibase_db_info()
ibase_delete_user()
ibase_drop_db()
ibase_errcode()
ibase_errmsg()
ibase_execute()
ibase_fetch_assoc()
ibase_fetch_object()
ibase_fetch_row()
ibase_field_info()
ibase_free_event_handler()
ibase_free_query()
ibase_free_result()
ibase_gen_id()
ibase_maintain_db()
ibase_modify_user()
ibase_name_result()
ibase_num_fields()
ibase_num_params()
ibase_param_info()
ibase_pconnect()
ibase_prepare()
ibase_query()
ibase_restore()
ibase_rollback()
ibase_rollback_ret()
ibase_server_info()
ibase_service_attach()
ibase_service_detach()
ibase_set_event_handler()
ibase_timefmt()
ibase_trans()
ibase_wait_event()
iconv()
iconv_get_encoding()
iconv_mime_decode()
iconv_mime_decode_headers()
iconv_mime_encode()
iconv_set_encoding()
iconv_strlen()
iconv_strpos()
iconv_strrpos()
iconv_substr()
id3_get_frame_long_name()
id3_get_frame_short_name()
id3_get_genre_id()
id3_get_genre_list()
id3_get_genre_name()
id3_get_tag()
id3_get_version()
id3_remove_tag()
id3_set_tag()
idate()
ifx_affected_rows()
ifx_blobinfile_mode()
ifx_byteasvarchar()
ifx_close()
ifx_connect()
ifx_copy_blob()
ifx_create_blob()
ifx_create_char()
ifx_do()
ifx_error()
ifx_errormsg()
ifx_fetch_row()
ifx_fieldproperties()
ifx_fieldtypes()
ifx_free_blob()
ifx_free_char()
ifx_free_result()
ifx_get_blob()
ifx_get_char()
ifx_getsqlca()
ifx_htmltbl_result()
ifx_nullformat()
ifx_num_fields()
ifx_num_rows()
ifx_pconnect()
ifx_prepare()
ifx_query()
ifx_textasvarchar()
ifx_update_blob()
ifx_update_char()
ifxus_close_slob()
ifxus_create_slob()
ifxus_free_slob()
ifxus_open_slob()
ifxus_read_slob()
ifxus_seek_slob()
ifxus_tell_slob()
ifxus_write_slob()
ignore_user_abort()
image2wbmp()
image_type_to_extension()
image_type_to_mime_type()
imagealphablending()
imageantialias()
imagearc()
imagechar()
imagecharup()
imagecolorallocate()
imagecolorallocatealpha()
imagecolorat()
imagecolorclosest()
imagecolorclosestalpha()
imagecolorclosesthwb()
imagecolordeallocate()
imagecolorexact()
imagecolorexactalpha()
imagecolormatch()
imagecolorresolve()
imagecolorresolvealpha()
imagecolorset()
imagecolorsforindex()
imagecolorstotal()
imagecolortransparent()
imagecopy()
imagecopymerge()
imagecopymergegray()
imagecopyresampled()
imagecopyresized()
imagecreate()
imagecreatefromgd()
imagecreatefromgd2()
imagecreatefromgd2part()
imagecreatefromgif()
imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromstring()
imagecreatefromwbmp()
imagecreatefromxbm()
imagecreatefromxpm()
imagecreatetruecolor()
imagedashedline()
imagedestroy()
imageellipse()
imagefill()
imagefilledarc()
imagefilledellipse()
imagefilledpolygon()
imagefilledrectangle()
imagefilltoborder()
imagefilter()
imagefontheight()
imagefontwidth()
imageftbbox()
imagefttext()
imagegammacorrect()
imagegd()
imagegd2()
imagegif()
imageinterlace()
imageistruecolor()
imagejpeg()
imagelayereffect()
imageline()
imageloadfont()
imagepalettecopy()
imagepng()
imagepolygon()
imagepsbbox()
imagepscopyfont()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
imagerectangle()
imagerotate()
imagesavealpha()
imagesetbrush()
imagesetpixel()
imagesetstyle()
imagesetthickness()
imagesettile()
imagestring()
imagestringup()
imagesx()
imagesy()
imagetruecolortopalette()
imagettfbbox()
imagettftext()
imagetypes()
imagewbmp()
imagexbm()
imap_8bit()
imap_alerts()
imap_append()
imap_base64()
imap_binary()
imap_body()
imap_bodystruct()
imap_check()
imap_clearflag_full()
imap_close()
imap_createmailbox()
imap_delete()
imap_deletemailbox()
imap_errors()
imap_expunge()
imap_fetch_overview()
imap_fetchbody()
imap_fetchheader()
imap_fetchstructure()
imap_get_quota()
imap_get_quotaroot()
imap_getacl()
imap_getmailboxes()
imap_getsubscribed()
imap_header()
imap_headerinfo()
imap_headers()
imap_last_error()
imap_list()
imap_listmailbox()
imap_listscan()
imap_listsubscribed()
imap_lsub()
imap_mail()
imap_mail_compose()
imap_mail_copy()
imap_mail_move()
imap_mailboxmsginfo()
imap_mime_header_decode()
imap_msgno()
imap_num_msg()
imap_num_recent()
imap_open()
imap_ping()
imap_qprint()
imap_renamemailbox()
imap_reopen()
imap_rfc822_parse_adrlist()
imap_rfc822_parse_headers()
imap_rfc822_write_address()
imap_scanmailbox()
imap_search()
imap_set_quota()
imap_setacl()
imap_setflag_full()
imap_sort()
imap_status()
imap_subscribe()
imap_thread()
imap_timeout()
imap_uid()
imap_undelete()
imap_unsubscribe()
imap_utf7_decode()
imap_utf7_encode()
imap_utf8()
implode()
import_request_variables()
in_array()
inet_ntop()
inet_pton()
ingres_autocommit()
ingres_close()
ingres_commit()
ingres_connect()
ingres_fetch_array()
ingres_fetch_object()
ingres_fetch_row()
ingres_field_length()
ingres_field_name()
ingres_field_nullable()
ingres_field_precision()
ingres_field_scale()
ingres_field_type()
ingres_num_fields()
ingres_num_rows()
ingres_pconnect()
ingres_query()
ingres_rollback()
ini_alter()
ini_get()
ini_get_all()
ini_restore()
ini_set()
interface_exists()
intval()
ip2long()
iptcembed()
iptcparse()
ircg_channel_mode()
ircg_disconnect()
ircg_eval_ecmascript_params()
ircg_fetch_error_msg()
ircg_get_username()
ircg_html_encode()
ircg_ignore_add()
ircg_ignore_del()
ircg_invite()
ircg_is_conn_alive()
ircg_join()
ircg_kick()
ircg_list()
ircg_lookup_format_messages()
ircg_lusers()
ircg_msg()
ircg_names()
ircg_nick()
ircg_nickname_escape()
ircg_nickname_unescape()
ircg_notice()
ircg_oper()
ircg_part()
ircg_pconnect()
ircg_register_format_messages()
ircg_set_current()
ircg_set_file()
ircg_set_on_die()
ircg_topic()
ircg_who()
ircg_whois()
is_a()
is_array()
is_bool()
is_callable()
is_dir()
is_double()
is_executable()
is_file()
is_finite()
is_float()
is_infinite()
is_int()
is_integer()
is_link()
is_long()
is_nan()
is_null()
is_numeric()
is_object()
is_readable()
is_real()
is_resource()
is_scalar()
is_soap_fault()
is_string()
is_subclass_of()
is_uploaded_file()
is_writable()
is_writeable()
isset()
iterator-to-array()
iterator_count()

J

java_last_exception_clear()
java_last_exception_get()
jddayofweek()
jdmonthname()
jdtofrench()
jdtogregorian()
jdtojewish()
jdtojulian()
jdtounix()
jewishtojd()
join()
jpeg2wbmp()
juliantojd()

K

key()
krsort()
ksort()

L

lcg_value()
ldap_8859_to_t61()
ldap_add()
ldap_bind()
ldap_close()
ldap_compare()
ldap_connect()
ldap_count_entries()
ldap_delete()
ldap_dn2ufn()
ldap_err2str()
ldap_errno()
ldap_error()
ldap_explode_dn()
ldap_first_attribute()
ldap_first_entry()
ldap_first_reference()
ldap_free_result()
ldap_get_attributes()
ldap_get_dn()
ldap_get_entries()
ldap_get_option()
ldap_get_values()
ldap_get_values_len()
ldap_list()
ldap_mod_add()
ldap_mod_del()
ldap_mod_replace()
ldap_modify()
ldap_next_attribute()
ldap_next_entry()
ldap_next_reference()
ldap_parse_reference()
ldap_parse_result()
ldap_read()
ldap_rename()
ldap_sasl_bind()
ldap_search()
ldap_set_option()
ldap_set_rebind_proc()
ldap_sort()
ldap_start_tls()
ldap_t61_to_8859()
ldap_unbind()
levenshtein()
LimitIterator::getPosition()
LimitIterator::next()
LimitIterator::rewind()
LimitIterator::seek()
LimitIterator::valid()
link()
linkinfo()
list()
lob->append()
lob->close()
lob->eof()
lob->erase()
lob->export()
lob->flush()
lob->getBuffering()
lob->import()
lob->load()
lob->read()
lob->rewind()
lob->save()
lob->seek()
lob->setBuffering()
lob->size()
lob->tell()
lob->truncate()
lob->write()
lob->writeTemporary()
localeconv()
localtime()
log()
log10()
log1p()
long2ip()
lstat()
ltrim()
lzf_compress()
lzf_decompress()
lzf_optimized_for()

M

mail()
mailparse_determine_best_xfer_encoding()
mailparse_msg_create()
mailparse_msg_extract_part()
mailparse_msg_extract_part_file()
mailparse_msg_free()
mailparse_msg_get_part()
mailparse_msg_get_part_data()
mailparse_msg_get_structure()
mailparse_msg_parse()
mailparse_msg_parse_file()
mailparse_rfc822_parse_addresses()
mailparse_stream_encode()
mailparse_uudecode_all()
main()
max()
mb_convert_case()
mb_convert_encoding()
mb_convert_kana()
mb_convert_variables()
mb_decode_mimeheader()
mb_decode_numericentity()
mb_detect_encoding()
mb_detect_order()
mb_encode_mimeheader()
mb_encode_numericentity()
mb_ereg()
mb_ereg_match()
mb_ereg_replace()
mb_ereg_search()
mb_ereg_search_getpos()
mb_ereg_search_getregs()
mb_ereg_search_init()
mb_ereg_search_pos()
mb_ereg_search_regs()
mb_ereg_search_setpos()
mb_eregi()
mb_eregi_replace()
mb_get_info()
mb_http_input()
mb_http_output()
mb_internal_encoding()
mb_language()
mb_list_encodings()
mb_output_handler()
mb_parse_str()
mb_preferred_mime_name()
mb_regex_encoding()
mb_regex_set_options()
mb_send_mail()
mb_split()
mb_strcut()
mb_strimwidth()
mb_strlen()
mb_strpos()
mb_strrpos()
mb_strtolower()
mb_strtoupper()
mb_strwidth()
mb_substitute_character()
mb_substr()
mb_substr_count()
mcal_append_event()
mcal_close()
mcal_create_calendar()
mcal_date_compare()
mcal_date_valid()
mcal_day_of_week()
mcal_day_of_year()
mcal_days_in_month()
mcal_delete_calendar()
mcal_delete_event()
mcal_event_add_attribute()
mcal_event_init()
mcal_event_set_alarm()
mcal_event_set_category()
mcal_event_set_class()
mcal_event_set_description()
mcal_event_set_end()
mcal_event_set_recur_daily()
mcal_event_set_recur_monthly_mday()
mcal_event_set_recur_monthly_wday()
mcal_event_set_recur_none()
mcal_event_set_recur_weekly()
mcal_event_set_recur_yearly()
mcal_event_set_start()
mcal_event_set_title()
mcal_expunge()
mcal_fetch_current_stream_event()
mcal_fetch_event()
mcal_is_leap_year()
mcal_list_alarms()
mcal_list_events()
mcal_next_recurrence()
mcal_open()
mcal_popen()
mcal_rename_calendar()
mcal_reopen()
mcal_snooze()
mcal_store_event()
mcal_time_valid()
mcal_week_of_year()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_create_iv()
mcrypt_decrypt()
mcrypt_ecb()
mcrypt_enc_get_algorithms_name()
mcrypt_enc_get_block_size()
mcrypt_enc_get_iv_size()
mcrypt_enc_get_key_size()
mcrypt_enc_get_modes_name()
mcrypt_enc_get_supported_key_sizes()
mcrypt_enc_is_block_algorithm()
mcrypt_enc_is_block_algorithm_mode()
mcrypt_enc_is_block_mode()
mcrypt_enc_self_test()
mcrypt_encrypt()
mcrypt_generic()
mcrypt_generic_deinit()
mcrypt_generic_end()
mcrypt_generic_init()
mcrypt_get_block_size()
mcrypt_get_cipher_name()
mcrypt_get_iv_size()
mcrypt_get_key_size()
mcrypt_list_algorithms()
mcrypt_list_modes()
mcrypt_module_close()
mcrypt_module_get_algo_block_size()
mcrypt_module_get_algo_key_size()
mcrypt_module_get_supported_key_sizes()
mcrypt_module_is_block_algorithm()
mcrypt_module_is_block_algorithm_mode()
mcrypt_module_is_block_mode()
mcrypt_module_open()
mcrypt_module_self_test()
mcrypt_ofb()
mcve_adduser()
mcve_adduserarg()
mcve_bt()
mcve_checkstatus()
mcve_chkpwd()
mcve_chngpwd()
mcve_completeauthorizations()
mcve_connect()
mcve_connectionerror()
mcve_deleteresponse()
mcve_deletetrans()
mcve_deleteusersetup()
mcve_deluser()
mcve_destroyconn()
mcve_destroyengine()
mcve_disableuser()
mcve_edituser()
mcve_enableuser()
mcve_force()
mcve_getcell()
mcve_getcellbynum()
mcve_getcommadelimited()
mcve_getheader()
mcve_getuserarg()
mcve_getuserparam()
mcve_gft()
mcve_gl()
mcve_gut()
mcve_initconn()
mcve_initengine()
mcve_initusersetup()
mcve_iscommadelimited()
mcve_liststats()
mcve_listusers()
mcve_maxconntimeout()
mcve_monitor()
mcve_numcolumns()
mcve_numrows()
mcve_override()
mcve_parsecommadelimited()
mcve_ping()
mcve_preauth()
mcve_preauthcompletion()
mcve_qc()
mcve_responseparam()
mcve_return()
mcve_returncode()
mcve_returnstatus()
mcve_sale()
mcve_setblocking()
mcve_setdropfile()
mcve_setip()
mcve_setssl()
mcve_setssl_files()
mcve_settimeout()
mcve_settle()
mcve_text_avs()
mcve_text_code()
mcve_text_cv()
mcve_transactionauth()
mcve_transactionavs()
mcve_transactionbatch()
mcve_transactioncv()
mcve_transactionid()
mcve_transactionitem()
mcve_transactionssent()
mcve_transactiontext()
mcve_transinqueue()
mcve_transnew()
mcve_transparam()
mcve_transsend()
mcve_ub()
mcve_uwait()
mcve_verifyconnection()
mcve_verifysslcert()
mcve_void()
md5()
md5_file()
mdecrypt_generic()
Memcache::add()
Memcache::close()
Memcache::connect()
Memcache::decrement()
Memcache::delete()
Memcache::flush()
Memcache::get()
Memcache::getStats()
Memcache::getVersion()
Memcache::increment()
Memcache::pconnect()
Memcache::replace()
Memcache::set()
memcache_debug()
memory_get_usage()
metaphone()
method_exists()
mhash()
mhash_count()
mhash_get_block_size()
mhash_get_hash_name()
mhash_keygen_s2k()
microtime()
mime_content_type()
min()
ming_setcubicthreshold()
ming_setscale()
ming_useswfversion()
mkdir()
mktime()
money_format()
move_uploaded_file()
msession_connect()
msession_count()
msession_create()
msession_destroy()
msession_disconnect()
msession_find()
msession_get()
msession_get_array()
msession_get_data()
msession_inc()
msession_list()
msession_listvar()
msession_lock()
msession_plugin()
msession_randstr()
msession_set()
msession_set_array()
msession_set_data()
msession_timeout()
msession_uniq()
msession_unlock()
msg_get_queue()
msg_receive()
msg_remove_queue()
msg_send()
msg_set_queue()
msg_stat_queue()
msql()
msql_affected_rows()
msql_close()
msql_connect()
msql_create_db()
msql_createdb()
msql_data_seek()
msql_db_query()
msql_dbname()
msql_drop_db()
msql_error()
msql_fetch_array()
msql_fetch_field()
msql_fetch_object()
msql_fetch_row()
msql_field_flags()
msql_field_len()
msql_field_name()
msql_field_seek()
msql_field_table()
msql_field_type()
msql_fieldflags()
msql_fieldlen()
msql_fieldname()
msql_fieldtable()
msql_fieldtype()
msql_free_result()
msql_list_dbs()
msql_list_fields()
msql_list_tables()
msql_num_fields()
msql_num_rows()
msql_numfields()
msql_numrows()
msql_pconnect()
msql_query()
msql_regcase()
msql_result()
msql_select_db()
msql_tablename()
mssql_bind()
mssql_close()
mssql_connect()
mssql_data_seek()
mssql_execute()
mssql_fetch_array()
mssql_fetch_assoc()
mssql_fetch_batch()
mssql_fetch_field()
mssql_fetch_object()
mssql_fetch_row()
mssql_field_length()
mssql_field_name()
mssql_field_seek()
mssql_field_type()
mssql_free_result()
mssql_free_statement()
mssql_get_last_message()
mssql_guid_string()
mssql_init()
mssql_min_error_severity()
mssql_min_message_severity()
mssql_next_result()
mssql_num_fields()
mssql_num_rows()
mssql_pconnect()
mssql_query()
mssql_result()
mssql_rows_affected()
mssql_select_db()
mt_getrandmax()
mt_rand()
mt_srand()
muscat_close()
muscat_get()
muscat_give()
muscat_setup()
muscat_setup_net()
mysql_affected_rows()
mysql_change_user()
mysql_client_encoding()
mysql_close()
mysql_connect()
mysql_create_db()
mysql_data_seek()
mysql_db_name()
mysql_db_query()
mysql_drop_db()
mysql_errno()
mysql_error()
mysql_escape_string()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_field()
mysql_fetch_lengths()
mysql_fetch_object()
mysql_fetch_row()
mysql_field_flags()
mysql_field_len()
mysql_field_name()
mysql_field_seek()
mysql_field_table()
mysql_field_type()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_insert_id()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_pconnect()
mysql_ping()
mysql_query()
mysql_real_escape_string()
mysql_result()
mysql_select_db()
mysql_stat()
mysql_tablename()
mysql_thread_id()
mysql_unbuffered_query()
mysqli()()
mysqli->affected_rows()
mysqli->autocommit()
mysqli->change_user()
mysqli->character_set_name()
mysqli->close()
mysqli->commit()
mysqli->disable_reads_from_master()
mysqli->dump_debug_info()
mysqli->errno()
mysqli->fetch_assoc()
mysqli->field_count()
mysqli->get_host_info()
mysqli->info()
mysqli->insert_id()
mysqli->kill()
mysqli->more_results()
mysqli->multi_query()
mysqli->next_result()
mysqli->options()
mysqli->ping()
mysqli->prepare()
mysqli->protocol_version()
mysqli->query()
mysqli->real_connect()
mysqli->real_escape_string()
mysqli->real_query()
mysqli->rollback()
mysqli->rpl_query_type()
mysqli->select_db()
mysqli->send_query()
mysqli->server_info()
mysqli->sqlstate()
mysqli->ssl_set()
mysqli->stat()
mysqli->stmt_init()
mysqli->store_result()
mysqli->thread_id()
mysqli->use_result()
mysqli->warning_count()
mysqli_affected_rows()
mysqli_autocommit()
mysqli_bind_param()
mysqli_bind_result()
mysqli_change_user()
mysqli_character_set_name()
mysqli_client_encoding()
mysqli_close()
mysqli_commit()
mysqli_connect()
mysqli_connect_errno()
mysqli_connect_error()
mysqli_data_seek()
mysqli_debug()
mysqli_disable_reads_from_master()
mysqli_disable_rpl_parse()
mysqli_dump_debug_info()
mysqli_embedded_connect()
mysqli_enable_reads_from_master()
mysqli_enable_rpl_parse()
mysqli_errno()
mysqli_error()
mysqli_escape_string()
mysqli_execute()
mysqli_fetch()
mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_field()
mysqli_fetch_field_direct()
mysqli_fetch_fields()
mysqli_fetch_lengths()
mysqli_fetch_object()
mysqli_fetch_row()
mysqli_field_count()
mysqli_field_seek()
mysqli_field_tell()
mysqli_free_result()
mysqli_get_client_info()
mysqli_get_client_version()
mysqli_get_host_info()
mysqli_get_metadata()
mysqli_get_proto_info()
mysqli_get_server_info()
mysqli_get_server_version()
mysqli_info()
mysqli_init()
mysqli_insert_id()
mysqli_kill()
mysqli_master_query()
mysqli_more_results()
mysqli_multi_query()
mysqli_next_result()
mysqli_num_fields()
mysqli_num_rows()
mysqli_options()
mysqli_param_count()
mysqli_ping()
mysqli_prepare()
mysqli_query()
mysqli_real_connect()
mysqli_real_escape_string()
mysqli_real_query()
mysqli_report()
mysqli_rollback()
mysqli_rpl_parse_enabled()
mysqli_rpl_probe()
mysqli_rpl_query_type()
mysqli_select_db()
mysqli_send_long_data()
mysqli_send_query()
mysqli_server_end()
mysqli_server_init()
mysqli_set_opt()
mysqli_sqlstate()
mysqli_ssl_set()
mysqli_stat()
mysqli_stmt->affected_rows()
mysqli_stmt->close()
mysqli_stmt->errno()
mysqli_stmt->error()
mysqli_stmt->store_result()
mysqli_stmt_affected_rows()
mysqli_stmt_bind_param()
mysqli_stmt_bind_result()
mysqli_stmt_close()
mysqli_stmt_data_seek()
mysqli_stmt_errno()
mysqli_stmt_error()
mysqli_stmt_execute()
mysqli_stmt_fetch()
mysqli_stmt_free_result()
mysqli_stmt_init()
mysqli_stmt_num_rows()
mysqli_stmt_param_count()
mysqli_stmt_prepare()
mysqli_stmt_reset()
mysqli_stmt_result_metadata()
mysqli_stmt_send_long_data()
mysqli_stmt_sqlstate()
mysqli_stmt_store_result()
mysqli_store_result()
mysqli_thread_id()
mysqli_thread_safe()
mysqli_use_result()
mysqli_warning_count()

N

natcasesort()
natsort()
ncurses_addch()
ncurses_addchnstr()
ncurses_addchstr()
ncurses_addnstr()
ncurses_addstr()
ncurses_assume_default_colors()
ncurses_attroff()
ncurses_attron()
ncurses_attrset()
ncurses_baudrate()
ncurses_beep()
ncurses_bkgd()
ncurses_bkgdset()
ncurses_border()
ncurses_bottom_panel()
ncurses_can_change_color()
ncurses_cbreak()
ncurses_clear()
ncurses_clrtobot()
ncurses_clrtoeol()
ncurses_color_content()
ncurses_color_set()
ncurses_curs_set()
ncurses_def_prog_mode()
ncurses_def_shell_mode()
ncurses_define_key()
ncurses_del_panel()
ncurses_delay_output()
ncurses_delch()
ncurses_deleteln()
ncurses_delwin()
ncurses_doupdate()
ncurses_echo()
ncurses_echochar()
ncurses_end()
ncurses_erase()
ncurses_erasechar()
ncurses_filter()
ncurses_flash()
ncurses_flushinp()
ncurses_getch()
ncurses_getmaxyx()
ncurses_getmouse()
ncurses_getyx()
ncurses_halfdelay()
ncurses_has_colors()
ncurses_has_ic()
ncurses_has_il()
ncurses_has_key()
ncurses_hide_panel()
ncurses_hline()
ncurses_inch()
ncurses_init()
ncurses_init_color()
ncurses_init_pair()
ncurses_insch()
ncurses_insdelln()
ncurses_insertln()
ncurses_insstr()
ncurses_instr()
ncurses_isendwin()
ncurses_keyok()
ncurses_keypad()
ncurses_killchar()
ncurses_longname()
ncurses_meta()
ncurses_mouse_trafo()
ncurses_mouseinterval()
ncurses_mousemask()
ncurses_move()
ncurses_move_panel()
ncurses_mvaddch()
ncurses_mvaddchnstr()
ncurses_mvaddchstr()
ncurses_mvaddnstr()
ncurses_mvaddstr()
ncurses_mvcur()
ncurses_mvdelch()
ncurses_mvgetch()
ncurses_mvhline()
ncurses_mvinch()
ncurses_mvvline()
ncurses_mvwaddstr()
ncurses_napms()
ncurses_new_panel()
ncurses_newpad()
ncurses_newwin()
ncurses_nl()
ncurses_nocbreak()
ncurses_noecho()
ncurses_nonl()
ncurses_noqiflush()
ncurses_noraw()
ncurses_pair_content()
ncurses_panel_above()
ncurses_panel_below()
ncurses_panel_window()
ncurses_pnoutrefresh()
ncurses_prefresh()
ncurses_putp()
ncurses_qiflush()
ncurses_raw()
ncurses_refresh()
ncurses_replace_panel()
ncurses_reset_prog_mode()
ncurses_reset_shell_mode()
ncurses_resetty()
ncurses_savetty()
ncurses_scr_dump()
ncurses_scr_init()
ncurses_scr_restore()
ncurses_scr_set()
ncurses_scrl()
ncurses_show_panel()
ncurses_slk_attr()
ncurses_slk_attroff()
ncurses_slk_attron()
ncurses_slk_attrset()
ncurses_slk_clear()
ncurses_slk_color()
ncurses_slk_init()
ncurses_slk_noutrefresh()
ncurses_slk_refresh()
ncurses_slk_restore()
ncurses_slk_set()
ncurses_slk_touch()
ncurses_standend()
ncurses_standout()
ncurses_start_color()
ncurses_termattrs()
ncurses_termname()
ncurses_timeout()
ncurses_top_panel()
ncurses_typeahead()
ncurses_ungetch()
ncurses_ungetmouse()
ncurses_update_panels()
ncurses_use_default_colors()
ncurses_use_env()
ncurses_use_extended_names()
ncurses_vidattr()
ncurses_vline()
ncurses_waddch()
ncurses_waddstr()
ncurses_wattroff()
ncurses_wattron()
ncurses_wattrset()
ncurses_wborder()
ncurses_wclear()
ncurses_wcolor_set()
ncurses_werase()
ncurses_wgetch()
ncurses_whline()
ncurses_wmouse_trafo()
ncurses_wmove()
ncurses_wnoutrefresh()
ncurses_wrefresh()
ncurses_wstandend()
ncurses_wstandout()
ncurses_wvline()
next()
ngettext()
nl2br()
nl_langinfo()
notes_body()
notes_copy_db()
notes_create_db()
notes_create_note()
notes_drop_db()
notes_find_note()
notes_header_info()
notes_list_msgs()
notes_mark_read()
notes_mark_unread()
notes_nav_create()
notes_search()
notes_unread()
notes_version()
nsapi_request_headers()
nsapi_response_headers()
nsapi_virtual()
number_format()

O

ob_clean()
ob_end_clean()
ob_end_flush()
ob_flush()
ob_get_clean()
ob_get_contents()
ob_get_flush()
ob_get_length()
ob_get_level()
ob_get_status()
ob_gzhandler()
ob_iconv_handler()
ob_implicit_flush()
ob_list_handlers()
ob_start()
ob_tidyhandler()
OCI-Collection->append()
OCI-Collection->assign()
OCI-Collection->assignElem()
OCI-Collection->free()
OCI-Collection->getElem()
OCI-Collection->max()
OCI-Collection->size()
OCI-Collection->trim()
oci_bind_by_name()
oci_cancel()
oci_close()
oci_commit()
oci_connect()
oci_define_by_name()
oci_error()
oci_execute()
oci_fetch()
oci_fetch_all()
oci_fetch_array()
oci_fetch_assoc()
oci_fetch_object()
oci_fetch_row()
oci_field_is_null()
oci_field_name()
oci_field_precision()
oci_field_scale()
oci_field_size()
oci_field_type()
oci_field_type_raw()
oci_free_statement()
oci_internal_debug()
oci_lob_copy()
oci_lob_is_equal()
oci_new_collection()
oci_new_connect()
oci_new_cursor()
oci_new_descriptor()
oci_num_fields()
oci_num_rows()
oci_parse()
oci_password_change()
oci_pconnect()
oci_result()
oci_rollback()
oci_server_version()
oci_set_prefetch()
oci_statement_type()
ocibindbyname()
ocicancel()
ocicloselob()
ocicollappend()
ocicollassign()
ocicollassignelem()
ocicollgetelem()
ocicollmax()
ocicollsize()
ocicolltrim()
ocicolumnisnull()
ocicolumnname()
ocicolumnprecision()
ocicolumnscale()
ocicolumnsize()
ocicolumntype()
ocicolumntyperaw()
ocicommit()
ocidefinebyname()
ocierror()
ociexecute()
ocifetch()
ocifetchinto()
ocifetchstatement()
ocifreecollection()
ocifreecursor()
ocifreedesc()
ocifreestatement()
ociinternaldebug()
ociloadlob()
ocilogoff()
ocilogon()
ocinewcollection()
ocinewcursor()
ocinewdescriptor()
ocinlogon()
ocinumcols()
ociparse()
ociplogon()
ociresult()
ocirollback()
ocirowcount()
ocisavelob()
ocisavelobfile()
ociserverversion()
ocisetprefetch()
ocistatementtype()
ociwritelobtofile()
ociwritetemporarylob()
octdec()
odbc_autocommit()
odbc_binmode()
odbc_close()
odbc_close_all()
odbc_columnprivileges()
odbc_columns()
odbc_commit()
odbc_connect()
odbc_cursor()
odbc_data_source()
odbc_do()
odbc_error()
odbc_errormsg()
odbc_exec()
odbc_execute()
odbc_fetch_array()
odbc_fetch_into()
odbc_fetch_object()
odbc_fetch_row()
odbc_field_len()
odbc_field_name()
odbc_field_num()
odbc_field_precision()
odbc_field_scale()
odbc_field_type()
odbc_foreignkeys()
odbc_free_result()
odbc_gettypeinfo()
odbc_longreadlen()
odbc_next_result()
odbc_num_fields()
odbc_num_rows()
odbc_pconnect()
odbc_prepare()
odbc_primarykeys()
odbc_procedurecolumns()
odbc_procedures()
odbc_result()
odbc_result_all()
odbc_rollback()
odbc_setoption()
odbc_specialcolumns()
odbc_statistics()
odbc_tableprivileges()
odbc_tables()
openal_buffer_create()
openal_buffer_data()
openal_buffer_destroy()
openal_buffer_get()
openal_buffer_loadwav()
openal_context_create()
openal_context_current()
openal_context_destroy()
openal_context_process()
openal_context_suspend()
openal_device_close()
openal_device_open()
openal_listener_get()
openal_listener_set()
openal_source_create()
openal_source_destroy()
openal_source_get()
openal_source_pause()
openal_source_play()
openal_source_rewind()
openal_source_set()
openal_source_stop()
openal_stream()
opendir()
openlog()
openssl_csr_export()
openssl_csr_export_to_file()
openssl_csr_new()
openssl_csr_sign()
openssl_error_string()
openssl_free_key()
openssl_get_privatekey()
openssl_get_publickey()
openssl_open()
openssl_pkcs7_decrypt()
openssl_pkcs7_encrypt()
openssl_pkcs7_sign()
openssl_pkcs7_verify()
openssl_pkey_export()
openssl_pkey_export_to_file()
openssl_pkey_get_private()
openssl_pkey_get_public()
openssl_pkey_new()
openssl_private_decrypt()
openssl_private_encrypt()
openssl_public_decrypt()
openssl_public_encrypt()
openssl_seal()
openssl_sign()
openssl_verify()
openssl_x509_check_private_key()
openssl_x509_checkpurpose()
openssl_x509_export()
openssl_x509_export_to_file()
openssl_x509_free()
openssl_x509_parse()
openssl_x509_read()
ora_bind()
ora_close()
ora_columnname()
ora_columnsize()
ora_columntype()
ora_commit()
ora_commitoff()
ora_commiton()
ora_do()
ora_error()
ora_errorcode()
ora_exec()
ora_fetch()
ora_fetch_into()
ora_getcolumn()
ora_logoff()
ora_logon()
ora_numcols()
ora_numrows()
ora_open()
ora_parse()
ora_plogon()
ora_rollback()
ord()
output_add_rewrite_var()
output_reset_rewrite_vars()
overload()
override_function()
ovrimos_close()
ovrimos_commit()
ovrimos_connect()
ovrimos_cursor()
ovrimos_exec()
ovrimos_execute()
ovrimos_fetch_into()
ovrimos_fetch_row()
ovrimos_field_len()
ovrimos_field_name()
ovrimos_field_num()
ovrimos_field_type()
ovrimos_free_result()
ovrimos_longreadlen()
ovrimos_num_fields()
ovrimos_num_rows()
ovrimos_prepare()
ovrimos_result()
ovrimos_result_all()
ovrimos_rollback()

P

pack()
ParentIterator::getChildren()
ParentIterator::hasChildren()
ParentIterator::next()
ParentIterator::rewind()
parse_ini_file()
parse_str()
parse_url()
parsekit_compile_file()
parsekit_compile_string()
parsekit_func_arginfo()
passthru()
pathinfo()
pclose()
pcntl_alarm()
pcntl_exec()
pcntl_fork()
pcntl_getpriority()
pcntl_setpriority()
pcntl_signal()
pcntl_wait()
pcntl_waitpid()
pcntl_wexitstatus()
pcntl_wifexited()
pcntl_wifsignaled()
pcntl_wifstopped()
pcntl_wstopsig()
pcntl_wtermsig()
pdf_add_annotation()
pdf_add_bookmark()
pdf_add_launchlink()
pdf_add_locallink()
pdf_add_note()
pdf_add_outline()
pdf_add_pdflink()
pdf_add_thumbnail()
pdf_add_weblink()
pdf_arc()
pdf_arcn()
pdf_attach_file()
pdf_begin_page()
pdf_begin_pattern()
pdf_begin_template()
pdf_circle()
pdf_clip()
pdf_close()
pdf_close_image()
pdf_close_pdi()
pdf_close_pdi_page()
pdf_closepath()
pdf_closepath_fill_stroke()
pdf_closepath_stroke()
pdf_concat()
pdf_continue_text()
pdf_curveto()
pdf_delete()
pdf_end_page()
pdf_end_pattern()
pdf_end_template()
pdf_endpath()
pdf_fill()
pdf_fill_stroke()
pdf_findfont()
pdf_get_buffer()
pdf_get_font()
pdf_get_fontname()
pdf_get_fontsize()
pdf_get_image_height()
pdf_get_image_width()
pdf_get_majorversion()
pdf_get_minorversion()
pdf_get_parameter()
pdf_get_pdi_parameter()
pdf_get_pdi_value()
pdf_get_value()
pdf_initgraphics()
pdf_lineto()
pdf_makespotcolor()
pdf_moveto()
pdf_new()
pdf_open()
pdf_open_ccitt()
pdf_open_file()
pdf_open_gif()
pdf_open_image()
pdf_open_image_file()
pdf_open_jpeg()
pdf_open_memory_image()
pdf_open_pdi()
pdf_open_pdi_page()
pdf_open_png()
pdf_open_tiff()
pdf_place_image()
pdf_place_pdi_page()
pdf_rect()
pdf_restore()
pdf_rotate()
pdf_save()
pdf_scale()
pdf_set_border_color()
pdf_set_border_dash()
pdf_set_border_style()
pdf_set_char_spacing()
pdf_set_duration()
pdf_set_font()
pdf_set_horiz_scaling()
pdf_set_info()
pdf_set_info_author()
pdf_set_info_creator()
pdf_set_info_keywords()
pdf_set_info_subject()
pdf_set_info_title()
pdf_set_leading()
pdf_set_parameter()
pdf_set_text_matrix()
pdf_set_text_pos()
pdf_set_text_rendering()
pdf_set_text_rise()
pdf_set_value()
pdf_set_word_spacing()
pdf_setcolor()
pdf_setdash()
pdf_setflat()
pdf_setfont()
pdf_setgray()
pdf_setgray_fill()
pdf_setgray_stroke()
pdf_setlinecap()
pdf_setlinejoin()
pdf_setlinewidth()
pdf_setmatrix()
pdf_setmiterlimit()
pdf_setpolydash()
pdf_setrgbcolor()
pdf_setrgbcolor_fill()
pdf_setrgbcolor_stroke()
pdf_show()
pdf_show_boxed()
pdf_show_xy()
pdf_skew()
pdf_stringwidth()
pdf_stroke()
pdf_translate()
PDO::__construct()
PDO::beginTransaction()
PDO::commit()
PDO::errorCode()
PDO::errorInfo()
PDO::exec()
PDO::lastInsertId()
PDO::prepare()
PDO::rollBack()
PDO::setAttribute()
PDOStatement::bindColumn()
PDOStatement::bindParam()
PDOStatement::errorCode()
PDOStatement::errorInfo()
PDOStatement::execute()
PDOStatement::fetch()
PDOStatement::fetchAll()
PDOStatement::fetchSingle()
PDOStatement::rowCount()
pfpro_cleanup()
pfpro_init()
pfpro_process()
pfpro_process_raw()
pfpro_version()
pfsockopen()
pg_affected_rows()
pg_cancel_query()
pg_client_encoding()
pg_close()
pg_connect()
pg_connection_busy()
pg_connection_reset()
pg_connection_status()
pg_convert()
pg_copy_from()
pg_copy_to()
pg_dbname()
pg_delete()
pg_end_copy()
pg_escape_bytea()
pg_escape_string()
pg_fetch_all()
pg_fetch_array()
pg_fetch_assoc()
pg_fetch_object()
pg_fetch_result()
pg_fetch_row()
pg_field_is_null()
pg_field_name()
pg_field_num()
pg_field_prtlen()
pg_field_size()
pg_field_type()
pg_free_result()
pg_get_notify()
pg_get_pid()
pg_get_result()
pg_host()
pg_insert()
pg_last_error()
pg_last_notice()
pg_last_oid()
pg_lo_close()
pg_lo_create()
pg_lo_export()
pg_lo_import()
pg_lo_open()
pg_lo_read()
pg_lo_read_all()
pg_lo_seek()
pg_lo_tell()
pg_lo_unlink()
pg_lo_write()
pg_meta_data()
pg_num_fields()
pg_num_rows()
pg_options()
pg_parameter_status()
pg_pconnect()
pg_ping()
pg_port()
pg_put_line()
pg_query()
pg_result_error()
pg_result_seek()
pg_result_status()
pg_select()
pg_send_query()
pg_set_client_encoding()
pg_trace()
pg_tty()
pg_unescape_bytea()
pg_untrace()
pg_update()
pg_version()
php_check_syntax()
php_ini_scanned_files()
php_logo_guid()
php_register_url_stream_wrapper()
php_sapi_name()
php_stream_can_cast()
php_stream_cast()
php_stream_close()
php_stream_closedir()
php_stream_copy_to_mem()
php_stream_copy_to_stream()
php_stream_eof()
php_stream_filter_register_factory()
php_stream_filter_unregister_factory()
php_stream_flush()
php_stream_fopen_from_file()
php_stream_fopen_temporary_file()
php_stream_fopen_tmpfile()
php_stream_getc()
php_stream_gets()
php_stream_is()
php_stream_is_persistent()
php_stream_make_seekable()
php_stream_open_wrapper()
php_stream_open_wrapper_as_file()
php_stream_open_wrapper_ex()
php_stream_opendir()
php_stream_passthru()
php_stream_read()
php_stream_readdir()
php_stream_rewinddir()
php_stream_seek()
php_stream_sock_open_from_socket()
php_stream_sock_open_host()
php_stream_sock_open_unix()
php_stream_stat()
php_stream_stat_path()
php_stream_tell()
php_stream_write()
php_strip_whitespace()
php_uname()
php_unregister_url_stream_wrapper()
phpcredits()
phpinfo()
phpversion()
pi()
png2wbmp()
popen()
pos()
posix_ctermid()
posix_get_last_error()
posix_getcwd()
posix_getegid()
posix_geteuid()
posix_getgid()
posix_getgrgid()
posix_getgrnam()
posix_getgroups()
posix_getlogin()
posix_getpgid()
posix_getpgrp()
posix_getpid()
posix_getppid()
posix_getpwnam()
posix_getpwuid()
posix_getrlimit()
posix_getsid()
posix_getuid()
posix_isatty()
posix_kill()
posix_mkfifo()
posix_setegid()
posix_seteuid()
posix_setgid()
posix_setpgid()
posix_setsid()
posix_setuid()
posix_strerror()
posix_times()
posix_ttyname()
posix_uname()
pow()
preg_grep()
preg_match()
preg_match_all()
preg_quote()
preg_replace()
preg_replace_callback()
preg_split()
prev()
print()
print_r()
printer_abort()
printer_close()
printer_create_brush()
printer_create_dc()
printer_create_font()
printer_create_pen()
printer_delete_brush()
printer_delete_dc()
printer_delete_font()
printer_delete_pen()
printer_draw_bmp()
printer_draw_chord()
printer_draw_elipse()
printer_draw_line()
printer_draw_pie()
printer_draw_rectangle()
printer_draw_roundrect()
printer_draw_text()
printer_end_doc()
printer_end_page()
printer_get_option()
printer_list()
printer_logical_fontheight()
printer_open()
printer_select_brush()
printer_select_font()
printer_select_pen()
printer_set_option()
printer_start_doc()
printer_start_page()
printer_write()
printf()
proc_close()
proc_get_status()
proc_nice()
proc_open()
proc_terminate()
pspell_add_to_personal()
pspell_add_to_session()
pspell_check()
pspell_clear_session()
pspell_config_create()
pspell_config_data_dir()
pspell_config_dict_dir()
pspell_config_ignore()
pspell_config_mode()
pspell_config_personal()
pspell_config_repl()
pspell_config_runtogether()
pspell_config_save_repl()
pspell_new()
pspell_new_config()
pspell_new_personal()
pspell_save_wordlist()
pspell_store_replacement()
pspell_suggest()
putenv()

Q

qdom_error()
qdom_tree()
quoted_printable_decode()
quotemeta()

R

rad2deg()
rand()
range()
Rar::extract()
Rar::getAttr()
Rar::getCrc()
Rar::getFileTime()
Rar::getHostOs()
Rar::getMethod()
Rar::getName()
Rar::getPackedSize()
Rar::getUnpackedSize()
Rar::getVersion()
rar_close()
rar_entry_get()
rar_list()
rar_open()
rawurldecode()
rawurlencode()
read_exif_data()
readdir()
readfile()
readgzfile()
readline()
readline_add_history()
readline_callback_handler_install()
readline_callback_handler_remove()
readline_callback_read_char()
readline_clear_history()
readline_completion_function()
readline_info()
readline_list_history()
readline_on_new_line()
readline_read_history()
readline_redisplay()
readline_write_history()
readlink()
realpath()
recode()
recode_file()
recode_string()
RecursiveDirectoryIterator::getChildren()
RecursiveDirectoryIterator::hasChildren()
RecursiveDirectoryIterator::key()
RecursiveDirectoryIterator::next()
RecursiveDirectoryIterator::rewind()
RecursiveIteratorIterator::current()
RecursiveIteratorIterator::getDepth()
RecursiveIteratorIterator::getSubIterator()
RecursiveIteratorIterator::key()
RecursiveIteratorIterator::next()
RecursiveIteratorIterator::rewind()
RecursiveIteratorIterator::valid()
register_shutdown_function()
register_tick_function()
rename()
rename_function()
reset()
restore_error_handler()
restore_exception_handler()
restore_include_path()
result->current_field()
result->data_seek()
result->fetch_array()
result->fetch_field()
result->fetch_field_direct()
result->fetch_fields()
result->fetch_object()
result->fetch_row()
result->field_count()
result->field_seek()
result->free()
result->lengths()
rewind()
rewinddir()
rmdir()
round()
rsort()
rtrim()

S

scandir()
sem_acquire()
sem_get()
sem_release()
sem_remove()
serialize()
sesam_affected_rows()
sesam_commit()
sesam_connect()
sesam_diagnostic()
sesam_disconnect()
sesam_errormsg()
sesam_execimm()
sesam_fetch_array()
sesam_fetch_result()
sesam_fetch_row()
sesam_field_array()
sesam_field_name()
sesam_free_result()
sesam_num_fields()
sesam_query()
sesam_rollback()
sesam_seek_row()
sesam_settransaction()
session_cache_expire()
session_cache_limiter()
session_commit()
session_decode()
session_destroy()
session_encode()
session_get_cookie_params()
session_id()
session_is_registered()
session_module_name()
session_name()
session_regenerate_id()
session_register()
session_save_path()
session_set_cookie_params()
session_set_save_handler()
session_start()
session_unregister()
session_unset()
session_write_close()
set_error_handler()
set_exception_handler()
set_file_buffer()
set_include_path()
set_magic_quotes_runtime()
set_time_limit()
setcookie()
setlocale()
setrawcookie()
settype()
sha1()
sha1_file()
shell_exec()
shm_attach()
shm_detach()
shm_get_var()
shm_put_var()
shm_remove()
shm_remove_var()
shmop_close()
shmop_delete()
shmop_open()
shmop_read()
shmop_size()
shmop_write()
show_source()
shuffle()
similar_text()
simplexml_import_dom()
simplexml_load_file()
simplexml_load_string()
SimpleXMLElement->asXML()
SimpleXMLElement->attributes()
SimpleXMLElement->children()
SimpleXMLElement->xpath()
SimpleXMLIterator::current()
SimpleXMLIterator::getChildren()
SimpleXMLIterator::hasChildren()
SimpleXMLIterator::key()
SimpleXMLIterator::next()
SimpleXMLIterator::rewind()
SimpleXMLIterator::valid()
sin()
sinh()
sizeof()
sleep()
snmp_get_quick_print()
snmp_get_valueretrieval()
snmp_read_mib()
snmp_set_enum_print()
snmp_set_oid_numeric_print()
snmp_set_quick_print()
snmp_set_valueretrieval()
snmpget()
snmpgetnext()
snmprealwalk()
snmpset()
snmpwalk()
snmpwalkoid()
SoapClient::__call()
SoapClient::__getFunctions()
SoapClient::__getLastRequest()
SoapClient::__getLastResponse()
SoapClient::__getTypes()
SoapClient::SoapClient()
SoapFault::SoapFault()
SoapHeader::SoapHeader()
SoapParam::SoapParam()
SoapServer::addFunction()
SoapServer::getFunctions()
SoapServer::handle()
SoapServer::setClass()
SoapServer::setPersistence()
SoapServer::SoapServer()
SoapVar::SoapVar()
socket_accept()
socket_bind()
socket_clear_error()
socket_close()
socket_connect()
socket_create()
socket_create_listen()
socket_create_pair()
socket_get_option()
socket_get_status()
socket_getpeername()
socket_getsockname()
socket_last_error()
socket_listen()
socket_read()
socket_recv()
socket_recvfrom()
socket_select()
socket_send()
socket_sendto()
socket_set_block()
socket_set_blocking()
socket_set_nonblock()
socket_set_option()
socket_set_timeout()
socket_shutdown()
socket_strerror()
socket_write()
sort()
soundex()
spl_classes()
split()
spliti()
sprintf()
sql_regcase()
sqlite_array_query()
sqlite_busy_timeout()
sqlite_changes()
sqlite_close()
sqlite_column()
sqlite_create_aggregate()
sqlite_create_function()
sqlite_current()
sqlite_error_string()
sqlite_escape_string()
sqlite_exec()
sqlite_factory()
sqlite_fetch_all()
sqlite_fetch_array()
sqlite_fetch_column_types()
sqlite_fetch_object()
sqlite_fetch_single()
sqlite_fetch_string()
sqlite_field_name()
sqlite_has_more()
sqlite_has_prev()
sqlite_last_error()
sqlite_last_insert_rowid()
sqlite_libencoding()
sqlite_libversion()
sqlite_next()
sqlite_num_fields()
sqlite_num_rows()
sqlite_open()
sqlite_popen()
sqlite_prev()
sqlite_query()
sqlite_rewind()
sqlite_seek()
sqlite_single_query()
sqlite_udf_decode_binary()
sqlite_udf_encode_binary()
sqlite_unbuffered_query()
sqrt()
srand()
sscanf()
ssh2_auth_none()
ssh2_auth_password()
ssh2_auth_pubkey_file()
ssh2_connect()
ssh2_exec()
ssh2_fetch_stream()
ssh2_fingerprint()
ssh2_methods_negotiated()
ssh2_scp_recv()
ssh2_scp_send()
ssh2_sftp()
ssh2_sftp_lstat()
ssh2_sftp_mkdir()
ssh2_sftp_readlink()
ssh2_sftp_realpath()
ssh2_sftp_rename()
ssh2_sftp_rmdir()
ssh2_sftp_stat()
ssh2_sftp_symlink()
ssh2_sftp_unlink()
ssh2_shell()
ssh2_tunnel()
stat()
stmt->bind_param()
stmt->bind_result()
stmt->data_seek()
stmt->execute()
stmt->fetch()
stmt->free_result()
stmt->num_rows()
stmt->param_count()
stmt->prepare()
stmt->reset()
stmt->send_long_data()
str_ireplace()
str_pad()
str_repeat()
str_replace()
str_rot13()
str_shuffle()
str_split()
str_word_count()
strcasecmp()
strchr()
strcmp()
strcoll()
strcspn()
stream_context_create()
stream_context_get_default()
stream_context_get_options()
stream_context_set_option()
stream_context_set_params()
stream_copy_to_stream()
stream_filter_append()
stream_filter_prepend()
stream_filter_register()
stream_filter_remove()
stream_get_contents()
stream_get_filters()
stream_get_line()
stream_get_meta_data()
stream_get_transports()
stream_get_wrappers()
stream_register_wrapper()
stream_select()
stream_set_blocking()
stream_set_timeout()
stream_set_write_buffer()
stream_socket_accept()
stream_socket_client()
stream_socket_enable_crypto()
stream_socket_get_name()
stream_socket_pair()
stream_socket_recvfrom()
stream_socket_sendto()
stream_socket_server()
stream_wrapper_register()
stream_wrapper_restore()
stream_wrapper_unregister()
strftime()
strip_tags()
stripcslashes()
stripos()
stripslashes()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpbrk()
strpos()
strptime()
strrchr()
strrev()
strripos()
strrpos()
strspn()
strstr()
strtok()
strtolower()
strtotime()
strtoupper()
strtr()
strval()
substr()
substr_compare()
substr_count()
substr_replace()
swf_actiongeturl()
swf_actiongotoframe()
swf_actiongotolabel()
swf_actionnextframe()
swf_actionplay()
swf_actionprevframe()
swf_actionsettarget()
swf_actionstop()
swf_actiontogglequality()
swf_actionwaitforframe()
swf_addbuttonrecord()
swf_addcolor()
swf_closefile()
swf_definebitmap()
swf_definefont()
swf_defineline()
swf_definepoly()
swf_definerect()
swf_definetext()
swf_endbutton()
swf_enddoaction()
swf_endshape()
swf_endsymbol()
swf_fontsize()
swf_fontslant()
swf_fonttracking()
swf_getbitmapinfo()
swf_getfontinfo()
swf_getframe()
swf_labelframe()
swf_lookat()
swf_modifyobject()
swf_mulcolor()
swf_nextid()
swf_oncondition()
swf_openfile()
swf_ortho()
swf_ortho2()
swf_perspective()
swf_placeobject()
swf_polarview()
swf_popmatrix()
swf_posround()
swf_pushmatrix()
swf_removeobject()
swf_rotate()
swf_scale()
swf_setfont()
swf_setframe()
swf_shapearc()
swf_shapecurveto()
swf_shapecurveto3()
swf_shapefillbitmapclip()
swf_shapefillbitmaptile()
swf_shapefilloff()
swf_shapefillsolid()
swf_shapelinesolid()
swf_shapelineto()
swf_shapemoveto()
swf_showframe()
swf_startbutton()
swf_startdoaction()
swf_startshape()
swf_startsymbol()
swf_textwidth()
swf_translate()
swf_viewport()
swfaction()
swfbitmap()
SWFBitmap->getHeight()
SWFBitmap->getWidth()
swfbutton()
SWFbutton->addAction()
SWFbutton->addShape()
SWFbutton->setAction()
SWFbutton->setdown()
SWFbutton->setHit()
SWFbutton->setOver()
SWFbutton->setUp()
swfbutton_keypress()
swfdisplayitem()
SWFDisplayItem->addColor()
SWFDisplayItem->move()
SWFDisplayItem->moveTo()
SWFDisplayItem->multColor()
SWFDisplayItem->remove()
SWFDisplayItem->Rotate()
SWFDisplayItem->rotateTo()
SWFDisplayItem->scale()
SWFDisplayItem->scaleTo()
SWFDisplayItem->setDepth()
SWFDisplayItem->setName()
SWFDisplayItem->setRatio()
SWFDisplayItem->skewX()
SWFDisplayItem->skewXTo()
SWFDisplayItem->skewY()
SWFDisplayItem->skewYTo()
swffill()
SWFFill->moveTo()
SWFFill->rotateTo()
SWFFill->scaleTo()
SWFFill->skewXTo()
SWFFill->skewYTo()
swffont()
swffont->getwidth()
swfgradient()
SWFGradient->addEntry()
swfmorph()
SWFMorph->getshape1()
SWFMorph->getshape2()
swfmovie()
SWFMovie->add()
SWFMovie->nextframe()
SWFMovie->output()
swfmovie->remove()
SWFMovie->save()
SWFMovie->setbackground()
SWFMovie->setdimension()
SWFMovie->setframes()
SWFMovie->setrate()
SWFMovie->streammp3()
swfshape()
SWFShape->addFill()
SWFShape->drawCurve()
SWFShape->drawCurveTo()
SWFShape->drawLine()
SWFShape->drawLineTo()
SWFShape->movePen()
SWFShape->movePenTo()
SWFShape->setLeftFill()
SWFShape->setLine()
SWFShape->setRightFill()
swfsprite()
swfsprite->add()
SWFSprite->nextframe()
SWFSprite->remove()
SWFSprite->setframes()
swftext()
SWFText->addString()
SWFText->getWidth()
SWFText->moveTo()
SWFText->setColor()
SWFText->setFont()
SWFText->setHeight()
SWFText->setSpacing()
swftextfield()
SWFTextField->addstring()
SWFTextField->align()
SWFTextField->setbounds()
SWFTextField->setcolor()
SWFTextField->setFont()
SWFTextField->setHeight()
SWFTextField->setindentation()
SWFTextField->setLeftMargin()
SWFTextField->setLineSpacing()
SWFTextField->setMargins()
SWFTextField->setname()
SWFTextField->setrightMargin()
sybase_affected_rows()
sybase_close()
sybase_connect()
sybase_data_seek()
sybase_deadlock_retry_count()
sybase_fetch_array()
sybase_fetch_assoc()
sybase_fetch_field()
sybase_fetch_object()
sybase_fetch_row()
sybase_field_seek()
sybase_free_result()
sybase_get_last_message()
sybase_min_client_severity()
sybase_min_error_severity()
sybase_min_message_severity()
sybase_min_server_severity()
sybase_num_fields()
sybase_num_rows()
sybase_pconnect()
sybase_query()
sybase_result()
sybase_select_db()
sybase_set_message_handler()
sybase_unbuffered_query()
symlink()
syslog()
system()

T

tan()
tanh()
tcpwrap_check()
tempnam()
textdomain()
tidy::__construct()
tidy_access_count()
tidy_clean_repair()
tidy_config_count()
tidy_diagnose()
tidy_error_count()
tidy_get_body()
tidy_get_config()
tidy_get_error_buffer()
tidy_get_head()
tidy_get_html()
tidy_get_html_ver()
tidy_get_output()
tidy_get_release()
tidy_get_root()
tidy_get_status()
tidy_getopt()
tidy_is_xhtml()
tidy_is_xml()
tidy_load_config()
tidy_node->children()
tidy_node->get_attr()
tidy_node->get_nodes()
tidy_node->hasChildren()
tidy_node->hasSiblings()
tidy_node->isComment()
tidy_node->isHtml()
tidy_node->isJste()
tidy_node->isText()
tidy_node->isXhtml()
tidy_node->isXml()
tidy_node->next()
tidy_node->prev()
tidy_parse_file()
tidy_parse_string()
tidy_repair_file()
tidy_repair_string()
tidy_reset_config()
tidy_save_config()
tidy_set_encoding()
tidy_setopt()
tidy_warning_count()
tidyNode->isAsp()
tidyNode->isPhp()
time()
time_nanosleep()
tmpfile()
token_get_all()
token_name()
touch()
trigger_error()
trim()

U

uasort()
ucfirst()
ucwords()
udm_add_search_limit()
udm_alloc_agent()
udm_alloc_agent_array()
udm_api_version()
udm_cat_list()
udm_cat_path()
udm_check_charset()
udm_check_stored()
udm_clear_search_limits()
udm_close_stored()
udm_crc32()
udm_errno()
udm_error()
udm_find()
udm_free_agent()
udm_free_ispell_data()
udm_free_res()
udm_get_doc_count()
udm_get_res_field()
udm_get_res_param()
udm_hash32()
udm_load_ispell_data()
udm_open_stored()
udm_set_agent_param()
uksort()
umask()
uniqid()
unixtojd()
unlink()
unpack()
unregister_tick_function()
unserialize()
unset()
urldecode()
urlencode()
user_error()
usleep()
usort()
utf8_decode()
utf8_encode()

V

var_dump()
var_export()
variant()
variant_abs()
variant_add()
variant_and()
variant_cast()
variant_cat()
variant_cmp()
variant_date_from_timestamp()
variant_date_to_timestamp()
variant_div()
variant_eqv()
variant_fix()
variant_get_type()
variant_idiv()
variant_imp()
variant_int()
variant_mod()
variant_mul()
variant_neg()
variant_not()
variant_or()
variant_pow()
variant_round()
variant_set()
variant_set_type()
variant_sub()
variant_xor()
version_compare()
vfprintf()
virtual()
vpopmail_add_alias_domain()
vpopmail_add_alias_domain_ex()
vpopmail_add_domain()
vpopmail_add_domain_ex()
vpopmail_add_user()
vpopmail_alias_add()
vpopmail_alias_del()
vpopmail_alias_del_domain()
vpopmail_alias_get()
vpopmail_alias_get_all()
vpopmail_auth_user()
vpopmail_del_domain()
vpopmail_del_domain_ex()
vpopmail_del_user()
vpopmail_error()
vpopmail_passwd()
vpopmail_set_user_quota()
vprintf()
vsprintf()

W

w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
w32api_register_function()
w32api_set_call_method()
wddx_add_vars()
wddx_deserialize()
wddx_packet_end()
wddx_packet_start()
wddx_serialize_value()
wddx_serialize_vars()
wordwrap()

X

xattr_get()
xattr_list()
xattr_remove()
xattr_set()
xattr_supported()
xdiff_file_diff()
xdiff_file_diff_binary()
xdiff_file_merge3()
xdiff_file_patch()
xdiff_file_patch_binary()
xdiff_string_diff()
xdiff_string_diff_binary()
xdiff_string_merge3()
xdiff_string_patch()
xdiff_string_patch_binary()
xml_error_string()
xml_get_current_byte_index()
xml_get_current_column_number()
xml_get_current_line_number()
xml_get_error_code()
xml_parse()
xml_parse_into_struct()
xml_parser_create()
xml_parser_create_ns()
xml_parser_free()
xml_parser_get_option()
xml_parser_set_option()
xml_set_character_data_handler()
xml_set_default_handler()
xml_set_element_handler()
xml_set_end_namespace_decl_handler()
xml_set_external_entity_ref_handler()
xml_set_notation_decl_handler()
xml_set_object()
xml_set_processing_instruction_handler()
xml_set_start_namespace_decl_handler()
xml_set_unparsed_entity_decl_handler()
xmlrpc_decode()
xmlrpc_decode_request()
xmlrpc_encode()
xmlrpc_encode_request()
xmlrpc_get_type()
xmlrpc_is_fault()
xmlrpc_parse_method_descriptions()
xmlrpc_server_add_introspection_data()
xmlrpc_server_call_method()
xmlrpc_server_create()
xmlrpc_server_destroy()
xmlrpc_server_register_introspection_callback()
xmlrpc_server_register_method()
xmlrpc_set_type()
xpath_eval()
xpath_eval_expression()
xpath_new_context()
xptr_eval()
xptr_new_context()
xsl_xsltprocessor_get_parameter()
xsl_xsltprocessor_has_exslt_support()
xsl_xsltprocessor_import_stylesheet()
xsl_xsltprocessor_register_php_functions()
xsl_xsltprocessor_remove_parameter()
xsl_xsltprocessor_set_parameter()
xsl_xsltprocessor_transform_to_doc()
xsl_xsltprocessor_transform_to_uri()
xsl_xsltprocessor_transform_to_xml()
xslt_backend_info()
xslt_backend_name()
xslt_backend_version()
xslt_create()
xslt_errno()
xslt_error()
xslt_free()
xslt_getopt()
xslt_process()
xslt_set_base()
xslt_set_encoding()
xslt_set_error_handler()
xslt_set_log()
xslt_set_object()
xslt_set_sax_handler()
xslt_set_sax_handlers()
xslt_set_scheme_handler()
xslt_set_scheme_handlers()
xslt_setopt()

Y

yaz_addinfo()
yaz_ccl_conf()
yaz_ccl_parse()
yaz_close()
yaz_connect()
yaz_database()
yaz_element()
yaz_errno()
yaz_error()
yaz_es_result()
yaz_get_option()
yaz_hits()
yaz_itemorder()
yaz_present()
yaz_range()
yaz_record()
yaz_scan()
yaz_scan_result()
yaz_schema()
yaz_search()
yaz_set_option()
yaz_sort()
yaz_syntax()
yaz_wait()
yp_all()
yp_cat()
yp_err_string()
yp_errno()
yp_first()
yp_get_default_domain()
yp_master()
yp_match()
yp_next()
yp_order()

Z

zend_logo_guid()
zend_version()
zip_close()
zip_entry_close()
zip_entry_compressedsize()
zip_entry_compressionmethod()
zip_entry_filesize()
zip_entry_name()
zip_entry_open()
zip_entry_read()
zip_open()
zip_read()
zlib_get_coding_type()

Prev | Home | Next
Function Index | Up | HTML Help Edition


PHP Manual

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 46 section of the documentation is based on an initial contribution by Zend Technologies.

Home


About This Edition

PHP Manual
Prev Next

Chapter 63. About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote webpage to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). The user notes are in php_manual_notes.chm. You only need to have one copy of this file on your computer, regardless of how many languages you use to read the PHP Manual. The only requirement is that you need to have all php_manual_LANG.chm files in one directory with php_manual_notes.chm. You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this WinWriters article.

Prev | Home | Next
HTML Help Edition | Up | Using PHP Manual CHM Edition


CHM Edition Credits

PHP Manual
Prev

Chapter 69. CHM Edition Credits

This enhanced version of the PHP Manual would never come to existence, if the following people would not help with their contribution to the project (in no particular order):

  • Holger Eggert, who created the two default designs, and provided many usability tips

  • Gonzalo De la Pena Andreu, who added many comments on how it would be ideal to provide the skinnable interface

  • Olexandr Vynnychenko added countless comments and testing all the time

  • Brendan Ferguson, who provided many optimizations, improvements to the HTML and JS codes behind the manual pages

  • Sandor Hojtsy, who coded the manual preferences desktop application

  • And at last but not least, everybody, who provided feedback through our mailing list, and in the user survey

Prev | Home
CSS classes | Up


Integrating the PHP Manual

PHP Manual
Prev Next

Chapter 67. Integrating the PHP Manual

Note: The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Note: All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at http://msdn.microsoft.com/library/en-us/htmlhelp/html/vsconhh1start.asp.

Prev | Home | Next
Presentational Specialities | Up | Skin development


The Full Text Search

PHP Manual
Prev Next

Chapter 65. The Full Text Search

Table of Contents
General searching rules
Searching for words or phrases
Defining search terms
Using nested expressions when searching
Manual Content and User Note Separation

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.

  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.

  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.

  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Note: If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

Prev | Home | Next
Keyboard Shortcuts | Up | Searching for words or phrases


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.

  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".

  • You cannot nest expressions more than five levels deep.

Prev | Home | Next
Defining search terms | Up | Manual Content and User Note Separation


Manual Content and User Note Separation

The manual content and the user notes are separated to php_manual_LANG.chm and php_manual_notes.chm. There were several resons to do this, including:

  • This way you can update the user notes and the manual independently as you need.

  • You can have more than one language of the manual, while only need to have one notes file. All the CHM files need to be in the same directory, and all translations need to share the same preferences if you would not like to have more then one notes file.

  • You can bookmark manual pages with notes, or just a notes part of a page separately.

  • You can "turn off" user note display and user note search results by simply deleting php_manual_notes.chm, moving it out of the directory or renaming it.

All these benefits lead us to provide the manual the way you can see it right now. This distribution had the effect on the full text search that you get search results from the manual content and from the user notes as separate ones. The "Location" column shows the source of the result, also enabling you to "add precedence" to manual content results with ordering the results by "Location". User note page titles are also prefixed with "N:" to make them easily distinguishable in the favorites list (there's no location info in the favorites list).

Prev | Home | Next
Using nested expressions when searching | Up | Specialities of this Edition


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Table 65-2. Search operators

Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Note: The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

Prev | Home | Next
Searching for words or phrases | Up | Using nested expressions when searching


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Table 65-1. Word and phrase searches

Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase "new operator" or new operator

Topics that contain the literal phrase "new operator" and all its grammatical variations.

Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.

Wildcard expressions esc* or HT??

Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term.

Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Note: Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

Prev | Home | Next
The Full Text Search | Up | Defining search terms


Skin development

PHP Manual
Prev Next

Chapter 68. Skin development

Table of Contents
Page Display Process
Page Elements
CSS classes

This edition of the PHP Manual allows users to choose from skins to display the contents, as well as develop custom skins to meet some special needs. We decided to support skins because we realized that one skin cannot satisfy everybody's needs in a such heavily used edition.

We included two skins by default inside the CHM. These cannot be modified or removed, so if you have the CHM, you have these two skins inside. The Low skin is optimized for small window display, the High skin is a variation of the Low one with some graphics added to spice it up.

A skin must have at least two files, a skin loader JavaScript file and a CSS file. The two inline skins have these files inside the CHM. The skin loader JS should at least load in the CSS file and display the page contents to the viewer. Theoretically there are two kinds of skins: CSS skins and Full skins. CSS skins only modify the CSS and does not amend the page layout. Full skins also modify the page layout. We have included sample skins for both the CSS skin type and the Full skin type ("greenlinks" and "headernostalgia" respectively).

Warning

Note that though the current skin development methods are quite final, there may be heavy changes in used CSS classes or page elements while we refine the skin development ideas. As this edition is currently in development stage, the information described herein is not to be considered completely stable.

Page Display Process

If you are going to develop your own skin, you should know how one page is loaded and displayed to the user, and how a skin fits in this process. For these paragraphs, we assume that you have put your CHM into c:\phpmanual, so it's accessible as c:\phpmanual\php_manual_LANG.chm (where LANG is the language code), and you would like to see the function page of "echo", which is function.echo.html inside the CHM. See the sections about integration for more information on CHM contents.

  • First of all the HTML content is loaded in from function.echo.html from inside the CHM.

  • At the top of this file, there is a HTML <script> tag, which loads in the _script.js file from the CHM. This file contains all the JS code needed to move on with the process. Most importantly this JS defines many variables (like where the CHM is, or what is the actual page viewed) and many functions to print out the context menu or handle online functions.

  • At last _script.js loads in the preferences file from outside the CHM (c:\phpmanual\php_manual_prefs.js in our example). This JS file defines the preference variables, and calls back prefHandler() which is also defined in _script.js.

  • That function loads in the skin JS file as the preferences dictate. The skin JS file should load in the needed CSS file, and define a displayPage() function, which displays the page if called.

  • The HTML file (function.echo.html in this example) also contains a function call to load in the user notes, which simply puts the notes into this HTML file using DHTML to be displayed as if they were here before...

  • The HTML file also contains a body onload attribute which calls the skin-defined displayPage() function to show the page to the user. This is the last function called, it should present the page in it's complete form to the user.

Every action is synchronized with calling back a function in the previously loaded file when the JS is in memory. The notes loading and skin JS loading is only synchronized with the page's onload event (which as the Microsoft documentation says only fires if the page is completely loaded).

This load and callback chain may seem to be too complicated, but so far this seemed to be the best way to do as many things as possible parallel, while also synchronize some calls.

As you can see your skin JavaScript file is loaded in by _script.js and it's displayPage() function is called by the body onload event.

Prev | Home | Next
Integrating the PHP Manual | Up | Page Elements


CSS classes

We cannot provide accurate documentation currently on usable CSS classes, as some of the DocBook XSL sheets classes are not used and some classes are added. Please see the sample CSS files included for first time reference.

Prev | Home | Next
Page Elements | Up | CHM Edition Credits


Page Elements

The PHP Manual pages are all HTML files with several HTML tags in them for both presentational and divisional purposes. The HTML pages contain divisions to be used for skinning purposes and misc divisions added by the DocBook XSL sheets.

A HTML page can be either a function reference page or another kind of page (like a feature description). Skins should get ready to skin these two kinds of pages separately most of the time (depending on the actual design).

The pages are structured using <div> tags with appropriate IDs to ease the skin writers work. A page consists of these parts:

  • <div id="pageContent"></div> contains all the page contents. This begins right after <body> and ends just before </body>. This division is hidden by default, you need to show it after you are ready with the page rewriting process.

  • <div id="pageHeaders"></div> contains the page header parts. This includes the text only main title (in a <span id="pageTitle"></span>) and function properties, in case this is a function page (contained in <span id="funcPurpose"></span>, <span id="funcAvail"></span> and <span id="funcUsage"></span>). In case one of these three is not available, the current page is not a function page.

  • <div id="pageText"></div> contains the majority of the page contents, including examples, manual notes, warnings, etc. This also includes see also parts for now, as we still cannot differentiate between see also and normal text parts (may be a thing to change in the future).

  • <div id="pageNotes"></div> contains the user notes (itself loaded in from another HTML file by JS). It contains a heading, and then a <div> without ID for every user note and spans in that divs for every element of a user note (with "email", "date" and "text" IDs respectively).

  • <div id="pageNav"></div> contains the
navigation table, which is further divided into spans (<span
id="navPrev"></span>, <span
id="navPath"></span>, <span
id="navNext"></span>, <span
id="navOnline"></span>, <span
id="navThisOnline"></span> and <span
id="navReportBug"></span>), where navThisOnline
and navReportBug is inside navOnline.

If you would like to rewrite the page, you should first read in the parts you need from the page to JS variables, then clear the contents of pageContent (or just the part you would like to rewrite), write in the new content and show the pageContent div for the user. If you would not like to make any structural changes, you can simply display the pageContent div and only specify a special style sheet in your skin JS file (see the "greenlinks" skin for an example).

You can find a "Full skin" developed to show you how to make skins built on top of this structure. The skin name is "headernostalgia". It rewrites the header part and removes the footer navigational table.

Prev | Home | Next
Skin development | Up | CSS classes


Specialities of this Edition

PHP Manual
Prev Next

Chapter 66. Specialities of this Edition

Table of Contents
User Preferences
Presentational Specialities

The Windows HTML Help Edition of the PHP Manual over-performs the presentational and interactive capabilities offered by other editions (including the online manual). This was possible because currently CHMs can only be viewed on Windows using Internet explorer, so we can develop for one browser family and one operating system. Viewers for other OSes may be developed in the future by third parties.

User Preferences

Most of the interactive features of this manual are provided by the viewer application (including full text search, index, favorites list), but we extended this list with PHP Manual specific tools. All these can be adjusted to your needs using a simple desktop application named php_manual_prefs.exe. If you run this program you can see three groups of settings: Online Functions, Context Menu, and Skin. All your settings are stored in php_manual_prefs.js.

Online functions enable you to have elements connected to websites. The two ones you can see on all manual pages are "This page online" and "Report a bug". As you can figure out the first one shows you the same page in the online manual, the second one opens a page from http://bugs.php.net/ and prefills some bug data for you. You need to select a mirror site to use for "php.net sensitive" online functions. We recommend choosing a close mirror site to get the best speed. Other components that may be limited by this online functions setting include context menu items opening new websites ("Google search selection" for example). Custom designs may also include elements restricted by this setting.

The context menu settings enables you to choose which context menu you prefer. This application provides you with an option to define your own context menu adding elements to it from a predefined set. You can have this custom context menu for the right click of your mouse, and have the original menu for CTRL+right click, or the opposite way. Three special types of custom context menu items exist:

Table 66-1. Context menu items

Type | Examples | Comments
Page Jump | Function Reference, Function Index | These items jump to a specific page in the CHM. Page Jump options are not restricted to point inside the CHM though. They can point to websites or other resources. Page jump options with a protocol part in the URL open in new window.
Function Call | Print page, Select all, Copy selection to clipboard, Google Search Selection | These are "function calls" for internally defined context menu functions. The last two examples have the speciality that they only show up in the menu if you rightclicked on a selection. Currently there is no way to extend the context menu with skin defined functions.
Special display | Google SearchBox, AlltheWeb SearchBox | These are displayed as HTML forms, where you can enter search keywords, press ENTER, and receive a new window with the search issued in the appropriate search engine. Currently there is no way to extend the set of specially displayed context menu items.
Possible context menu elements and their "abstract implementations" are stored in context.ini. You have the ability to add possible page jump options there, but there is no way currently to extend the context menu system with user (skin) defined functions. The possible mirror sites are listed in mirrors.ini. Feel free to suggest more bundled context menu items to us at php-doc-chm@lists.php.net.

The skins setting enables you to choose from the two bundled default skins, or from any user defined skins. The Low skin is optimized to display correctly at any small size, the High skin is optimized for your viewing pleasure. Other skins may be developed according to our skins development guide. The recommended place for skins on the file system is the skins/SKINNAME subfolder of the PHP Manual directory. Though this is not required, some skins may define other rules (not recommended). We included sample skins for you to see examples of how to develop skins for the PHP Manual.

You have three buttons to choose from at the bottom. The Apply button applies your changes without exiting, the OK button applies and closes the application, the Cancel button does not modify your settings and closes the program.

Prev | Home | Next
Manual Content and User Note Separation | Up | Presentational Specialities


Presentational Specialities

This edition of the PHP Manual is highly optimized for screen presentation. Skins may be developed to better support printing, as this was not the goal of the included skins. This approach allowed us to make many modifications to the presentation of different parts of the manual.

The first thing you'll notice is that all examples are color coded, using the PHP function show_source(). The actual colors used are defined by CSS classes. Examples also have links to PHP functions used in them to provide quick access to reference material. All code examples have a "copy to clipboard" link by the side of them with which you can copy the text contents of the example to the clipboard.

External links are marked with a special » sign, and open in a new browser window. We also included the "path to this page" information on all pages for you to easily identify where you are and navigate as needed.

Other parts of the manual are quite similar to the online ones by default, though custom skins can modify many elements on the pages.

Prev | Home | Next
Specialities of this Edition | Up | Integrating the PHP Manual


Using PHP Manual CHM Edition

PHP Manual
Prev Next

Chapter 64. Using PHP Manual CHM Edition

Table of Contents
The HTML Help Toolbar
The Navigation Pane
Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.

  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).

  • Back - Goes back in the history.

  • Forward - Goes forward in the history.

  • Refresh - Reloads the current page.

  • Home - Opens the startup page of the CHM.

  • Print - Opens the print dialog box.

  • Options - Provides a dropdown with more options.

Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

Prev | Home | Next
About This Edition | Up | The Navigation Pane


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

Table 64-1. General Help Viewer Shortcuts

To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu [see the User Preferences section] | SHIFT+F10

Table 64-2. Contents Tab Shortcuts

To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER

Table 64-3. Index Tab Shortcuts

To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D

Table 64-4. Search Tab shortcuts

To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R

Table 64-5. Favorites Tab Shortcuts

To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R

Table 64-6. Topic Pane Shortcuts

To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

Prev | Home | Next
The Navigation Pane | Up | The Full Text Search


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).

  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.

  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.

  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

Prev | Home | Next
Using PHP Manual CHM Edition | Up | Keyboard Shortcuts


HTML Help Edition

PHP Manual
Prev Next

X. HTML Help Edition

Table of Contents
63. About This Edition
64. Using PHP Manual CHM Edition
65. The Full Text Search
66. Specialities of this Edition
67. Integrating the PHP Manual
68. Skin development
69. CHM Edition Credits

Prev | Home | Next
Function Index |  | About This Edition


Runtime Configuration

PHP Manual
Prev Next

Chapter 9. Runtime Configuration

Table of Contents
The configuration file
How to change configuration settings

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".

Prev | Home | Next
Bug reports | Up | How to change configuration settings


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().

Prev | Home | Next
Runtime Configuration | Up | Language Reference


Extension Categorization

PHP Manual
Prev Next

Appendix I. Extension Categorization

Table of Contents
Purpose
Membership
State

This appendix categorizes more than 150 extensions documented in the PHP Manual by several criteria.

Purpose

Basic PHP Extensions

Variable and Type Related Extensions

  • Reference V, Array Functions

  • Reference XIII, Classkit Functions

  • Reference XII, Class/Object Functions

  • Reference XVII, Character Type Functions

  • Reference XLI, Filter Functions

  • Reference XLVII, Function Handling Functions

  • Reference CIII, Object Aggregation/Composition Functions

  • Reference CLXVIII, Variable Handling Functions

Text Processing

  • Reference CXVIII, Regular Expression Functions (Perl-Compatible)

  • Reference CXXIV, Regular Expression Functions (POSIX Extended)

  • Reference CLIX, String Functions

  • Reference CLXXVI, xdiff Functions

Affecting PHP's Behaviour

  • Reference III, Alternative PHP Cache

  • Reference IV, Advanced PHP debugger

  • Reference VIII, PHP bytecode Compiler

  • Reference XXXIII, Error Handling and Logging Functions

  • Reference LIV, HTTP

  • Reference CXXII, PHP Options&Information

  • Reference CXIII, Output Control Functions

  • Reference CXXXVII, runkit Functions

Session Extensions

  • Reference XCII, Mohawk Software Session Handler Functions

  • Reference XCV, muscat Functions

  • Reference CXLVII, Session Handling Functions

  • Reference CXLVI, PostgreSQL Session Save Handler

Other Basic Extensions

  • Reference XLVIII, GeoIP Functions

  • Reference LXXI, JSON Functions

  • Reference LXXXVIII, Miscellaneous Functions

  • Reference CXVI, Parsekit Functions

  • Reference CLIII, Standard PHP Library (SPL) Functions

  • Reference CLXIV, Tidy Functions

  • Reference CLXV, Tokenizer Functions

  • Reference CLXVII, URL Functions

Database Extensions

Abstraction Layers

  • Reference XXIV, Database (dbm-style) Abstraction Layer Functions

  • Reference XXVII, dbx Functions

  • Reference CXX, PDO Functions

  • Reference CXLI, SDO Functions

  • Reference CXLIII, SDO Relational Data Access Service Functions

  • Reference CVI, ODBC Functions (Unified)

Vendor Specific Database Extensions

  • Reference XXV, dBase Functions

  • Reference XXIII, DB++ Functions

  • Reference XLV, FrontBase Functions

  • Reference XXXIX, filePro Functions

  • Reference XLII, Firebird/InterBase Functions

  • Reference LVIII, IBM DB2, Cloudscape and Apache Derby Functions

  • Reference LXVI, Informix Functions

  • Reference LXVIII, Ingres II Functions

  • Reference LXXX, MaxDB PHP Extension

  • Reference XCIII, mSQL Functions

  • Reference XC, Microsoft SQL Server Functions

  • Reference XCVI, MySQL Functions

  • Reference XCVIII, MySQL Improved Extension

  • Reference CV, Oracle Functions

  • Reference CXI, Oracle Functions [deprecated]

  • Reference CXIV, Ovrimos SQL Functions

  • Reference CXV, Paradox File Access

  • Reference XCI, Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

  • Reference XLIII, Firebird/Interbase Functions (PDO_FIREBIRD)

  • Reference LXVII, Informix Functions (PDO_INFORMIX)

  • Reference XCVII, MySQL Functions (PDO_MYSQL)

  • Reference CXII, Oracle Functions (PDO_OCI)

  • Reference CVII, ODBC and DB2 Functions (PDO_ODBC)

  • Reference CXXVI, PostgreSQL Functions (PDO_PGSQL)

  • Reference CLV, SQLite Functions (PDO_SQLITE)

  • Reference CXXV, PostgreSQL Functions

  • Reference CLIV, SQLite Functions

  • Reference CLXII, Sybase Functions

XML Manipulation

  • Reference XXX, DOM Functions

  • Reference XXXI, DOM XML Functions

  • Reference LXXIV, libxml Functions

  • Reference CXXXI, qtdom Functions

  • Reference CXLII, SDO XML Data Access Service Functions

  • Reference CXLIX, SimpleXML functions

  • Reference CLXXVII, XML Parser Functions

  • Reference CLXXIX, XMLReader functions

  • Reference CLXXX, XMLWriter Functions

  • Reference CLXXXI, XSL functions

  • Reference CLXXXII, XSLT Functions

Web Services

  • Reference CLI, SOAP Functions

  • Reference CLXXII, WDDX Functions

  • Reference CLXXVIII, XML-RPC Functions

Credit Card Processing

  • Reference XIX, Cybercash Payment Functions

  • Reference XX, Credit Mutuel CyberMUT functions

  • Reference LXXXIII, MCVE (Monetra) Payment Functions

  • Reference CLXIX, Verisign Payflow Pro Functions

Math and Cryptography

Mathematical Extensions

  • Reference VII, BCMath Arbitrary Precision Mathematics Functions

  • Reference L, GMP Functions

  • Reference LXXIX, Mathematical Functions

  • Reference CLVII, Statistics Functions

Cryptography Extensions

  • Reference XVI, Crack Functions

  • Reference LIII, hash Functions

  • Reference LXXXII, Mcrypt Encryption Functions

  • Reference LXXXV, Mhash Functions

  • Reference CX, OpenSSL Functions

Human Language and Character Encoding Support

  • Reference XXXII, enchant Functions

  • Reference XLIV, FriBiDi Functions

  • Reference XLIX, Gettext

  • Reference LX, iconv Functions

  • Reference XCIV, Multibyte String Functions

  • Reference CXXX, Pspell Functions

  • Reference CXXXV, GNU Recode Functions

  • Reference CLXVI, Unicode Functions

File System and Process Control

File System Related Extensions

  • Reference XXVIII, Direct IO Functions

  • Reference XXIX, Directory Functions

  • Reference XXXVI, File Alteration Monitor Functions

  • Reference XXXVIII, Fileinfo Functions

  • Reference XL, Filesystem Functions

  • Reference LXXXVI, Mimetype Functions

  • Reference CLXXV, xattr Functions

Process Control Extensions

  • Reference CXXVIII, Program Execution Functions

  • Reference XXXV, Expect Functions

  • Reference CXVII, Process Control Functions

  • Reference CXXIII, POSIX Functions

  • Reference CXLIV, Semaphore, Shared Memory and IPC Functions

  • Reference CXLVIII, Shared Memory Functions

Accessing Services

Mail Related Extensions

  • Reference XXI, Cyrus IMAP administration Functions

  • Reference LXV, IMAP, POP3 and NNTP Functions

  • Reference LXXVII, Mail Functions

  • Reference LXXVIII, mailparse Functions

  • Reference CLXX, vpopmail Functions

Authentication Services

  • Reference LXXII, KADM5

  • Reference CXXXII, Radius

Other Services

  • Reference XVIII, CURL, Client URL Library Functions

  • Reference XLVI, FTP Functions

  • Reference LV, Hyperwave Functions

  • Reference LVI, Hyperwave API Functions

  • Reference LXIX, IRC Gateway Functions

  • Reference LXX, PHP / Java Integration

  • Reference LXXIII, LDAP Functions

  • Reference LXXXIV, Memcache Functions

  • Reference LXXXIX, mnoGoSearch Functions

  • Reference LII, Net_Gopher

  • Reference C, Network Functions

  • Reference CLXXXIV, YP/NIS Functions

  • Reference LXXV, Lotus Notes Functions

  • Reference CL, SNMP Functions

  • Reference CLII, Socket Functions

  • Reference CLVI, Secure Shell2 Functions

  • Reference CLVIII, Stream Functions

  • Reference CLXIII, TCP Wrappers Functions

  • Reference CLXXXIII, YAZ Functions

Compression Extensions

  • Reference IX, Bzip2 Compression Functions

  • Reference LXXVI, LZF Functions

  • Reference CXXXIII, Rar Functions

  • Reference CLXXXV, Zip File Functions

  • Reference CLXXXVI, Zlib Compression Functions

Calendar and Event Related Extensions

  • Reference X, Calendar Functions

  • Reference XXII, Date and Time Functions

  • Reference LXXXI, MCAL Functions

Utilization Area Specific Extensions

Non-Text MIME Output

  • Reference XIV, ClibPDF Functions

  • Reference XXXVII, Forms Data Format Functions

  • Reference LI, gnupg Functions

  • Reference LXXXVII, Ming functions for Flash

  • Reference CXIX, PDF Functions

  • Reference CXXIX, PostScript document creation

  • Reference CXXXVI, RPM Header Reading Functions

  • Reference CLX, Shockwave Flash Functions

Image Processing and Generation

  • Reference XXXIV, Exif Functions

  • Reference LXIII, Image Functions

Audio Formats Manipulation

  • Reference LXI, ID3 Functions

  • Reference CVIII, oggvorbis

  • Reference CIX, OpenAL Audio Bindings

Command Line Specific Extensions

  • Reference XCIX, Ncurses Terminal Screen Control Functions

  • Reference CI, Newt Functions

  • Reference CXXXIV, GNU Readline

Windows Only Extensions

  • Reference XV, COM and .Net (Windows)

  • Reference I, .NET Functions

  • Reference CXXVII, Printer Functions

  • Reference CLXXI, W32api Functions

  • Reference CLXXIII, win32ps Functions

  • Reference CLXXIV, win32service Functions

Server Specific Extensions

  • Reference II, Apache-specific Functions

  • Reference LXII, IIS Administration Functions

  • Reference CII, NSAPI-specific Functions

Prev | Home | Next
List of timezones in the group Others | Up | Membership


Membership

Core Extensions

These are not actual extensions. They are part of the PHP core and cannot be left out of a PHP binary with compilation options.

  • Reference V, Array Functions

  • Reference XII, Class/Object Functions

  • Reference XXII, Date and Time Functions

  • Reference XXIX, Directory Functions

  • Reference XXXIII, Error Handling and Logging Functions

  • Reference CXXVIII, Program Execution Functions

  • Reference XL, Filesystem Functions

  • Reference XLVII, Function Handling Functions

  • Reference CXXII, PHP Options&Information

  • Reference LXXVII, Mail Functions

  • Reference LXXIX, Mathematical Functions

  • Reference LXXXVIII, Miscellaneous Functions

  • Reference C, Network Functions

  • Reference CXIII, Output Control Functions

  • Reference CXXIV, Regular Expression Functions (POSIX Extended)

  • Reference CXLVII, Session Handling Functions

  • Reference CLVIII, Stream Functions

  • Reference CLIX, String Functions

  • Reference CLXV, Tokenizer Functions

  • Reference CLXVI, Unicode Functions

  • Reference CLXVII, URL Functions

  • Reference CLXVIII, Variable Handling Functions

Bundled Extensions

These extensions are bundled with PHP.

  • Reference II, Apache-specific Functions

  • Reference VII, BCMath Arbitrary Precision Mathematics Functions

  • Reference IX, Bzip2 Compression Functions

  • Reference X, Calendar Functions

  • Reference XV, COM and .Net (Windows)

  • Reference XVII, Character Type Functions

  • Reference XVIII, CURL, Client URL Library Functions

  • Reference XXIV, Database (dbm-style) Abstraction Layer Functions

  • Reference XXV, dBase Functions

  • Reference XXX, DOM Functions

  • Reference I, .NET Functions

  • Reference XXXIV, Exif Functions

  • Reference XLV, FrontBase Functions

  • Reference XXXVII, Forms Data Format Functions

  • Reference XLVI, FTP Functions

  • Reference XLIX, Gettext

  • Reference L, GMP Functions

  • Reference LIII, hash Functions

  • Reference XLII, Firebird/InterBase Functions

  • Reference LX, iconv Functions

  • Reference LXVI, Informix Functions

  • Reference LXIII, Image Functions

  • Reference LXV, IMAP, POP3 and NNTP Functions

  • Reference LXXI, JSON Functions

  • Reference LXXIII, LDAP Functions

  • Reference LXXIV, libxml Functions

  • Reference XCIV, Multibyte String Functions

  • Reference LXXXII, Mcrypt Encryption Functions

  • Reference LXXXV, Mhash Functions

  • Reference LXXXVI, Mimetype Functions

  • Reference LXXXVII, Ming functions for Flash

  • Reference XCIII, mSQL Functions

  • Reference XC, Microsoft SQL Server Functions

  • Reference XCVI, MySQL Functions

  • Reference XCVIII, MySQL Improved Extension

  • Reference XCIX, Ncurses Terminal Screen Control Functions

  • Reference CII, NSAPI-specific Functions

  • Reference CIII, Object Aggregation/Composition Functions

  • Reference CV, Oracle Functions

  • Reference CX, OpenSSL Functions

  • Reference CXVII, Process Control Functions

  • Reference CXVIII, Regular Expression Functions (Perl-Compatible)

  • Reference CXX, PDO Functions

  • Reference XCI, Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

  • Reference XLIII, Firebird/Interbase Functions (PDO_FIREBIRD)

  • Reference XCVII, MySQL Functions (PDO_MYSQL)

  • Reference CXII, Oracle Functions (PDO_OCI)

  • Reference CVII, ODBC and DB2 Functions (PDO_ODBC)

  • Reference CXXVI, PostgreSQL Functions (PDO_PGSQL)

  • Reference CLV, SQLite Functions (PDO_SQLITE)

  • Reference CXXV, PostgreSQL Functions

  • Reference CXXIII, POSIX Functions

  • Reference CXXX, Pspell Functions

  • Reference CXXXIV, GNU Readline

  • Reference CXXXV, GNU Recode Functions

  • Reference CXLIV, Semaphore, Shared Memory and IPC Functions

  • Reference CXLVIII, Shared Memory Functions

  • Reference CXLIX, SimpleXML functions

  • Reference CL, SNMP Functions

  • Reference CLI, SOAP Functions

  • Reference CLII, Socket Functions

  • Reference CLIII, Standard PHP Library (SPL) Functions

  • Reference CLIV, SQLite Functions

  • Reference CLXII, Sybase Functions

  • Reference CLXIV, Tidy Functions

  • Reference CVI, ODBC Functions (Unified)

  • Reference CLXXII, WDDX Functions

  • Reference CLXXVII, XML Parser Functions

  • Reference CLXXIX, XMLReader functions

  • Reference CLXXVIII, XML-RPC Functions

  • Reference CLXXXI, XSL functions

  • Reference CLXXXII, XSLT Functions

  • Reference CLXXXV, Zip File Functions

  • Reference CLXXXVI, Zlib Compression Functions

External Extensions

In order to compile these extensions, external libraries will be needed.

  • Reference IX, Bzip2 Compression Functions

  • Reference XIV, ClibPDF Functions

  • Reference XVI, Crack Functions

  • Reference XVIII, CURL, Client URL Library Functions

  • Reference XXV, dBase Functions

  • Reference XXIII, DB++ Functions

  • Reference XXVII, dbx Functions

  • Reference XXX, DOM Functions

  • Reference XXXI, DOM XML Functions

  • Reference XXXII, enchant Functions

  • Reference XXXVI, File Alteration Monitor Functions

  • Reference XLV, FrontBase Functions

  • Reference XXXVII, Forms Data Format Functions

  • Reference XXXVIII, Fileinfo Functions

  • Reference XLIV, FriBiDi Functions

  • Reference XLVIII, GeoIP Functions

  • Reference XLIX, Gettext

  • Reference L, GMP Functions

  • Reference LV, Hyperwave Functions

  • Reference LVI, Hyperwave API Functions

  • Reference XLII, Firebird/InterBase Functions

  • Reference LVIII, IBM DB2, Cloudscape and Apache Derby Functions

  • Reference LXVI, Informix Functions

  • Reference LXV, IMAP, POP3 and NNTP Functions

  • Reference LXVIII, Ingres II Functions

  • Reference LXIX, IRC Gateway Functions

  • Reference LXX, PHP / Java Integration

  • Reference LXXIII, LDAP Functions

  • Reference LXXIV, libxml Functions

  • Reference LXXX, MaxDB PHP Extension

  • Reference LXXXI, MCAL Functions

  • Reference LXXXII, Mcrypt Encryption Functions

  • Reference LXXXIV, Memcache Functions

  • Reference LXXXV, Mhash Functions

  • Reference LXXXVII, Ming functions for Flash

  • Reference LXXXIX, mnoGoSearch Functions

  • Reference XCII, Mohawk Software Session Handler Functions

  • Reference XCIII, mSQL Functions

  • Reference XC, Microsoft SQL Server Functions

  • Reference XCV, muscat Functions

  • Reference XCVI, MySQL Functions

  • Reference XCVIII, MySQL Improved Extension

  • Reference XCIX, Ncurses Terminal Screen Control Functions

  • Reference CI, Newt Functions

  • Reference CV, Oracle Functions

  • Reference CVIII, oggvorbis

  • Reference CIX, OpenAL Audio Bindings

  • Reference CX, OpenSSL Functions

  • Reference CXI, Oracle Functions [deprecated]

  • Reference CXIV, Ovrimos SQL Functions

  • Reference CXV, Paradox File Access

  • Reference CXIX, PDF Functions

  • Reference XCI, Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

  • Reference XLIII, Firebird/Interbase Functions (PDO_FIREBIRD)

  • Reference LXVII, Informix Functions (PDO_INFORMIX)

  • Reference XCVII, MySQL Functions (PDO_MYSQL)

  • Reference CXII, Oracle Functions (PDO_OCI)

  • Reference CVII, ODBC and DB2 Functions (PDO_ODBC)

  • Reference CXXVI, PostgreSQL Functions (PDO_PGSQL)

  • Reference CLXIX, Verisign Payflow Pro Functions

  • Reference CXXV, PostgreSQL Functions

  • Reference CXXIX, PostScript document creation

  • Reference CXXX, Pspell Functions

  • Reference CXXXI, qtdom Functions

  • Reference CXXXII, Radius

  • Reference CXXXIII, Rar Functions

  • Reference CXXXIV, GNU Readline

  • Reference CXXXV, GNU Recode Functions

  • Reference CXLVI, PostgreSQL Session Save Handler

  • Reference CXLIX, SimpleXML functions

  • Reference CL, SNMP Functions

  • Reference CLI, SOAP Functions

  • Reference CLVI, Secure Shell2 Functions

  • Reference CLX, Shockwave Flash Functions

  • Reference CLXII, Sybase Functions

  • Reference CLXIV, Tidy Functions

  • Reference CLXVI, Unicode Functions

  • Reference CVI, ODBC Functions (Unified)

  • Reference CLXX, vpopmail Functions

  • Reference CLXXII, WDDX Functions

  • Reference CLXXV, xattr Functions

  • Reference CLXXVI, xdiff Functions

  • Reference CLXXVII, XML Parser Functions

  • Reference CLXXIX, XMLReader functions

  • Reference CLXXXI, XSL functions

  • Reference CLXXXII, XSLT Functions

  • Reference CLXXXIII, YAZ Functions

PECL Extensions

These extensions are available from PECL. More PECL extensions exist but they are not documented in the PHP manual yet.

  • Reference III, Alternative PHP Cache

  • Reference IV, Advanced PHP debugger

  • Reference VIII, PHP bytecode Compiler

  • Reference XIII, Classkit Functions

  • Reference XIV, ClibPDF Functions

  • Reference XVI, Crack Functions

  • Reference XIX, Cybercash Payment Functions

  • Reference XX, Credit Mutuel CyberMUT functions

  • Reference XXI, Cyrus IMAP administration Functions

  • Reference XXIII, DB++ Functions

  • Reference XXVII, dbx Functions

  • Reference XXVIII, Direct IO Functions

  • Reference XXXI, DOM XML Functions

  • Reference XXXII, enchant Functions

  • Reference XXXV, Expect Functions

  • Reference XXXVI, File Alteration Monitor Functions

  • Reference XXXVIII, Fileinfo Functions

  • Reference XXXIX, filePro Functions

  • Reference XLI, Filter Functions

  • Reference XLIV, FriBiDi Functions

  • Reference XLVIII, GeoIP Functions

  • Reference LI, gnupg Functions

  • Reference LIII, hash Functions

  • Reference LIV, HTTP

  • Reference LV, Hyperwave Functions

  • Reference LVI, Hyperwave API Functions

  • Reference LVIII, IBM DB2, Cloudscape and Apache Derby Functions

  • Reference LXI, ID3 Functions

  • Reference LXII, IIS Administration Functions

  • Reference LXVIII, Ingres II Functions

  • Reference LXIX, IRC Gateway Functions

  • Reference LXX, PHP / Java Integration

  • Reference LXXI, JSON Functions

  • Reference LXXII, KADM5

  • Reference LXXVI, LZF Functions

  • Reference LXXVIII, mailparse Functions

  • Reference LXXX, MaxDB PHP Extension

  • Reference LXXXI, MCAL Functions

  • Reference LXXXIII, MCVE (Monetra) Payment Functions

  • Reference LXXXIV, Memcache Functions

  • Reference LXXXIX, mnoGoSearch Functions

  • Reference XCII, Mohawk Software Session Handler Functions

  • Reference XCV, muscat Functions

  • Reference XCIX, Ncurses Terminal Screen Control Functions

  • Reference LII, Net_Gopher

  • Reference CI, Newt Functions

  • Reference CLXXXIV, YP/NIS Functions

  • Reference LXXV, Lotus Notes Functions

  • Reference CVIII, oggvorbis

  • Reference CIX, OpenAL Audio Bindings

  • Reference CXI, Oracle Functions [deprecated]

  • Reference CXIV, Ovrimos SQL Functions

  • Reference CXV, Paradox File Access

  • Reference CXVI, Parsekit Functions

  • Reference CXIX, PDF Functions

  • Reference CXX, PDO Functions

  • Reference XCI, Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

  • Reference XLIII, Firebird/Interbase Functions (PDO_FIREBIRD)

  • Reference LXVII, Informix Functions (PDO_INFORMIX)

  • Reference XCVII, MySQL Functions (PDO_MYSQL)

  • Reference CXII, Oracle Functions (PDO_OCI)

  • Reference CVII, ODBC and DB2 Functions (PDO_ODBC)

  • Reference CXXVI, PostgreSQL Functions (PDO_PGSQL)

  • Reference CLV, SQLite Functions (PDO_SQLITE)

  • Reference CLXIX, Verisign Payflow Pro Functions

  • Reference CXXVII, Printer Functions

  • Reference CXXIX, PostScript document creation

  • Reference CXXXI, qtdom Functions

  • Reference CXXXII, Radius

  • Reference CXXXIII, Rar Functions

  • Reference CXXXVI, RPM Header Reading Functions

  • Reference CXXXVII, runkit Functions

  • Reference CXLI, SDO Functions

  • Reference CXLII, SDO XML Data Access Service Functions

  • Reference CXLIII, SDO Relational Data Access Service Functions

  • Reference CXLVI, PostgreSQL Session Save Handler

  • Reference CLVI, Secure Shell2 Functions

  • Reference CLVII, Statistics Functions

  • Reference CLX, Shockwave Flash Functions

  • Reference CLXIII, TCP Wrappers Functions

  • Reference CLXIV, Tidy Functions

  • Reference CLXX, vpopmail Functions

  • Reference CLXXI, W32api Functions

  • Reference CLXXIII, win32ps Functions

  • Reference CLXXIV, win32service Functions

  • Reference CLXXV, xattr Functions

  • Reference CLXXVI, xdiff Functions

  • Reference CLXXIX, XMLReader functions

  • Reference CLXXX, XMLWriter Functions

  • Reference CLXXXIII, YAZ Functions

  • Reference CLXXXV, Zip File Functions

Prev | Home | Next
Extension Categorization | Up | State


State

This part lists extensions not intended for the production use - they are either too "old" (deprecated) or "new" (experimental).

Deprecated Extensions

These extensions have been deprecated usually in the favor of some other extensions.

  • Reference VI, Aspell functions [deprecated]

  • Reference XI, CCVS API Functions [deprecated]

  • Reference XXVI, DBM Functions [deprecated]

  • Reference LIX, ICAP Functions [removed]

  • Reference LXXXVI, Mimetype Functions

  • Reference CXI, Oracle Functions [deprecated]

  • Reference CIV, Object property and method call overloading

  • Reference CXXXIX, Satellite CORBA client extension [deprecated]

  • Reference CXLV, SESAM Database Functions

Experimental Extensions

The behaviour of these extensions - including the names of their functions and anything else documented about these extensions - may change without notice in a future release of PHP. Use these extensions at your own risk.

  • Reference I, .NET Functions

  • Reference XLI, Filter Functions

  • Reference LIII, hash Functions

  • Reference LXX, PHP / Java Integration

  • Reference LXXVIII, mailparse Functions

  • Reference XCV, muscat Functions

  • Reference CI, Newt Functions

  • Reference CIII, Object Aggregation/Composition Functions

  • Reference CXLI, SDO Functions

  • Reference CXLII, SDO XML Data Access Service Functions

  • Reference CXLIII, SDO Relational Data Access Service Functions

  • Reference CLXX, vpopmail Functions

Prev | Home | Next
Membership | Up | List of Function Aliases


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

Version | Description
3.0.11 | The limited parameter was introduced.

Examples

Example 1. A apc_cache_info() example

&#60;?php
print_r(apc_cache_info());
?&#62;

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)
)

See Also

APC configuration directives

Prev | Home | Next
Alternative PHP Cache | Up | apc_clear_cache


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.

Prev | Home | Next
apc_cache_info | Up | apc_define_constants


apc_define_constants

(PECL)

apc_define_constants -- Defines a set of constants for later 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.

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

&#60;?php
$constants = array(
    'ONE'   =&#62; 1,
    'TWO'   =&#62; 2,
    'THREE' =&#62; 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?&#62;

The above example will output:

123

See Also

apc_load_constants()
define()
constant()
Or the PHP constants reference

Prev | Home | Next
apc_clear_cache | Up | apc_delete


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

&#60;?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?&#62;

See Also

apc_store()
apc_fetch()

Prev | Home | Next
apc_define_constants | Up | apc_fetch


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

&#60;?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?&#62;

The above example will output:

string(3) "BAR"

See Also

apc_store()
apc_delete()

Prev | Home | Next
apc_delete | Up | apc_load_constants


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

&#60;?php
$constants = array(
    'ONE'   =&#62; 1,
    'TWO'   =&#62; 2,
    'THREE' =&#62; 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?&#62;

The above example will output:

123

See Also

apc_define_constants()
define()
constant()
Or the PHP constants reference

Prev | Home | Next
apc_fetch | Up | apc_sma_info


apc_sma_info

(PECL)

apc_sma_info -- Retrieves APC's Shared Memory Allocation information

Description

array apc_sma_info ( void )

Return Values

Array of Shared Memory Allocation data; FALSE on failure.

Examples

Example 1. A apc_sma_info() example

&#60;?php
print_r(apc_sma_info());
?&#62;

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
                        )

                )

        )

)

See Also

APC configuration directives

Prev | Home | Next
apc_load_constants | Up | apc_store


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

&#60;?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?&#62;

The above example will output:

string(3) "BAR"

See Also

apc_fetch()
apc_delete()

Prev | Home | Next
apc_sma_info | Up | Advanced PHP debugger


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 )

array_fill_keys() fills an array with the value of the value parameter, using the values of the keys array as keys.

Example 1. array_fill_keys() example

&#60;?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?&#62;

$a now is:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

See also array_fill() and array_combine().

Prev | Home | Next
array_diff | Up | array_fill


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

&#60;?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?&#62;

The above example will output:

product(a) = 384

Prev | Home | Next
array_pop | Up | array_push


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 webpage

&#60;?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL =&#62; 'http://www.example.com/',
                 CURLOPT_HEADER =&#62; 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);
?&#62;

Prior to PHP 5.1.4 you can simulate this function with:

Example 2. Our own implementation of curl_setopt_array()

&#60;?php
if (!function_exists('curl_setopt_array')) {
   function curl_setopt_array(&#38;$ch, $curl_options)
   {
       foreach ($curl_options as $option =&#62; $value) {
           if (!curl_setopt($ch, $option, $value)) {
               return false;
           }
       }
       return true;
   }
}
?&#62;

See Also

curl_setopt()

Prev | Home | Next
curl_multi_select | Up | curl_setopt


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.

See Also

cybermut_testmac()
cybermut_creerreponsecm()

Prev | Home | Next
Credit Mutuel CyberMUT functions | Up | cybermut_creerreponsecm


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.

See Also

cybermut_creerformulairecm()
cybermut_testmac()

Prev | Home | Next
cybermut_creerformulairecm | Up | cybermut_testmac


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.

See Also

cybermut_creerformulairecm()
cybermut_creerreponsecm()

Prev | Home | Next
cybermut_creerreponsecm | Up | Cyrus IMAP administration Functions


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.

Prev | Home | Next
checkdate | Up | date_date_set


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.

See Also

date_isodate_set()
date_time_set()

Prev | Home | Next
date_create | Up | date_default_timezone_get


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.

See Also

date_default_timezone_set()

Prev | Home | Next
date_date_set | Up | date_default_timezone_set


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 H.

Return Values

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

ChangeLog

Version | Description
5.1.2 | The function started to validate the timezone_identifier parameter.

See Also

date_default_timezone_get()

Prev | Home | Next
date_default_timezone_get | Up | date_format


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()

Prev | Home | Next
date_default_timezone_set | Up | date_isodate_set


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()

Prev | Home | Next
date_format | Up | date_modify


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

&#60;?php
$date = new DateTime("2006-12-12");
$date-&#62;modify("+1 day");
echo $date-&#62;format("Y-m-d");
?&#62;

The above example will output:

2006-12-13

See Also

strtotime()

Prev | Home | Next
date_isodate_set | Up | date_offset_get


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.

Prev | Home | Next
date_modify | Up | date_parse


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

&#60;?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?&#62;

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()

Prev | Home | Next
date_offset_get | Up | date_sun_info


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

&#60;?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key =&#62; $val) {
    echo "$key: " . date("H:i:s", $val) . "\n";
}
?&#62;

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

Prev | Home | Next
date_parse | Up | 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()

Prev | Home | Next
date_sunset | Up | date_timezone_get


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.

Prev | Home | Next
date_time_set | Up | date_timezone_set


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.

Prev | Home | Next
date_timezone_get | Up | date


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 name | Return type | Description
APPL_CODEPAGE | int | The application code page.
CONN_CODEPAGE | int | The code page for the current connection.
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database.
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51".
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
ODBC_SQL_CONFORMANCE string The level of ODBC SQL grammar supported by the client:

MINIMUM

Supports the minimum ODBC SQL grammar.

CORE

Supports the core ODBC SQL grammar.

EXTENDED

Supports extended ODBC SQL grammar.

ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000".

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().

&#60;?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
    echo "DRIVER_NAME: ";         var_dump( $client-&#62;DRIVER_NAME );
    echo "DRIVER_VER: ";         var_dump( $client-&#62;DRIVER_VER );
    echo "DATA_SOURCE_NAME: ";         var_dump( $client-&#62;DATA_SOURCE_NAME );
    echo "DRIVER_ODBC_VER: ";         var_dump( $client-&#62;DRIVER_ODBC_VER );
    echo "ODBC_VER: ";             var_dump( $client-&#62;ODBC_VER );
    echo "ODBC_SQL_CONFORMANCE: ";     var_dump( $client-&#62;ODBC_SQL_CONFORMANCE );
    echo "APPL_CODEPAGE: ";         var_dump( $client-&#62;APPL_CODEPAGE );
    echo "CONN_CODEPAGE: ";         var_dump( $client-&#62;CONN_CODEPAGE );
}
else {
    echo "Error retrieving client information.
     Perhaps your database connection was invalid.";
}
db2_close($conn);

?&#62;

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)

See Also

db2_server_info()

Prev | Home | Next
db2_bind_param | Up | db2_close


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.

&#60;?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]);
}
?&#62;

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.

&#60;?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' =&#62; 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;
}
?&#62;

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

db2_fetch_assoc()
db2_fetch_both()
db2_fetch_object()
db2_fetch_row()
db2_result()

Prev | Home | Next
db2_execute | Up | db2_fetch_assoc


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".

&#60;?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-&#62;NAME}, my little {$pet-&#62;BREED}!";
    }
    db2_close($conn);
}
?&#62;

The above example will output:

Come here, Pook, my little cat!

See Also

db2_fetch_array()
db2_fetch_assoc()
db2_fetch_both()
db2_fetch_row()
db2_result()

Prev | Home | Next
db2_fetch_both | Up | db2_fetch_row


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 name | Return type | Description
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running.
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
DB_CODEPAGE | int | The code page of the database to which you are connected.
DB_NAME | string | The name of the database to which you are connected.
DFT_ISOLATION string The default transaction isolation level supported by the server:

UR

Uncommitted read: changes are immediately visible by all concurrent transactions.

CS

Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction.

RS

Read stability: a transaction can add or remove rows matching a search condition or a pending transaction.

RR

Repeatable read: data affected by pending transaction is not available to other transactions.

NC

No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.

IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier.
INST_NAME | string | The instance on the database server that contains the database.
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDS | array | An array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSE | bool | TRUE if the database server supports the use of % and _ wildcard characters. FALSE if the database server does not support these wildcard characters.
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNS | bool | TRUE if the database server supports columns that can be defined as NOT NULL, FALSE if the database server does not support columns defined as NOT NULL.
PROCEDURES | bool | TRUE if the database server supports the use of the CALL statement to call stored procedures, FALSE if the database server does not support the CALL statement.
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCE string The level of conformance to the ANSI/ISO SQL-92 specification offered by the database server:

ENTRY

Entry-level SQL-92 compliance.

FIPS127

FIPS-127-2 transitional compliance.

FULL

Full level SQL-92 compliance.

INTERMEDIATE

Intermediate level SQL-92 compliance.

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().

&#60;?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
    echo "DBMS_NAME: ";                 var_dump( $server-&#62;DBMS_NAME );
    echo "DBMS_VER: ";                  var_dump( $server-&#62;DBMS_VER );
    echo "DB_CODEPAGE: ";               var_dump( $server-&#62;DB_CODEPAGE );
    echo "DB_NAME: ";                   var_dump( $server-&#62;DB_NAME );
    echo "INST_NAME: ";                 var_dump( $server-&#62;INST_NAME );
    echo "SPECIAL_CHARS: ";             var_dump( $server-&#62;SPECIAL_CHARS );
    echo "KEYWORDS: ";                  var_dump( sizeof($server-&#62;KEYWORDS) );
    echo "DFT_ISOLATION: ";             var_dump( $server-&#62;DFT_ISOLATION );
    echo "ISOLATION_OPTION: ";
    $il = '';
    foreach( $server-&#62;ISOLATION_OPTION as $opt )
    {
       $il .= $opt." ";
    }
    var_dump( $il );
    echo "SQL_CONFORMANCE: ";           var_dump( $server-&#62;SQL_CONFORMANCE );
    echo "PROCEDURES: ";                var_dump( $server-&#62;PROCEDURES );
    echo "IDENTIFIER_QUOTE_CHAR: ";     var_dump( $server-&#62;IDENTIFIER_QUOTE_CHAR );
    echo "LIKE_ESCAPE_CLAUSE: ";        var_dump( $server-&#62;LIKE_ESCAPE_CLAUSE );
    echo "MAX_COL_NAME_LEN: ";          var_dump( $server-&#62;MAX_COL_NAME_LEN );
    echo "MAX_ROW_SIZE: ";              var_dump( $server-&#62;MAX_ROW_SIZE );
    echo "MAX_IDENTIFIER_LEN: ";        var_dump( $server-&#62;MAX_IDENTIFIER_LEN );
    echo "MAX_INDEX_SIZE: ";            var_dump( $server-&#62;MAX_INDEX_SIZE );
    echo "MAX_PROC_NAME_LEN: ";         var_dump( $server-&#62;MAX_PROC_NAME_LEN );
    echo "MAX_SCHEMA_NAME_LEN: ";       var_dump( $server-&#62;MAX_SCHEMA_NAME_LEN );
    echo "MAX_STATEMENT_LEN: ";         var_dump( $server-&#62;MAX_STATEMENT_LEN );
    echo "MAX_TABLE_NAME_LEN: ";        var_dump( $server-&#62;MAX_TABLE_NAME_LEN );
    echo "NON_NULLABLE_COLUMNS: ";      var_dump( $server-&#62;NON_NULLABLE_COLUMNS );

    db2_close($conn);
}
?&#62;

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)

See Also

db2_client_info()

Prev | Home | Next
db2_rollback | Up | db2_set_option


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.

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.

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

Key | Value | Resource Type
 |  | Connection | Statement | Result Set
autocommit | DB2_AUTOCOMMIT_ON | X | - | -
autocommit | DB2_AUTOCOMMIT_OFF | X | - | -
cursor | DB2_SCROLLABLE | X | X | -
cursor | DB2_FORWARD_ONLY | X | X | -
binmode | DB2_BINARY | X | X | -
binmode | DB2_CONVERT | X | X | -
binmode | DB2_PASSTHRU | X | X | -
db2_attr_case | DB2_CASE_LOWER | X | X | -
db2_attr_case | DB2_CASE_UPPER | X | X | -
db2_attr_case | DB2_CASE_NATURAL | X | X | -
i5_fetch_only | DB2_I5_FETCH_ON | - | X | -
i5_fetch_only | DB2_I5_FETCH_OFF | - | X | -

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Setting one parameter with a connection resource

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_ON);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Options Set Successfully

Example 2. Setting multiple parameters with a connection resource

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_OFF,
                    'binmode' =&#62; DB2_PASSTHRU,
              'db2_attr_case' =&#62; DB2_CASE_UPPER,
                       'cursor' =&#62; DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Options Set Successfully

Example 3. Setting multiple parameters with an invalid key

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_OFF,
             'MY_INVALID_KEY' =&#62; DB2_PASSTHRU,
              'db2_attr_case' =&#62; DB2_CASE_UPPER,
                     'cursor' =&#62; DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Could Not Set Options

Example 4. Setting multiple parameters with an invalid value

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_OFF,
                     'binmode' =&#62; 'INVALID_VALUE',
              'db2_attr_case' =&#62; DB2_CASE_UPPER,
                       'cursor' =&#62; DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Could Not Set Options

Example 5. Setting multiple parameters with a connection resource and the wrong type

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_OFF,
                     'binmode' =&#62; DB2_PASSTHRU,
              'db2_attr_case' =&#62; DB2_CASE_UPPER,
                       'cursor' =&#62; DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Could Not Set Options

Example 6. Setting multiple parameters with the wrong resource

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' =&#62; DB2_AUTOCOMMIT_OFF,
                     'binmode' =&#62; DB2_PASSTHRU,
              'db2_attr_case' =&#62; DB2_CASE_UPPER,
                     'cursor' =&#62; DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');

/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?&#62;

The above example will output:

Could Not Set Options

Example 7. Putting it all together

&#60;?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' =&#62; DB2_CASE_LOWER,
                        'cursor' =&#62; DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');

/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));

/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '&#60;br /&#62;&#60;br /&#62;';
print_r(db2_fetch_assoc($stmt, 1));

?&#62;

The above example will output:

Array
(
    [empno] => 000140
    [firstnme] => HEATHER
    [midinit] => A
    [lastname] => NICHOLLS
    [workdept] => C01
    [phoneno] => 1793
    [hiredate] => 1976-12-15
    [job] => ANALYST
    [edlevel] => 18
    [sex] => F
    [birthdate] => 1946-01-19
    [salary] => 28420.00
    [bonus] => 600.00
    [comm] => 2274.00
)

Array
(
    [empno] => 000130
    [firstnme] => DELORES
    [midinit] => M
    [lastname] => QUINTANA
    [workdept] => C01
    [phoneno] => 4578
    [hiredate] => 1971-07-28
    [job] => ANALYST
    [edlevel] => 16
    [sex] => F
    [birthdate] => 1925-09-15
    [salary] => 23800.00
    [bonus] => 500.00
    [comm] => 1904.00
)

Example 8. i5/OS cursors are read-only

&#60;?php
  $conn = db2_connect("", "", "", array("i5_lib"=&#62;"nobody"));
  $stmt = db2_prepare($conn, 'select * from names where first = ?');
  $name = "first2";
  db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
  $options = array("i5_fetch_only"=&#62;DB2_I5_FETCH_ON);
  db2_set_option($stmt,$options,0);
  if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
      echo "{$row[0]} {$row[1]}";
    }
  }
?&#62;

The above example will output:

first2 last2

See Also

db2_connect()
db2_pconnect()
db2_exec()
db2_prepare()
db2_cursor_type()

Prev | Home | Next
db2_server_info | Up | db2_special_columns


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.

See Also

The DOM Specification
DOMNode->normalize()

Prev | Home | Next
DOMDocument->loadXML() | Up | DOMDocument->registerNodeClass()


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.

Examples

Example 1. Adding a new method to DOMElement to ease our code

&#60;?php

class myElement extends DOMElement {
   function appendElement($name) {
      return $this-&#62;appendChild(new myElement($name));
   }
}

class myDocument extends DOMDocument {
   function setRoot($name) {
      return $this-&#62;appendChild(new myElement($name));
   }
}

$doc = new myDocument();
$doc-&#62;registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc-&#62;setRoot('root');
$child = $root-&#62;appendElement('child');
$child-&#62;setAttribute('foo', 'bar');

echo $doc-&#62;saveXML();

?&#62;

The above example will output:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Prev | Home | Next
DOMDocument->normalizeDocument() | Up | DOMDocument->relaxNGValidate()


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

&#60;?php
$doc = new DOMDocument();
$doc-&#62;loadXML("&#60;root/&#62;");
$f = $doc-&#62;createDocumentFragment();
$f-&#62;appendXML("&#60;foo&#62;text&#60;/foo&#62;&#60;bar&#62;text2&#60;/bar&#62;");
$doc-&#62;documentElement-&#62;appendChild($f);
echo $doc-&#62;saveXML();
?&#62;

The above example will output:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

Prev | Home | Next
DOMDocument->xinclude() | Up | DOMElement->__construct()


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.

See Also

DOMDocument->getElementById()
DOMElement->setIdAttributeNode()
DOMElement->setIdAttributeNS()

Prev | Home | Next
DOMElement->setAttributeNS() | Up | DOMElement->setIdAttributeNode()


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.

See Also

DOMDocument->getElementById()
DOMElement->setIdAttribute()
DOMElement->setIdAttributeNS()

Prev | Home | Next
DOMElement->setIdAttribute() | Up | DOMElement->setIdAttributeNS()


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.

See Also

DOMDocument->getElementById()
DOMElement->setIdAttribute()
DOMElement->setIdAttributeNode()

Prev | Home | Next
DOMElement->setIdAttributeNode() | Up | DOMEntityReference->__construct()


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.

Prev | Home | Next
DOMNode->insertBefore() | Up | DOMNode->isSameNode()


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.

See Also

DomAttribute->value

Prev | Home | Next
DomAttribute->name | Up | DomAttribute->specified


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.

Prev | Home | Next
DomElement->remove_attribute() | Up | DomElement->set_attribute()


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

&#60;?php

echo domxml_xslt_version();

?&#62;

The above example will output something similar to:

10112

See Also

domxml_version()

Prev | Home | Next
domxml_xslt_stylesheet | Up | xpath_eval_expression


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

&#60;?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

?&#62;

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
        )

)

Prev | Home | Next
enchant Functions | Up | enchant_broker_dict_exists


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

&#60;?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    echo $tag . " dictionary found.\n";
}
?&#62;

See Also

enchant_broker_describe()

Prev | Home | Next
enchant_broker_describe | Up | enchant_broker_free_dict


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.

See Also

enchant_broker_init()

Prev | Home | Next
enchant_broker_free_dict | Up | enchant_broker_get_error


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.

See Also

enchant_broker_request_dict()
enchant_broker_request_pwl_dict()

Prev | Home | Next
enchant_broker_dict_exists | Up | enchant_broker_free


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

Prev | Home | Next
enchant_broker_free | Up | enchant_broker_init


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.

See Also

enchant_broker_free()

Prev | Home | Next
enchant_broker_get_error | Up | enchant_broker_list_dicts


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

&#60;?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?&#62;

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 ()

Prev | Home | Next
enchant_broker_init | Up | enchant_broker_request_dict


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.

&#60;?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
}
?&#62;

See Also

enchant_dict_describe()
enchant_broker_dict_exists()
enchant_broker_dict_free()

Prev | Home | Next
enchant_broker_list_dicts | Up | enchant_broker_request_pwl_dict


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()

Prev | Home | Next
enchant_broker_request_dict | Up | enchant_broker_set_ordering


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.

Prev | Home | Next
enchant_broker_request_pwl_dict | Up | enchant_dict_add_to_personal


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.

See Also

enchant_broker_request_pwl_dict()
enchant_broker_request_dict()

Prev | Home | Next
enchant_broker_set_ordering | Up | enchant_dict_add_to_session


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.

See Also

enchant_broker_request_dict()

Prev | Home | Next
enchant_dict_add_to_personal | Up | enchant_dict_check


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.

Prev | Home | Next
enchant_dict_add_to_session | Up | enchant_dict_describe


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.

&#60;?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);
}
?&#62;

The above example will output something similar to:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

Prev | Home | Next
enchant_dict_check | Up | enchant_dict_get_error


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.

Prev | Home | Next
enchant_dict_describe | Up | enchant_dict_is_in_session


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

See Also

enchant_dict_add_to_session()

Prev | Home | Next
enchant_dict_get_error | Up | enchant_dict_quick_check


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

&#60;?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);
}
?&#62;

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
)

See Also

enchant_dict_check()
enchant_dict_suggest()

Prev | Home | Next
enchant_dict_is_in_session | Up | enchant_dict_store_replacement


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.

Prev | Home | Next
enchant_dict_quick_check | Up | enchant_dict_suggest


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

&#60;?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);
?&#62;

See Also

enchant_dict_check()
enchant_dict_quick_check()

Prev | Home | Next
enchant_dict_store_replacement | Up | Error Handling and Logging Functions


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

&#60;?php
echo $a;
print_r(error_get_last());
?&#62;

The above example will output something similar to:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

See Also

Error constants
Variable $php_errormsg
Directive display_errors

Prev | Home | Next
debug_print_backtrace | Up | error_log


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

mixed 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 Key | Value Type | Description | Is Mandatory | Default Value
0 | string | pattern, that will be matched against the output from the stream | yes
1 | mixed | value, that will be returned by this function, if the pattern matches | yes
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB

Return Values

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

ChangeLog

Version | Description
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

&#60;?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 =&#62; "password:", 1 =&#62; PASSWORD),
  array (0 =&#62; "yes/no)?", 1 =&#62; 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);
?&#62;

See Also

expect_popen()

Prev | Home | Next
Expect Functions | Up | 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

&#60;?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);
?&#62;

See Also

popen()

Prev | Home | Next
expect_expectl | Up | File Alteration Monitor Functions


fbsql_rows_fetched

(PHP 5 >= 5.1.0RC1)

fbsql_rows_fetched --

Description

int fbsql_rows_fetched ( [resource result] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
fbsql_rollback | Up | fbsql_select_db


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.

Prev | Home | Next
fbsql_select_db | Up | fbsql_set_lob_mode


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

&#60;?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i &#60; fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "&#60;br /&#62;";
    $i++;
}
?&#62;

Prev | Home | Next
fbsql_stop_db | Up | fbsql_tablename


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.

Prev | Home | Next
Filter Functions | Up | filter_id


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()

Prev | Home | Next
filter_has_var | Up | filter_input_array


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

&#60;?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 "&#60;a href='?search=$search_url'&#62;Search again.&#60;/a&#62;";
?&#62;

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>

See Also

filter_var()
filter_input_array()
filter_var_array()

Prev | Home | Next
filter_input_array | Up | 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

&#60;?php
error_reporting(E_ALL | E_STRICT);
/* data actually came from POST
$_POST = array(
    'product_id'    =&#62; 'libgd&#60;script&#62;',
    'component'     =&#62; '10',
    'versions'      =&#62; '2.0.33',
    'testscalar'    =&#62; array('2', '23', '10', '12'),
    'testarray'     =&#62; '2',
);
*/

$args = array(
    'product_id'   =&#62; FILTER_SANITIZE_ENCODED,
    'component'    =&#62; array('filter'    =&#62; FILTER_VALIDATE_INT,
                            'flags'     =&#62; FILTER_FLAG_ARRAY,
                            'options'   =&#62; array('min_range' =&#62; 1, 'max_range' =&#62; 10)
                           ),
    'versions'     =&#62; FILTER_SANITIZE_ENCODED,
    'doesnotexist' =&#62; FILTER_VALIDATE_INT,
    'testscalar'   =&#62; array(
                            'filter' =&#62; FILTER_VALIDATE_INT,
                            'flags'  =&#62; FILTER_FLAG_SCALAR,
                           ),
    'testarray'    =&#62; array(
                            'filter' =&#62; FILTER_VALIDATE_INT,
                            'flags'  =&#62; FILTER_FLAG_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?&#62;

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)
  }
}

See Also

filter_input()
filter_var_array()

Prev | Home | Next
filter_id | Up | filter_input


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

&#60;?php
print_r(filter_list());
?&#62;

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
)

Prev | Home | Next
filter_input | Up | filter_var_array


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

&#60;?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
?&#62;

The above example will output:

string(15) "bob@example.com"
bool(false)

See Also

filter_var_array()
filter_input()
filter_input_array()
information about the callback type

Prev | Home | Next
filter_var_array | Up | Firebird/InterBase Functions


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

&#60;?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'product_id'    =&#62; 'libgd&#60;script&#62;',
    'component'     =&#62; '10',
    'versions'      =&#62; '2.0.33',
    'testscalar'    =&#62; array('2', '23', '10', '12'),
    'testarray'     =&#62; '2',
);

$args = array(
    'product_id'   =&#62; FILTER_SANITIZE_ENCODED,
    'component'    =&#62; array('filter'    =&#62; FILTER_VALIDATE_INT,
                            'flags'     =&#62; FILTER_FORCE_ARRAY,
                            'options'   =&#62; array('min_range' =&#62; 1, 'max_range' =&#62; 10)
                           ),
    'versions'     =&#62; FILTER_SANITIZE_ENCODED,
    'doesnotexist' =&#62; FILTER_VALIDATE_INT,
    'testscalar'   =&#62; array(
                            'filter' =&#62; FILTER_VALIDATE_INT,
                            'flags'  =&#62; FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    =&#62; array(
                            'filter' =&#62; FILTER_VALIDATE_INT,
                            'flags'  =&#62; FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?&#62;

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)
  }
}

See Also

filter_input_array()
filter_var()
filter_input()

Prev | Home | Next
filter_list | Up | filter_var


finfo_buffer

(PECL)

finfo_buffer -- Return information about a string buffer

Description

string finfo_buffer ( resource finfo, string string [, int options] )

class finfo {

string buffer ( string string [, int options] )

}

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.

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

Examples

Example 1. A finfo_buffer() example

&#60;?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo-&#62;buffer($_POST["script"]) . "\n";
?&#62;

The above example will output something similar to:

application/x-sh

See Also

finfo_file()

Prev | Home | Next
Fileinfo Functions | Up | finfo_close


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.

Prev | Home | Next
finfo_buffer | Up | finfo_file


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 CLVIII, 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

&#60;?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);
?&#62;

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel

See Also

finfo_buffer()

Prev | Home | Next
finfo_close | Up | finfo_open


finfo_open

(PECL)

finfo_open -- Create a new fileinfo resource

Description

resource finfo_open ( [int options [, string arg]] )

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, MAGIC environment variable is used. If this variable is not set neither, /usr/share/misc/magic is used. .mime and/or .mgc is added if appropriate.

Return Values

Returns a magic database resource on success or FALSE on failure.

See Also

finfo_close()

Prev | Home | Next
finfo_file | Up | finfo_set_flags


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.

Prev | Home | Next
finfo_open | Up | filePro Functions


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.

&#60;?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?&#62;

The above example will output:

This host is located in: USA

See Also

geoip_country_code_by_name()
geoip_country_name_by_name()

Prev | Home | Next
geoip_country_code_by_name | Up | geoip_country_name_by_name


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.

&#60;?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?&#62;

The above example will output:

This host is located in: US

See Also

geoip_country_code3_by_name()
geoip_country_name_by_name()

Prev | Home | Next
GeoIP Functions | Up | geoip_country_code3_by_name


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.

&#60;?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?&#62;

The above example will output:

This host is located in: United States

See Also

geoip_country_code_by_name()
geoip_country_code3_by_name()

Prev | Home | Next
geoip_country_code3_by_name | Up | geoip_database_info


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.

&#60;?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?&#62;

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

Prev | Home | Next
geoip_country_name_by_name | Up | geoip_id_by_name


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.

&#60;?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';
}
?&#62;

The above example will output:

The connection type is corporate

Prev | Home | Next
geoip_database_info | Up | geoip_org_by_name


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.

&#60;?php
$org = geoip_country_code_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?&#62;

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

Prev | Home | Next
geoip_id_by_name | Up | geoip_record_by_name


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.

&#60;?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?&#62;

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
)

Prev | Home | Next
geoip_org_by_name | Up | geoip_region_by_name


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:

  • "country_code" -- Two letter country code (see geoip_country_code_by_name())

  • "region" -- The region code (ex: CA for California)

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.

&#60;?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?&#62;

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
)

Prev | Home | Next
geoip_record_by_name | Up | Gettext


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

&#60;?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";
?&#62;

The printout of the above program is:

11
-997

Prev | Home | Next
gmp_neg | Up | gmp_or


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

&#60;?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?&#62;

Example 2. OO gnupg_adddecryptkey() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?&#62;

Prev | Home | Next
gnupg Functions | Up | gnupg_addencryptkey


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

&#60;?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?&#62;

Example 2. OO gnupg_addencryptkey() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?&#62;

Prev | Home | Next
gnupg_adddecryptkey | Up | gnupg_addsignkey


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

&#60;?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?&#62;

Example 2. OO gnupg_addsignkey() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?&#62;

Prev | Home | Next
gnupg_addencryptkey | Up | gnupg_cleardecryptkeys


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

&#60;?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?&#62;

Example 2. OO gnupg_cleardecryptkeys() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; cleardecryptkeys();
?&#62;

Prev | Home | Next
gnupg_addsignkey | Up | gnupg_clearencryptkeys


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

&#60;?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?&#62;

Example 2. OO gnupg_clearencryptkeys() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; clearencryptkeys();
?&#62;

Prev | Home | Next
gnupg_cleardecryptkeys | Up | gnupg_clearsignkeys


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

&#60;?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?&#62;

Example 2. OO gnupg_clearsignkeys() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; clearsignkeys();
?&#62;

Prev | Home | Next
gnupg_clearencryptkeys | Up | gnupg_decrypt


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

&#60;?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?&#62;

Example 2. OO gnupg_encrypt() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -&#62; decrypt($encrypted_text);
echo $plain;
?&#62;

Prev | Home | Next
gnupg_clearsignkeys | Up | gnupg_decryptverify


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

&#60;?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?&#62;

Example 2. OO gnupg_decryptverify() example

&#60;?php
$plaintext = "";
$gpg = new gnupg();
$gpg -&#62; adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg -&#62; decryptverify($text,$plaintext);
print_r($info);
?&#62;

Prev | Home | Next
gnupg_decrypt | Up | gnupg_encrypt


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

&#60;?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?&#62;

Example 2. OO gnupg_encrypt() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg -&#62; encrypt("just a test");
echo $enc;
?&#62;

Prev | Home | Next
gnupg_decryptverify | Up | gnupg_encryptsign


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

&#60;?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?&#62;

Example 2. OO gnupg_encryptsign() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg -&#62; addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg -&#62; encryptsign("just a test");
echo $enc;
?&#62;

Prev | Home | Next
gnupg_encrypt | Up | gnupg_export


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

&#60;?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?&#62;

Example 2. OO gnupg_export() example

&#60;?php
$gpg = new gnupg();
$export = $gpg -&#62; export("8660281B6051D071D94B5B230549F9DC851566DC");
?&#62;

Prev | Home | Next
gnupg_encryptsign | Up | gnupg_geterror


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

&#60;?php
$res = gnupg_init();
echo gnupg_geterror($res);
?&#62;

Example 2. OO gnupg_geterror() example

&#60;?php
$gpg = new gnupg();
echo $gpg -&#62; geterror();
?&#62;

Prev | Home | Next
gnupg_export | Up | gnupg_getprotocol


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

&#60;?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?&#62;

Example 2. OO gnupg_getprotocol() example

&#60;?php
$gpg = new gnupg();
echo $gpg -&#62; getprotocol();
?&#62;

Prev | Home | Next
gnupg_geterror | Up | gnupg_import


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

&#60;?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?&#62;

Example 2. OO gnupg_import() example

&#60;?php
$gpg = new gnupg();
$info = $gpg -&#62; import($keydata);
print_r($info);
?&#62;

Prev | Home | Next
gnupg_getprotocol | Up | gnupg_keyinfo


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

&#60;?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?&#62;

Example 2. OO gnupg_keyinfo() example

&#60;?php
$gpg = new gnupg();
$info = $gpg -&#62; keyinfo("test");
print_r($info);
?&#62;

Prev | Home | Next
gnupg_import | Up | gnupg_setarmor


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

&#60;?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?&#62;

Example 2. OO gnupg_setarmor() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; setarmor(1); // enable armored output;
$gpg -&#62; setarmor(0); // disable armored output;
?&#62;

Prev | Home | Next
gnupg_keyinfo | Up | gnupg_seterrormode


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.

Examples

Example 1. Procedural gnupg_seterrormode() example

&#60;?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?&#62;

Example 2. OO gnupg_seterrormode() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?&#62;

Prev | Home | Next
gnupg_setarmor | Up | gnupg_setsignmode


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

&#60;?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?&#62;

Example 2. OO gnupg_setsignmode() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?&#62;

Prev | Home | Next
gnupg_seterrormode | Up | gnupg_sign


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

&#60;?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?&#62;

Example 2. OO gnupg_sign() example

&#60;?php
$gpg = new gnupg();
$gpg -&#62; setsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg -&#62; sign("just a test");
echo $signed;
?&#62;

Prev | Home | Next
gnupg_setsignmode | Up | gnupg_verify


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

&#60;?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);
?&#62;

Example 2. OO gnupg_verify() example

&#60;?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg -&#62; verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg -&#62; verify($signed_text,$signature);
print_r($info);
?&#62;

Prev | Home | Next
gnupg_sign | Up | Net_Gopher


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()

&#60;?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?&#62;

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
)

Prev | Home | Next
Net_Gopher | Up | hash Functions


gzdecode

(no version information, might be only in CVS)

gzdecode -- Decodes a gzip compressed string

Description

string gzdecode ( string data [, int length] )

This function returns a decoded version of the input data.

Parameters

data

The data to decode, encoded by gzencode().

length

The maximum length of data to decode.

Return Values

The decoded string, or FALSE if an error occurred.

See Also

gzencode()

Prev | Home | Next
gzcompress | Up | gzdeflate


__halt_compiler

(no version information, might be only in CVS)

__halt_compiler -- Halts the compiler execution

Description

void __halt_compiler ( void )

This function halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files. Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.

Note: __halt_compiler() can only be used from the outermost scope.

Examples

Example 1. A __halt_compiler() example

&#60;?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler();the installation data (eg. tar, gz, PHP, etc.)

Prev | Home | Next
get_browser | Up | highlight_file


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

&#60;?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?&#62;

The above example will output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

See Also

hash_file()
hash_hmac()
hash_init()

Prev | Home | Next
hash_update | Up | HTTP


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.

&#60;?php
print_r(hash_algos());
?&#62;

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
)

Prev | Home | Next
hash Functions | Up | hash_file


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()

&#60;?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');
?&#62;

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

hash()
hash_hmac_file()
hash_update_file()

Prev | Home | Next
hash_algos | Up | hash_final


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

&#60;?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?&#62;

The above example will output:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

See Also

hash_init()
hash_update()
hash_update_stream()
hash_update_file()

Prev | Home | Next
hash_file | Up | hash_hmac_file


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

&#60;?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?&#62;

The above example will output:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

See Also

hash()
hash_init()
hash_hmac_file()

Prev | Home | Next
hash_hmac_file | Up | hash_init


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

&#60;?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');
?&#62;

The above example will output:

7eb2b5c37443418fc77c136dd20e859c

See Also

hash_hmac()
hash_file()

Prev | Home | Next
hash_final | Up | hash_hmac


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

&#60;?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?&#62;

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

hash()
hash_file()
hash_hmac()
hash_hmac_file()

Prev | Home | Next
hash_hmac | Up | hash_update_file


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.

See Also

hash_init()
hash_update_file()
hash_update_stream()
hash_final()

Prev | Home | Next
hash_update_stream | Up | hash


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.

See Also

hash_init()
hash_update()
hash_update_stream()
hash_final()
hash()
hash_file()

Prev | Home | Next
hash_init | Up | hash_update_stream


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

&#60;?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);
?&#62;

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

hash_init()
hash_update()
hash_final()
hash()
hash_file()

Prev | Home | Next
hash_update_file | Up | hash_update


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.

Prev | Home | Next
http_match_request_header | Up | http_negotiate_charset


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.

Prev | Home | Next
http_throttle | Up | http_build_url


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

&#60;?php
echo http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
    array(
        "scheme" =&#62; "ftp",
        "host" =&#62; "ftp.example.com",
        "path" =&#62; "files/current/",
        "query" =&#62; "a=c"
    ),
    HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);
?&#62;

The above example will output:

ftp://ftp.example.com/pub/files/current/?a=b&a=c

Prev | Home | Next
http_build_str | Up | Hyperwave Functions


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.

Parameters

etag

Custom ETag

Return Values

Returns FALSE on failure, or exits with 304 Not Modified if the entity is cached.

Prev | Home | Next
HttpResponse::setThrottleDelay | Up | http_cache_last_modified


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.

Parameters

timestamp_or_expires

Unix timestamp

Return Values

Returns FALSE on failure, or exits with 304 Not Modified if the entity is cached.

Prev | Home | Next
http_cache_etag | Up | http_chunked_decode


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.

Prev | Home | Next
http_cache_last_modified | Up | http_deflate


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

Return Values

Returns the HTTP date as string.

Prev | Home | Next
http_get_request_headers | Up | http_support


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.

Prev | Home | Next
http_chunked_decode | Up | http_inflate


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.

The second parameter, if set, is expected to be an associative array where the following options will be recognized:

Table 1. HTTP request options

Name | Type | Description
redirect | int | whether and how many redirects to follow
unrestrictedauth | bool | whether to continue sending credentials on redirects to a different host
proxyhost | string | proxy host in "host[:port]" format
proxyport | int | use another proxy port as specified in proxyhost
proxytype | int | HTTP_PROXY_HTTP, HTTP_PROXY_SOCKS4 or HTTP_PROXY_SOCKS5
proxyauth | string | proxy credentials in "user:pass" format
proxyauthtype | int | HTTP_AUTH_BASIC and/or HTTP_AUTH_NTLM
httpauth | string | http credentials in "user:pass" format
httpauthtype | int | HTTP_AUTH_BASIC, HTTP_AUTH_DIGEST and/or HTTP_AUTH_NTLM
compress | bool | whether to allow gzip/deflate content encoding
port | int | use another port as specified in the url
referer | string | the referer to send
useragent | string | the user agent to send (defaults to PECL::HTTP/version (PHP/version))
headers | array | list of custom headers as associative array like array("header" => "value")
cookies | array | list of cookies as associative array like array("cookie" => "value")
encodecookies | bool | whether to urlencode the cookies (default: true)
cookiestore | string | path to a file where cookies are/will be stored
cookiesession | bool | don't load session cookies from cookiestore if TRUE
resume | int | byte offset to start the download from; if the server supports ranges
range | array | array of arrays, each containing two integers, specifying the ranges to download if server support is given; only recognized if the resume option is empty
maxfilesize | int | maximum file size that should be downloaded; has no effect, if the size of the requested entity is
lastmodified | int | timestamp for If-(Un)Modified-Since header
etag | string | quoted etag for If-(None-)Match header
timeout | int | seconds the request may take
connecttimeout | int | seconds the connect may take
onprogress | mixed | progress callback
interface | string | outgoing network interface (ifname, ip or hostname)
portrange | array | 2 integers specifying outgoing portrange to try
ssl array

Table 2. with the following options:

Name | Type | Description
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 |

Parameters

url

URL

options

HTTP request options

info

Will be filled with request/response information

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' => '',
)

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Prev | Home | Next
http_parse_params | Up | http_head


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.

Prev | Home | Next
http_get_request_body_stream | Up | http_get_request_headers


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.

Prev | Home | Next
http_inflate | Up | http_get_request_body


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.

Prev | Home | Next
http_get_request_body | Up | http_date


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 http_get() for a full list of available parameters and options.

Parameters

url

URL

options

Request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Prev | Home | Next
http_get | Up | http_post_data


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.

Prev | Home | Next
http_deflate | Up | http_get_request_body_stream


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.

Prev | Home | Next
http_support | Up | http_match_modified


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.

Prev | Home | Next
http_match_etag | Up | http_match_request_header


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.

Prev | Home | Next
http_match_modified | Up | http_build_cookie


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()

&#60;?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);
?&#62;

Prev | Home | Next
http_build_cookie | Up | http_negotiate_ctype


http_negotiate_ctype

(no version information, might be only in CVS)

http_negotiate_ctype -- Negotiate clients preferred content type

Description

string http_negotiate_ctype ( [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_ctype()

&#60;?php
$ctypes = array('application/xhtml+xml', 'text/html');
http_send_content_type(http_negotiate_content_type($ctypes));
?&#62;

Prev | Home | Next
http_negotiate_charset | Up | http_negotiate_language


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()

&#60;?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);
?&#62;

Prev | Home | Next
http_negotiate_ctype | Up | ob_deflatehandler


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

allowed_extras

Array containing recognized extra keys. By default all unknown keys will be treated as cookie names.

Return Values

Returns an stdClass like shown in the example on success or FALSE on failure.

Examples

Example 1. Using http_parse_cookie()

&#60;?php
print_r(http_parse_cookie("foo=bar; bar=baz; path=/; domain=example.com; comment=; secure", 0, array("comment")));
?&#62;

The above example will output:

stdClass Object
(
  [cookies] => Array
  (
    [foo] => bar
    [bar] => baz
  )

  [extras] => Array
  (
    [comment] =>
  )

  [flags] => 16
  [expires] => 0
  [path] => /
  [domain] => example.com
)

Prev | Home | Next
ob_inflatehandler | Up | http_parse_headers


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()

&#60;?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));
?&#62;

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
)

Prev | Home | Next
http_parse_cookie | Up | http_parse_message


http_parse_message

(PECL)

http_parse_message -- Parse the HTTP message

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

A hierarchical object structure of the parsed messages.

Examples

Example 1. Using http_parse_message()

&#60;?php
define ('URL', 'http://www.example.com/');
print_r(http_parse_message(http_get(URL, array('redirect' =&#62; 3))));
?&#62;

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] => ...
  )
)

Prev | Home | Next
http_parse_headers | Up | http_parse_params


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.

Prev | Home | Next
http_parse_message | Up | http_get


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_head | Up | http_post_fields


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_post_data | Up | http_put_data


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_post_fields | Up | http_put_file


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_put_data | Up | http_put_stream


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_put_file | Up | http_request_method_exists


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 on failure, or exits on success.

Prev | Home | Next
http_request_body_encode | Up | http_send_content_disposition


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
http_request_method_unregister | Up | http_request_body_encode


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

Prev | Home | Next
http_request | Up | http_redirect


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.

Prev | Home | Next
http_put_stream | Up | http_request_method_name


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.

Prev | Home | Next
http_request_method_exists | Up | http_request_method_register


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.

Prev | Home | Next
http_request_method_name | Up | http_request_method_unregister


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.

Prev | Home | Next
http_request_method_register | Up | http_request


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).

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.

Prev | Home | Next
http_redirect | Up | http_send_content_type


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. This is particularly important if you use the http_send() API.

Parameters

content_type

the desired content type (primary/secondary)

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
http_send_content_disposition | Up | http_send_data


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.

Prev | Home | Next
http_send_content_type | Up | http_send_file


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.

Parameters

file

the file to send

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
http_send_data | Up | http_send_last_modified


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.

Parameters

timestamp

a unix timestamp, converted it to a valid HTTP date; if omitted, the current time will be sent

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
http_send_file | Up | http_send_status


http_send_status

(PECL)

http_send_status -- Send status

Description

bool http_send_status ( int status )

Send HTTP status code.

Parameters

status

HTTP status code

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
http_send_last_modified | Up | http_send_stream


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.

Prev | Home | Next
http_send_status | Up | http_throttle


http_support

(no version information, might be only in CVS)

http_support -- Check builtin 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; if the parameter is 0 or omitted, the return value contains a bitmask of all supported features that depend on external libraries

Return Values

Returns int, whether requested feature is supported, or a bitmask with all supported features.

Prev | Home | Next
http_date | Up | http_match_etag


http_throttle

(PECL)

http_throttle -- HTTP throttling

Description

void http_throttle ( [double sec [, int bytes = 40960]] )

Sets the throttle delay and send buffer size for use with http_send() API. Provides a basic throttling mechanism, which will yield the current process resp. thread until the entity has been completely sent, though.

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.

&#60;?php
// ~ 20 kbyte/s
# http_throttle(1, 20000);
# http_throttle(0.5, 10000);
# http_throttle(0.1, 2000);
http_send_file('document.pdf');
?&#62;
?&#62;

Prev | Home | Next
http_send_stream | Up | http_build_str


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 arguments.

Parameters

flags

initialization flags

Prev | Home | Next
HttpDeflateStream | Up | HttpDeflateStream::update


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.

Prev | Home | Next
HttpDeflateStream::flush | Up | HttpInflateStream


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.

Prev | Home | Next
HttpDeflateStream::update | Up | HttpDeflateStream::finish


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.

Prev | Home | Next
HttpDeflateStream::__construct | Up | HttpDeflateStream::flush


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 arguments.

Parameters

flags

initialization flags

Prev | Home | Next
HttpInflateStream | Up | HttpInflateStream::update


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.

Prev | Home | Next
HttpInflateStream::flush | Up | HttpRequest


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.

Prev | Home | Next
HttpInflateStream::update | Up | HttpInflateStream::finish


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.

Prev | Home | Next
HttpInflateStream::__construct | Up | HttpInflateStream::flush


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.

Prev | Home | Next
HttpMessage::getHeader | Up | HttpMessage::setHeaders


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.

Prev | Home | Next
HttpMessage | Up | HttpMessage::fromString


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.

Prev | Home | Next
HttpMessage::guessContentType | Up | HttpMessage::prepend


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. Kind of a static constructor.

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.

Prev | Home | Next
HttpMessage::__construct | Up | HttpMessage::toString


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.

Prev | Home | Next
HttpMessage::setHeaders | Up | HttpMessage::setBody


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.

Prev | Home | Next
HttpMessage::getHeaders | Up | HttpMessage::addHeaders


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.

Prev | Home | Next
HttpMessage::setHttpVersion | Up | HttpMessage::getHeader


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.

Prev | Home | Next
HttpMessage::setType | Up | HttpMessage::setHttpVersion


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.

Prev | Home | Next
HttpMessage::send | Up | HttpMessage::getType


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.

Prev | Home | Next
HttpMessage::setBody | Up | HttpMessage::setRequestMethod


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.

Prev | Home | Next
HttpMessage::setRequestMethod | Up | HttpMessage::setRequestUrl


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.

Prev | Home | Next
HttpMessage::setRequestUrl | Up | HttpMessage::setResponseCode


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.

Prev | Home | Next
HttpMessage::setResponseCode | Up | HttpMessage::setResponseStatus


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.

Prev | Home | Next
HttpMessage::getParentMessage | Up | HttpMessage::setType


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.

Prev | Home | Next
HttpMessage::toMessageTypeObject | Up | HttpMessage::detach


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.

Prev | Home | Next
HttpMessage::detach | Up | HttpMessage::reverse


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.

Prev | Home | Next
HttpMessage::prepend | Up | HttpMessage::send


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.

Prev | Home | Next
HttpMessage::reverse | Up | HttpMessage::getParentMessage


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

Prev | Home | Next
HttpMessage::getBody | Up | HttpMessage::getRequestMethod


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

Prev | Home | Next
HttpMessage::addHeaders | Up | HttpMessage::getBody


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).

Prev | Home | Next
HttpMessage::getHttpVersion | Up | HttpMessage::getHeaders


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.

Prev | Home | Next
HttpMessage::getRequestMethod | Up | HttpMessage::getRequestUrl


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.

Prev | Home | Next
HttpMessage::getRequestUrl | Up | HttpMessage::getResponseCode


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).

Prev | Home | Next
HttpMessage::getResponseCode | Up | HttpMessage::getResponseStatus


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.

Prev | Home | Next
HttpMessage::getResponseStatus | Up | HttpQueryString


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

Prev | Home | Next
HttpMessage::getType | Up | HttpMessage::getHttpVersion


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.

Prev | Home | Next
HttpMessage::toString | Up | HttpMessage::guessContentType


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.

Prev | Home | Next
HttpMessage::fromString | Up | HttpMessage::toMessageTypeObject


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.

Prev | Home | Next
HttpQueryString | Up | HttpQueryString::singleton


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.

Prev | Home | Next
HttpQueryString::singleton | Up | HttpQueryString::mod


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

Prev | Home | Next
HttpQueryString::get | Up | HttpQueryString::set


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.

Prev | Home | Next
HttpQueryString::mod | Up | HttpQueryString::toArray


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.

Prev | Home | Next
HttpQueryString::__construct | Up | HttpQueryString::get


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.

Prev | Home | Next
HttpQueryString::set | Up | HttpQueryString::toString


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.

Prev | Home | Next
HttpQueryString::toArray | Up | HttpQueryString::xlate


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.

Prev | Home | Next
HttpQueryString::toString | Up | HttpDeflateStream


HttpRequest::addCookies

(no version information, might be only in CVS)

HttpRequest::addCookies -- Add cookies

Description

publicbool HttpRequest::addCookies ( array cookies )

Add cookies.

Parameters

cookies

an associative array as parameter containing any cookie name/value pairs to add

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpRequest | Up | HttpRequest::addHeaders


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.

Prev | Home | Next
HttpRequest::addCookies | Up | HttpRequest::addPostFields


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.

Prev | Home | Next
HttpRequest::addHeaders | Up | HttpRequest::addPostFile


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.

Prev | Home | Next
HttpRequest::addPostFields | Up | HttpRequest::addPutData


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.

Prev | Home | Next
HttpRequest::addPostFile | Up | HttpRequest::addQueryData


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.

Prev | Home | Next
HttpRequest::addPutData | Up | HttpRequest::addRawPostData


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.

Prev | Home | Next
HttpRequest::addQueryData | Up | HttpRequest::addSslOptions


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.

Prev | Home | Next
HttpRequest::addRawPostData | Up | HttpRequest::clearHistory


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.

Prev | Home | Next
HttpRequest::addSslOptions | Up | HttpRequest::__construct


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.

Prev | Home | Next
HttpRequest::clearHistory | Up | HttpRequest::enableCookies


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.

Prev | Home | Next
HttpRequest::__construct | Up | HttpRequest::getContentType


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.

Prev | Home | Next
HttpRequest::enableCookies | Up | HttpRequest::getCookies


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.

Prev | Home | Next
HttpRequest::getContentType | Up | HttpRequest::getHeaders


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.

Prev | Home | Next
HttpRequest::getCookies | Up | HttpRequest::getHistory


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.

Prev | Home | Next
HttpRequest::getHeaders | Up | HttpRequest::getMethod


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.

Prev | Home | Next
HttpRequest::getHistory | Up | HttpRequest::getOptions


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.

Prev | Home | Next
HttpRequest::getMethod | Up | HttpRequest::getPostFields


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.

Prev | Home | Next
HttpRequest::getOptions | Up | HttpRequest::getPostFiles


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.

Prev | Home | Next
HttpRequest::getPostFields | Up | HttpRequest::getPutData


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.

Prev | Home | Next
HttpRequest::getPostFiles | Up | HttpRequest::getPutFile


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.

Prev | Home | Next
HttpRequest::getPutData | Up | HttpRequest::getQueryData


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.

Prev | Home | Next
HttpRequest::getPutFile | Up | HttpRequest::getRawPostData


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.

Prev | Home | Next
HttpRequest::getQueryData | Up | HttpRequest::getRawRequestMessage


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.

Prev | Home | Next
HttpRequest::getRawPostData | Up | HttpRequest::getRawResponseMessage


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.

Prev | Home | Next
HttpRequest::getRawRequestMessage | Up | HttpRequest::getRequestMessage


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.

Prev | Home | Next
HttpRequest::getRawResponseMessage | Up | HttpRequest::getResponseBody


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.

Prev | Home | Next
HttpRequest::getRequestMessage | Up | HttpRequest::getResponseCode


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.

Prev | Home | Next
HttpRequest::getResponseBody | Up | HttpRequest::getResponseCookies


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.

Prev | Home | Next
HttpRequest::getResponseCode | Up | HttpRequest::getResponseData


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.

Prev | Home | Next
HttpRequest::getResponseCookies | Up | HttpRequest::getResponseHeader


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.

Prev | Home | Next
HttpRequest::getResponseData | Up | HttpRequest::getResponseInfo


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.

Prev | Home | Next
HttpRequest::getResponseHeader | Up | HttpRequest::getResponseMessage


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.

Prev | Home | Next
HttpRequest::getResponseInfo | Up | HttpRequest::getResponseStatus


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.

Prev | Home | Next
HttpRequest::getResponseMessage | Up | HttpRequest::getSslOptions


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.

Prev | Home | Next
HttpRequest::getResponseStatus | Up | HttpRequest::getUrl


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.

Prev | Home | Next
HttpRequest::getSslOptions | Up | HttpRequest::resetCookies


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.

Prev | Home | Next
HttpRequest::getUrl | Up | HttpRequest::send


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

&#60;?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r-&#62;setOptions(array('lastmodified' =&#62; filemtime('local.rss')));
$r-&#62;addQueryData(array('category' =&#62; 3));
try {
    $r-&#62;send();
    if ($r-&#62;getResponseCode() == 200) {
        file_put_contents('local.rss', $r-&#62;getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?&#62;

Example 2. POST example

&#60;?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r-&#62;setOptions(array('cookies' =&#62; array('lang' =&#62; 'de')));
$r-&#62;addPostFields(array('user' =&#62; 'mike', 'pass' =&#62; 's3c|r3t'));
$r-&#62;addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
    echo $r-&#62;send()-&#62;getBody();
} catch (HttpException $ex) {
    echo $ex;
}
?&#62;

Prev | Home | Next
HttpRequest::resetCookies | Up | HttpRequest::setContentType


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.

Prev | Home | Next
HttpRequest::send | Up | HttpRequest::setCookies


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.

Prev | Home | Next
HttpRequest::setContentType | Up | HttpRequest::setHeaders


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.

Prev | Home | Next
HttpRequest::setCookies | Up | HttpRequest::setMethod


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.

Prev | Home | Next
HttpRequest::setHeaders | Up | HttpRequest::setOptions


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 http_get() for a full list of available parameters and 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.

Prev | Home | Next
HttpRequest::setMethod | Up | HttpRequest::setPostFields


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 or omitted, the post data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpRequest::setOptions | Up | HttpRequest::setPostFiles


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 or omitted the post files will be unset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpRequest::setPostFields | Up | HttpRequest::setPutData


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.

Prev | Home | Next
HttpRequest::setPostFiles | Up | HttpRequest::setPutFile


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.

Prev | Home | Next
HttpRequest::setPutData | Up | HttpRequest::setQueryData


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 or omitted, the query data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpRequest::setPutFile | Up | HttpRequest::setRawPostData


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.

Prev | Home | Next
HttpRequest::setQueryData | Up | HttpRequest::setSslOptions


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.

Prev | Home | Next
HttpRequest::setRawPostData | Up | HttpRequest::setUrl


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.

Prev | Home | Next
HttpRequest::setSslOptions | Up | HttpRequestPool


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.

Prev | Home | Next
HttpRequestPool | Up | HttpRequestPool::__construct


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

&#60;?php
try {
    $pool = new HttpRequestPool(
        new HttpRequest('http://www.google.com/', HttpRequest::METH_HEAD),
        new HttpRequest('http://www.php.net/', HttpRequest::METH_HEAD)
    );
    $pool-&#62;send();
    foreach($pool as $request) {
        printf("%s is %s (%d)\n",
            $request-&#62;getUrl(),
            $request-&#62;getResponseCode() ? 'alive' : 'not alive',
            $request-&#62;getResponseCode()
        );
    }
} catch (HttpException $e) {
    echo $e;
}
?&#62;

Prev | Home | Next
HttpRequestPool::attach | Up | HttpRequestPool::__destruct


HttpRequestPool::__destruct

(no version information, might be only in CVS)

HttpRequestPool::__destruct -- HttpRequestPool destructor

Description

void HttpRequestPool::__destruct ( void )

Clean up HttpRequestPool object.

Prev | Home | Next
HttpRequestPool::__construct | Up | HttpRequestPool::detach


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.

Prev | Home | Next
HttpRequestPool::__destruct | Up | HttpRequestPool::getAttachedRequests


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.

Prev | Home | Next
HttpRequestPool::detach | Up | HttpRequestPool::getFinishedRequests


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.

Prev | Home | Next
HttpRequestPool::getAttachedRequests | Up | HttpRequestPool::reset


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.

Prev | Home | Next
HttpRequestPool::getFinishedRequests | Up | HttpRequestPool::send


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).

Prev | Home | Next
HttpRequestPool::reset | Up | HttpRequestPool::socketPerform


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

&#60;?php
class MyPool extends HttpRequestPool
{
    public function send()
    {
        while ($this-&#62;socketPerform()) {
            if (!$this-&#62;socketSelect()) {
                throw new HttpSocketExcpetion;
            }
        }
    }

    protected final function socketPerform()
    {
        $result = parent::socketPerform();
        foreach ($this-&#62;getFinishedRequests() as $r) {
            $this-&#62;detach($r);
            // handle response of finished request
        }
        return $result;
    }
}
?&#62;

Prev | Home | Next
HttpRequestPool::send | Up | HttpRequestPool::socketSelect


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.

Prev | Home | Next
HttpRequestPool::socketPerform | Up | HttpResponse


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

&#60;?php
HttpResponse::setCache(true);
HttpResponse::capture();
// script follows
?&#62;

Prev | Home | Next
HttpResponse | Up | HttpResponse::getBufferSize


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.

Prev | Home | Next
HttpResponse::capture | Up | HttpResponse::getCacheControl


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.

Prev | Home | Next
HttpResponse::getCacheControl | Up | HttpResponse::getContentDisposition


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.

Prev | Home | Next
HttpResponse::getBufferSize | Up | HttpResponse::getCache


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.

Prev | Home | Next
HttpResponse::getCache | Up | HttpResponse::getContentType


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.

Prev | Home | Next
HttpResponse::getContentDisposition | Up | HttpResponse::getData


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.

Prev | Home | Next
HttpResponse::getContentType | Up | HttpResponse::getETag


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.

Prev | Home | Next
HttpResponse::getData | Up | HttpResponse::getFile


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.

Prev | Home | Next
HttpResponse::getETag | Up | HttpResponse::getGzip


HttpResponse::getGzip

(no version information, might be only in CVS)

HttpResponse::getGzip -- Get gzip

Description

staticbool HttpResponse::getGzip ( void )

Get current gzipping setting.

Return Values

Returns TRUE if GZip compression is enabled, else FALSE.

Prev | Home | Next
HttpResponse::getFile | Up | HttpResponse::getHeader


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: In Apache2 this only works for PHP-5.1.3 and greater.

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.

Prev | Home | Next
HttpResponse::getGzip | Up | HttpResponse::getLastModified


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.

Prev | Home | Next
HttpResponse::getHeader | Up | HttpResponse::getStream


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.

Prev | Home | Next
HttpResponse::getLastModified | Up | HttpResponse::getThrottleDelay


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.

Prev | Home | Next
HttpResponse::getStream | Up | HttpResponse::guessContentType


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.

Prev | Home | Next
HttpResponse::getThrottleDelay | Up | HttpResponse::send


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 cause a script termination, and write a log entry if the INI setting http.cache_log is set.

Parameters

clean_ob

whether to destroy all previously started output handlers and their buffers

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws HttpHeaderException, HttpResponseException

Examples

Example 1. A HttpResponse::send() example

&#60;?php
HttpResponse::setCache(true);
HttpResponse::setContentType('application/pdf');
HttpResponse::setContentDisposition("$user.pdf", false);
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?&#62;

Prev | Home | Next
HttpResponse::guessContentType | Up | HttpResponse::setBufferSize


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 for use with HttpResponse::setThrottleDelay().

Provides a basic throttling mechanism, which will yield the current process resp. thread until the entity has been completely sent, though.

Note: This doesn't really work with the FastCGI SAPI.

Parameters

bytes

the chunk size in bytes

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::send | Up | HttpResponse::setCacheControl


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.

Prev | Home | Next
HttpResponse::setCacheControl | Up | HttpResponse::setContentDisposition


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.

Errors/Exceptions

Throws HttpInvalidParamException.

Prev | Home | Next
HttpResponse::setBufferSize | Up | HttpResponse::setCache


HttpResponse::setContentDisposition

(no version information, might be only in CVS)

HttpResponse::setContentDisposition -- Set content disposition

Description

staticbool HttpResponse::setContentDisposition ( [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).

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.

Prev | Home | Next
HttpResponse::setCache | Up | HttpResponse::setContentType


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.

Errors/Exceptions

Throws HttpInvalidParamException.

Prev | Home | Next
HttpResponse::setContentDisposition | Up | HttpResponse::setData


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.

Parameters

data

data to send

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::setContentType | Up | HttpResponse::setETag


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.

Prev | Home | Next
HttpResponse::setData | Up | HttpResponse::setFile


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.

Parameters

file

the path to the file to send

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::setETag | Up | HttpResponse::setGzip


HttpResponse::setGzip

(no version information, might be only in CVS)

HttpResponse::setGzip -- Set gzip

Description

staticbool HttpResponse::setGzip ( bool gzip )

Enable on-thy-fly gzipping of the sent entity.

Parameters

gzip

whether GZip compression should be enabled

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::setFile | Up | HttpResponse::setHeader


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.

Errors/Exceptions

Throws HttpHeaderException.

Prev | Home | Next
HttpResponse::setGzip | Up | HttpResponse::setLastModified


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.

Prev | Home | Next
HttpResponse::setHeader | Up | HttpResponse::setStream


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.

Parameters

stream

already opened stream from which the data to send will be read

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::setLastModified | Up | HttpResponse::setThrottleDelay


HttpResponse::setThrottleDelay

(no version information, might be only in CVS)

HttpResponse::setThrottleDelay -- Set throttle delay

Description

staticbool HttpResponse::setThrottleDelay ( double seconds )

Sets the throttle delay for use with HttpResponse::setBufferSize().

Provides a basic throttling mechanism, which will yield the current process resp. thread until the entity has been completely sent, though.

Note: This doesn't really work with the FastCGI SAPI.

Parameters

seconds

The seconds to sleep after each chunk sent

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
HttpResponse::setStream | Up | http_cache_etag


i18n_loc_get_default

(no version information, might be only in CVS)

i18n_loc_get_default -- Get the default Locale

Description

string i18n_loc_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 i18n_loc_get_default() example

&#60;?php

// get the default Locale
echo i18n_loc_get_default();

//set a new Locale...
i18n_loc_set_default('pt_PT');

// ... and print it
echo i18n_loc_get_default();

?&#62;

The above example will output:

en_US_POSIX
pt_PT

See Also

i18n_loc_set_default()

Prev | Home | Next
Unicode Functions | Up | i18n_loc_set_default


i18n_loc_set_default

(no version information, might be only in CVS)

i18n_loc_set_default -- Set the default Locale

Description

bool i18n_loc_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 i18n_loc_set_default() example

This example demonstrates a possible usage of i18n_loc_set_default() to localize the sort() functions.

&#60;?php

// the list of the strings to sort
$array = array(
    'caramelo',
    'cacto',
    'caçada'
);

// set our locale (Portuguese, in this case)
i18n_loc_set_default('pt_PT');

// sort using the locale we previously set
sort($array, SORT_LOCALE_STRING);

print_r($array);
?&#62;

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
)

See Also

i18n_loc_get_default()

Prev | Home | Next
i18n_loc_get_default | Up | unicode_encode


imageconvolution

(PHP 5 >= 5.1.0RC1)

imageconvolution -- Apply a 3x3 convolution matrix, using coefficient and offset

Description

bool imageconvolution ( resource image, array matrix, float div, float offset )

Applies a convolution matrix on the image, using the given coefficient and offset.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

matrix

A 3x3 matrix: an array of three arrays of three floats.

div

The divisor of the result of the convolution, used for normalization.

offset

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Embossing the PHP.net logo

&#60;?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');

$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);

header('Content-Type: image/png');
imagepng($image, null, 9);
?&#62;

The above example will output:

Example 2. Gaussian blur

&#60;?php
$image = imagecreatetruecolor(180,40);

// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);

// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);

header('Content-Type: image/png');
imagepng($image, null, 9);
?&#62;

The above example will output:

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

imagefilter()

Prev | Home | Next
imagecolortransparent | Up | imagecopy


imagick_begindraw

(PECL)

imagick_begindraw -- Begin draw

Description

bool imagick_begindraw ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
Image magick Functions | Up | imagick_blob2image


imagick_blob2image

(PECL)

imagick_blob2image -- Read image from BLOB

Description

resource imagick_blob2image ( string blob )

Warning

This function is currently not documented; only the argument list is available.

Parameters

blob

BLOB containing the image

Return Values

New image handle on success or FALSE on error.

Prev | Home | Next
imagick_begindraw | Up | imagick_blur


imagick_blur

(PECL)

imagick_blur -- Blur image

Description

bool imagick_blur ( resource image, float radius, float sigma )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the Gaussian in pixels, not counting the center pixel

sigma

Standard deviation of the Gaussian in pixels

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_blob2image | Up | imagick_border


imagick_border

(PECL)

imagick_border -- Surrounds the image with a border

Description

bool imagick_border ( resource image, int x, int y, int width, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

width

Rectangle width

height

Rectangle height

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_blur | Up | imagick_charcoal


imagick_charcoal

(PECL)

imagick_charcoal -- Highlight edges

Description

bool imagick_charcoal ( resource image, float radius, float sigma )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood

sigma

Standard deviation of the Gaussian in pixels

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_border | Up | imagick_chop


imagick_chop

(PECL)

imagick_chop -- Remove a region of an image and collapse the image to occupy the removed portion

Description

bool imagick_chop ( resource image, int x, int y, int width, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

width

Rectangle width

height

Rectangle height

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_charcoal | Up | imagick_clonehandle


imagick_clonehandle

(PECL)

imagick_clonehandle -- Clone image

Description

resource imagick_clonehandle ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

New image handle on success or FALSE on error.

Prev | Home | Next
imagick_chop | Up | imagick_composite


imagick_composite

(PECL)

imagick_composite -- Composite the second image onto the first at the specified offsets

Description

bool imagick_composite ( resource image, int type, resource image2, int x_offset, int y_offset )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

type

One of IMAGICK_COMPOSITE_* constants

image2

Image 2 handle

x_offset

Column offset of the composited image

y_offset

Row offset of the composited image

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_clonehandle | Up | imagick_contrast


imagick_contrast

(PECL)

imagick_contrast -- Enhance the intensity differences between the lighter and darker elements of the image

Description

bool imagick_contrast ( resource image, int sharpen )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

sharpen

Increase or decrease image contrast

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_composite | Up | imagick_convert


imagick_convert

(PECL)

imagick_convert -- Convert image

Description

bool imagick_convert ( resource image, string type )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

type

One of IMAGICK_TYPE_* constants

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_contrast | Up | imagick_crop


imagick_crop

(PECL)

imagick_crop -- Extract a region of the image

Description

bool imagick_crop ( resource image, int x, int y, int width, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

width

Rectangle width

height

Rectangle height

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_convert | Up | imagick_despeckle


imagick_despeckle

(PECL)

imagick_despeckle -- Reduce the speckle noise

Description

bool imagick_despeckle ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_crop | Up | imagick_destroyhandle


imagick_destroyhandle

(PECL)

imagick_destroyhandle -- Free image from memory

Description

bool imagick_destroyhandle ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_despeckle | Up | imagick_drawannotation


imagick_drawannotation

(PECL)

imagick_drawannotation -- Write text

Description

bool imagick_drawannotation ( resource image, float x, float y, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

X ordinate to left of text

y

Y ordinate to text baseline

text

Text to draw

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_destroyhandle | Up | imagick_drawarc


imagick_drawarc

(PECL)

imagick_drawarc -- Draw arc

Description

bool imagick_drawarc ( resource image, float x1, float y1, float x2, float y2, float start_rot, float end_rot )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x1

Starting x ordinate of bounding rectangle

y1

Starting y ordinate of bounding rectangle

x2

Ending x ordinate of bounding rectangle

y2

Ending y ordinate of bounding rectangle

start_rot

Starting degrees of rotation

end_rot

Ending degrees of rotation

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawannotation | Up | imagick_drawcircle


imagick_drawcircle

(PECL)

imagick_drawcircle -- Draw circle

Description

bool imagick_drawcircle ( resource image, float x1, float y1, float x2, float y2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x1

Origin x ordinate

y1

Origin y ordinate

x2

Perimeter x ordinate

y2

Perimeter y ordinate

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawarc | Up | imagick_drawellipse


imagick_drawellipse

(PECL)

imagick_drawellipse -- Draw ellipse

Description

bool imagick_drawellipse ( resource image, float x, float y, float radius_x, float radius_y, float start_rot, float end_rot )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Origin x ordinate

y

Origin y ordinate

radius_x

Radius in x

radius_y

Radius in y

start_rot

Starting rotation in degrees

end_rot

Ending rotation in degrees

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawcircle | Up | imagick_drawline


imagick_drawline

(PECL)

imagick_drawline -- Draw line

Description

bool imagick_drawline ( resource image, float x1, float y1, float x2, float y2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x1

Starting x ordinate

y1

Starting y ordinate

x2

Ending x ordinate

y2

Ending y ordinate

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawellipse | Up | imagick_drawpoint


imagick_drawpoint

(PECL)

imagick_drawpoint -- Draw point

Description

bool imagick_drawpoint ( resource image, float x, float y )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawline | Up | imagick_drawrectangle


imagick_drawrectangle

(PECL)

imagick_drawrectangle -- Draw rectangle

Description

bool imagick_drawrectangle ( resource image, float x1, float y1, float x2, float y2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x1

X ordinate of first coordinate

y1

Y ordinate of first coordinate

x2

X ordinate of second coordinate

y2

Y ordinate of second coordinate

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawpoint | Up | imagick_edge


imagick_edge

(PECL)

imagick_edge -- Find edges

Description

bool imagick_edge ( resource image, float radius )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_drawrectangle | Up | imagick_emboss


imagick_emboss

(PECL)

imagick_emboss -- Return a grayscale image with a three-dimensional effect

Description

bool imagick_emboss ( resource image, float radius, float sigma )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood

sigma

Standard deviation of the Gaussian in pixels

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_edge | Up | imagick_enhance


imagick_enhance

(PECL)

imagick_enhance -- Apply a digital filter that improves the quality of a noisy image

Description

bool imagick_enhance ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_emboss | Up | imagick_equalize


imagick_equalize

(PECL)

imagick_equalize -- Apply a histogram equalization to the image

Description

bool imagick_equalize ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_enhance | Up | imagick_error


imagick_error

(PECL)

imagick_error -- Check whether there is an error

Description

string imagick_error ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

String containing all types of errors or empty string if there is no error.

Prev | Home | Next
imagick_equalize | Up | imagick_faileddescription


imagick_faileddescription

(PECL)

imagick_faileddescription -- Get description of failure

Description

string imagick_faileddescription ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Description of failure or FALSE if there is no failure.

Prev | Home | Next
imagick_error | Up | imagick_failedreason


imagick_failedreason

(PECL)

imagick_failedreason -- Get reason of failure

Description

string imagick_failedreason ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Reason of failure or FALSE if there is no failure.

Prev | Home | Next
imagick_faileddescription | Up | imagick_first


imagick_first

(PECL)

imagick_first -- Set the internal pointer of an image list to its first element

Description

bool imagick_first ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_failedreason | Up | imagick_flatten


imagick_flatten

(PECL)

imagick_flatten -- Merge a sequence of images

Description

bool imagick_flatten ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_first | Up | imagick_flip


imagick_flip

(PECL)

imagick_flip -- Create a vertical mirror image by reflecting the pixels around the central x-axis

Description

bool imagick_flip ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_flatten | Up | imagick_flop


imagick_flop

(PECL)

imagick_flop -- Create a horizontal mirror image by reflecting the pixels around the central y-axis

Description

bool imagick_flop ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_flip | Up | imagick_frame


imagick_frame

(PECL)

imagick_frame -- Add a simulated three-dimensional border around the image

Description

bool imagick_frame ( resource image, int x, int y, int width, int height, int inner_bevel, int outer_bevel )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

width

Rectangle width

height

Rectangle height

inner_bevel

Inner bevel

outer_bevel

Outer bevel

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_flop | Up | imagick_free


imagick_free

(PECL)

imagick_free -- Alias of imagick_destroyhandle()

Description

bool imagick_free ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_frame | Up | imagick_gamma


imagick_gamma

(PECL)

imagick_gamma -- Gamma-correct a particular image channel

Description

bool imagick_gamma ( resource image, string level )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

level

Image gamma

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_free | Up | imagick_gaussianblur


imagick_gaussianblur

(PECL)

imagick_gaussianblur -- Blur image

Description

bool imagick_gaussianblur ( resource image, float radius, float sigma )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood not counting the center pixel

sigma

Standard deviation of the Gaussian in pixels

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_gamma | Up | imagick_getcanvas


imagick_getcanvas

(PECL)

imagick_getcanvas -- Get canvas

Description

resource imagick_getcanvas ( string color, int width, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

color

Background color

width

Width of the image

height

Height of the image

Return Values

New image handle on success or FALSE on error.

Prev | Home | Next
imagick_gaussianblur | Up | imagick_getcolorspace


imagick_getcolorspace

(PECL)

imagick_getcolorspace -- Get color space

Description

int imagick_getcolorspace ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

One of IMAGICK_COLORSPACE_* constants.

Prev | Home | Next
imagick_getcanvas | Up | imagick_getdpix


imagick_getdpix

(PECL)

imagick_getdpix -- Get DPI in X axis

Description

int imagick_getdpix ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Number of dots per inch in X axis.

Prev | Home | Next
imagick_getcolorspace | Up | imagick_getdpiy


imagick_getdpiy

(PECL)

imagick_getdpiy -- Get DPI in Y axis

Description

int imagick_getdpiy ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Number of dots per inch in Y axis.

Prev | Home | Next
imagick_getdpix | Up | imagick_getheight


imagick_getheight

(PECL)

imagick_getheight -- Get height

Description

int imagick_getheight ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Height of an image in pixels.

Prev | Home | Next
imagick_getdpiy | Up | imagick_getimagedepth


imagick_getimagedepth

(PECL)

imagick_getimagedepth -- Get color depth

Description

int imagick_getimagedepth ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Minimum number of bits required to store every pixel of an image.

Prev | Home | Next
imagick_getheight | Up | imagick_getimagefromlist


imagick_getimagefromlist

(PECL)

imagick_getimagefromlist -- Return copy of an image from the list

Description

resource imagick_getimagefromlist ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

New image handle on success or FALSE on failure.

Prev | Home | Next
imagick_getimagedepth | Up | imagick_getimagetype


imagick_getimagetype

(PECL)

imagick_getimagetype -- Get image type

Description

int imagick_getimagetype ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

One of IMAGICK_TYPE_* constants.

Prev | Home | Next
imagick_getimagefromlist | Up | imagick_getlistindex


imagick_getlistindex

(PECL)

imagick_getlistindex -- Get position in the list of the specified image

Description

int imagick_getlistindex ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

0-based index of the specified image in the list.

Prev | Home | Next
imagick_getimagetype | Up | imagick_getlistsize


imagick_getlistsize

(PECL)

imagick_getlistsize -- Get list size

Description

int imagick_getlistsize ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Number of images in the list.

Prev | Home | Next
imagick_getlistindex | Up | imagick_getmagick


imagick_getmagick

(PECL)

imagick_getmagick -- Get Magick string

Description

string imagick_getmagick ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Magick string on success or FALSE on failure.

Prev | Home | Next
imagick_getlistsize | Up | imagick_getmimetype


imagick_getmimetype

(PECL)

imagick_getmimetype -- Get MIME type

Description

string imagick_getmimetype ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

MIME type on success or FALSE on failure.

Prev | Home | Next
imagick_getmagick | Up | imagick_getnumbercolors


imagick_getnumbercolors

(PECL)

imagick_getnumbercolors -- Get number of colors

Description

int imagick_getnumbercolors ( resource image, string hist_filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

hist_filename

Write a histogram of the color distribution to this file

Return Values

Number of unique colors used in the image on success or FALSE on failure.

Prev | Home | Next
imagick_getmimetype | Up | imagick_getwidth


imagick_getwidth

(PECL)

imagick_getwidth -- Get width

Description

int imagick_getwidth ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Width of an image in pixels.

Prev | Home | Next
imagick_getnumbercolors | Up | imagick_goto


imagick_goto

(PECL)

imagick_goto -- Go to specified image in a list

Description

bool imagick_goto ( resource image, int frame )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

frame

0-based index of a frame

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_getwidth | Up | imagick_image2blob


imagick_image2blob

(PECL)

imagick_image2blob -- Return image as BLOB

Description

string imagick_image2blob ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

BLOB representation of image.

Prev | Home | Next
imagick_goto | Up | imagick_implode


imagick_implode

(PECL)

imagick_implode -- Implode image pixels

Description

bool imagick_implode ( resource image, float amount )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

amount

Extent of the implosion

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_image2blob | Up | imagick_iserror


imagick_iserror

(PECL)

imagick_iserror -- Check whether there is an error with image

Description

bool imagick_iserror ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

TRUE if there is an error, FALSE otherwise.

Prev | Home | Next
imagick_implode | Up | imagick_isgrayimage


imagick_isgrayimage

(PECL)

imagick_isgrayimage -- Check whether image is gray

Description

bool imagick_isgrayimage ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

TRUE if image is gray, FALSE otherwise.

Prev | Home | Next
imagick_iserror | Up | imagick_isimagesequal


imagick_isimagesequal

(PECL)

imagick_isimagesequal -- Compare two images

Description

bool imagick_isimagesequal ( resource image, resource image2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

image2

Image 2 handle

Return Values

TRUE if images are equal, FALSE otherwise.

Prev | Home | Next
imagick_isgrayimage | Up | imagick_ismonochromeimage


imagick_ismonochromeimage

(PECL)

imagick_ismonochromeimage -- Check whether image is monochrome

Description

bool imagick_ismonochromeimage ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

TRUE if image is monochrome, FALSE otherwise.

Prev | Home | Next
imagick_isimagesequal | Up | imagick_isopaqueimage


imagick_isopaqueimage

(PECL)

imagick_isopaqueimage -- Check whether image is opaque

Description

bool imagick_isopaqueimage ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

TRUE if image is opaque, FALSE otherwise.

Prev | Home | Next
imagick_ismonochromeimage | Up | imagick_ispaletteimage


imagick_ispaletteimage

(PECL)

imagick_ispaletteimage -- Check whether image is palette

Description

bool imagick_ispaletteimage ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

TRUE if image is palette, FALSE otherwise.

Prev | Home | Next
imagick_isopaqueimage | Up | imagick_level


imagick_level

(PECL)

imagick_level -- Adjust levels of a particular image channel by scaling the colors falling between specified white and black points to the full available quantum range

Description

bool imagick_level ( resource image, string level )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

level

Specify the levels where the black and white points have the range of 0-QuantumRange, and gamma has the range 0-10 (e.g. 10x90+2)

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_ispaletteimage | Up | imagick_magnify


imagick_magnify

(PECL)

imagick_magnify -- Double-size the image using bilinear interpolation

Description

bool imagick_magnify ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_level | Up | imagick_medianfilter


imagick_medianfilter

(PECL)

imagick_medianfilter -- Replace each pixel by the median in a set of neighboring pixels

Description

bool imagick_medianfilter ( resource image, float radius )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_magnify | Up | imagick_minify


imagick_minify

(PECL)

imagick_minify -- Half-size the image using the weighted average of a 4x4 cell

Description

bool imagick_minify ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_medianfilter | Up | imagick_modulate


imagick_modulate

(PECL)

imagick_modulate -- Control brightness, saturation and hue

Description

bool imagick_modulate ( resource image, string modulate )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

modulate

Define the percent change in brightness, saturation, and hue

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_minify | Up | imagick_mosaic


imagick_mosaic

(PECL)

imagick_mosaic -- Inlay a number of images to form a single coherent picture

Description

resource imagick_mosaic ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

New image handle on success or FALSE on failure.

Prev | Home | Next
imagick_modulate | Up | imagick_motionblur


imagick_motionblur

(PECL)

imagick_motionblur -- Simulate motion blur

Description

bool imagick_motionblur ( resource image, float radius, float sigma, float angle )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood not counting the center pixel

sigma

Standard deviation of the Gaussian in pixels

angle

Apply the effect along this angle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_mosaic | Up | imagick_negate


imagick_negate

(PECL)

imagick_negate -- Negate the colors

Description

bool imagick_negate ( resource image, int gray_scale )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

gray_scale

If non-zero, only negate grayscale pixels within the image

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_motionblur | Up | imagick_newimagelist


imagick_newimagelist

(PECL)

imagick_newimagelist -- Create new image list

Description

resource imagick_newimagelist ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

New image list on success or FALSE on failure.

Prev | Home | Next
imagick_negate | Up | imagick_next


imagick_next

(PECL)

imagick_next -- Advance the internal pointer of an image list

Description

bool imagick_next ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_newimagelist | Up | imagick_normalize


imagick_normalize

(PECL)

imagick_normalize -- Enhance the contrast of a color image by mapping the darkest 2 percent of all pixel to black and the brightest 1 percent to white

Description

bool imagick_normalize ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_next | Up | imagick_oilpaint


imagick_oilpaint

(PECL)

imagick_oilpaint -- Simulate oil painting

Description

bool imagick_oilpaint ( resource image, float radius )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the circular neighborhood

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_normalize | Up | imagick_ordereddither


imagick_ordereddither

(PECL)

imagick_ordereddither -- Use the ordered dithering technique of reducing color images to monochrome

Description

bool imagick_ordereddither ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_oilpaint | Up | imagick_poplist


imagick_poplist

(PECL)

imagick_poplist -- Remove the last image in the list

Description

resource imagick_poplist ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Image handle of extracted image on success or FALSE on failure.

Prev | Home | Next
imagick_ordereddither | Up | imagick_prev


imagick_prev

(PECL)

imagick_prev -- Rewind the internal pointer of an image list

Description

bool imagick_prev ( resource image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_poplist | Up | imagick_profile


imagick_profile

(PECL)

imagick_profile -- Add or remove a ICC, IPTC, or generic profile from an image

Description

bool imagick_profile ( resource image, string name, int clone [, string profile] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

name

Name of profile to add or remove: ICC, IPTC, or generic profile

clone

Should be zero

profile

The profile data

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_prev | Up | imagick_pushlist


imagick_pushlist

(PECL)

imagick_pushlist -- Add an image to the end of the list

Description

bool imagick_pushlist ( resource image, resource push_image )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

push_image

Handle if an image to push

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_profile | Up | imagick_raise


imagick_raise

(PECL)

imagick_raise -- Create a simulated three-dimensional button-like effect

Description

bool imagick_raise ( resource image, int x, int y, int width, int height, int raise )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

width

Rectangle width

height

Rectangle height

raise

A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_pushlist | Up | imagick_read


imagick_read

(PECL)

imagick_read -- Alias of imagick_readimage()

Description

resource imagick_read ( resource image, string filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

filename

Name of a file to read image from

Return Values

New image handle on success or FALSE on failure.

Prev | Home | Next
imagick_raise | Up | imagick_readimage


imagick_readimage

(PECL)

imagick_readimage -- Read image

Description

resource imagick_readimage ( string filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

filename

Name of a file to read image from

Return Values

New image handle on success or FALSE on failure.

Prev | Home | Next
imagick_read | Up | imagick_reducenoise


imagick_reducenoise

(PECL)

imagick_reducenoise -- Smooth the contours of an image while still preserving edge information

Description

bool imagick_reducenoise ( resource image, float radius )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_readimage | Up | imagick_resize


imagick_resize

(PECL)

imagick_resize -- Resize image

Description

bool imagick_resize ( resource image, int cols, int rows, int filter, float blur [, string geo_mods] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

cols

The number of columns desired in the scaled image

rows

The number of rows desired in the scaled image

filter

One of IMAGICK_FILTER_* constants

blur

The blur factor where > 1 is blurry, < 1 is sharp

geo_mods

Geometry modificators

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_reducenoise | Up | imagick_roll


imagick_roll

(PECL)

imagick_roll -- Offset an image as defined by x and y

Description

bool imagick_roll ( resource image, int x_offset, int y_offset )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x_offset

X offset

y_offset

Y offset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_resize | Up | imagick_rotate


imagick_rotate

(PECL)

imagick_rotate -- Rotate image

Description

bool imagick_rotate ( resource image, float degrees )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

degrees

The number of degrees to rotate the image

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_roll | Up | imagick_sample


imagick_sample

(PECL)

imagick_sample -- Scale image using pixel sampling

Description

bool imagick_sample ( resource image, int cols, int rows [, string geo_mods] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

cols

The number of columns in the scaled image

rows

The number of rows in the scaled image

geo_mods

Geometry modificators

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_rotate | Up | imagick_scale


imagick_scale

(PECL)

imagick_scale -- Scale image using pnmscale() of PBMPLUS

Description

bool imagick_scale ( resource image, int cols, int rows [, string geo_mods] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

cols

The number of columns in the scaled image

rows

The number of rows in the scaled image

geo_mods

Geometry modificators

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_sample | Up | imagick_set_image_comment


imagick_set_image_comment

(PECL)

imagick_set_image_comment -- Set "comment" attribute of image

Description

bool imagick_set_image_comment ( resource image, string comment )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

comment

The image comment

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_scale | Up | imagick_set_image_quality


imagick_set_image_quality

(PECL)

imagick_set_image_quality -- Set image quality

Description

bool imagick_set_image_quality ( resource image, int quality )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

quality

The image quality

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_set_image_comment | Up | imagick_setcompressionquality


imagick_setcompressionquality

(PECL)

imagick_setcompressionquality -- Set compression quality

Description

bool imagick_setcompressionquality ( resource image, int quality )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

quality

The image compression quality

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_set_image_quality | Up | imagick_setcompressiontype


imagick_setcompressiontype

(PECL)

imagick_setcompressiontype -- Set compression type

Description

bool imagick_setcompressiontype ( resource image, int type )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

type

One of IMAGICK_COMPRESSION_* constants

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setcompressionquality | Up | imagick_setdpi


imagick_setdpi

(PECL)

imagick_setdpi -- Set DPI

Description

bool imagick_setdpi ( resource image, int dpi_x, int dpi_y )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

dpi_x

Horizontal dots per inch

dpi_y

Vertical dots per inch

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setcompressiontype | Up | imagick_setfillcolor


imagick_setfillcolor

(PECL)

imagick_setfillcolor -- Set fill color

Description

bool imagick_setfillcolor ( resource image, string color )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

color

Fill color

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setdpi | Up | imagick_setfillopacity


imagick_setfillopacity

(PECL)

imagick_setfillopacity -- Set fill opacity

Description

bool imagick_setfillopacity ( resource image, float opacity )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

opacity

Fill opacity

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setfillcolor | Up | imagick_setfontface


imagick_setfontface

(PECL)

imagick_setfontface -- Set font face

Description

bool imagick_setfontface ( resource image, string face )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

face

Font family

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setfillopacity | Up | imagick_setfontsize


imagick_setfontsize

(PECL)

imagick_setfontsize -- Set font size

Description

bool imagick_setfontsize ( resource image, float size )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

size

Font pointsize

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setfontface | Up | imagick_setfontstyle


imagick_setfontstyle

(PECL)

imagick_setfontstyle -- Set font style

Description

bool imagick_setfontstyle ( resource image, int style )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

style

One of IMAGICK_FONTSTYLE_* constants

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setfontsize | Up | imagick_shade


imagick_shade

(PECL)

imagick_shade -- Shine a distant light on an image to create a three-dimensional effect

Description

bool imagick_shade ( resource image, int gray, float azimuth, float elevation )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

gray

A value other than zero shades the intensity of each pixel

azimuth

Azimuth of the light source direction

elevation

Elevation of the light source direction

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_setfontstyle | Up | imagick_sharpen


imagick_sharpen

(PECL)

imagick_sharpen -- Sharpen image

Description

bool imagick_sharpen ( resource image, float radius, float sigma )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood not counting the center pixel

sigma

Standard deviation of the Laplacian in pixels

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_shade | Up | imagick_shear


imagick_shear

(PECL)

imagick_shear -- Slide one edge of an image along the X or Y axis, creating a parallelogram

Description

bool imagick_shear ( resource image, float x, float y )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

x

Horizontal offset

y

Vertical offset

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_sharpen | Up | imagick_solarize


imagick_solarize

(PECL)

imagick_solarize -- Solarize image

Description

bool imagick_solarize ( resource image, float threshold )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

threshold

Extent of the solarization

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_shear | Up | imagick_spread


imagick_spread

(PECL)

imagick_spread -- Randomly displace each pixel in a block

Description

bool imagick_spread ( resource image, int radius )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Choose a random pixel in a neighborhood of this extent

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_solarize | Up | imagick_swirl


imagick_swirl

(PECL)

imagick_swirl -- Swirl pixels around the center of image

Description

bool imagick_swirl ( resource image, float degrees )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

degrees

Tightness of the swirling effect

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_spread | Up | imagick_threshold


imagick_threshold

(PECL)

imagick_threshold -- Change the value of individual pixels based on the intensity of each pixel compared to threshold

Description

bool imagick_threshold ( resource image, float threshold )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

threshold

The desired threshold value

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_swirl | Up | imagick_transformrgb


imagick_transformrgb

(PECL)

imagick_transformrgb -- Convert the image from RGB to an alternate colorspace

Description

bool imagick_transformrgb ( resource image, int colorspace )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

colorspace

One of IMAGICK_COLORSPACE_* constants

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_threshold | Up | imagick_transparent


imagick_transparent

(PECL)

imagick_transparent -- Make image transparent

Description

bool imagick_transparent ( resource image, string trans_color )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

trans_color

Name of the transparent color

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_transformrgb | Up | imagick_unsharpmask


imagick_unsharpmask

(PECL)

imagick_unsharpmask -- Sharpen image

Description

bool imagick_unsharpmask ( resource image, float radius, float sigma, float amount, float threshold )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

radius

Radius of the pixel neighborhood not counting the center pixel

sigma

Standard deviation of the Gaussian in pixels

amount

Percentage of the difference between the original and the blur image that is added back into the original

threshold

Threshold in pixels needed to apply the diffence amount

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_transparent | Up | imagick_wave


imagick_wave

(PECL)

imagick_wave -- Creates a ripple effect in the image by shifting the pixels vertically along a sine wave

Description

bool imagick_wave ( resource image, float amplitude, float frequency )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

amplitude

Amplitude of the sine wave

frequency

Wave length of the sine wave

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_unsharpmask | Up | imagick_writeimage


imagick_writeimage

(PECL)

imagick_writeimage -- Write image

Description

bool imagick_writeimage ( resource image, string filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

filename

Name of a file to write image to

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_wave | Up | imagick_writeimages


imagick_writeimages

(PECL)

imagick_writeimages -- Write images

Description

bool imagick_writeimages ( resource image, string filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

filename

Name of a file to write images to

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_writeimage | Up | imagick_zoom


imagick_zoom

(PECL)

imagick_zoom -- Zoom image using selected filter

Description

bool imagick_zoom ( resource image, int cols, int rows [, string geo_mods] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

image

Image handle

cols

The number of columns in the scaled image

rows

The number of rows in the scaled image

geo_mods

Geometry modificators

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
imagick_writeimages | Up | IMAP, POP3 and NNTP Functions


imap_savebody

(no version information, might be only in CVS)

imap_savebody -- Save a specific body section to a file

Description

bool imap_savebody ( resource imap_stream, mixed file, int msg_number [, string part_number [, int options]] )

Saves a part or the whole body of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

file

The path to the saved file as a string, or a valid file descriptor returned by fopen().

msg_number

The message number

part_number

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

imap_fetchbody()

Prev | Home | Next
imap_rfc822_write_address | Up | imap_scanmailbox


ingres_cursor

(PECL)

ingres_cursor -- Gets a cursor name for a given link resource

Description

string ingres_cursor ( [resource link] )

Returns an string containing the active cursor name. If no cursor is active then NULL is returned.

If a link resource is passed to ingres_cursor() it returns the cursor name recorded for the link. If no link is passed then ingres_cursor() returns the cursor name asssociated with the default link.

Example 1. ingres_cursor() example

&#60;?php
$link = ingres_connect($database, $user, $password);

ingres_prepare("select * from table", $link);

$cursor_name = ingres_cursor($link);

echo $cursor_name;

?&#62;

See also ingres_prepare() and ingres_execute().

Prev | Home | Next
ingres_connect | Up | ingres_errno


ingres_errno

(PECL)

ingres_errno -- Gets the last ingres error number generated

Description

int ingres_errno ( [resource link] )

Returns an integer containing the last error number. If no error was reported 0 is returned.

If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed then ingres_errno() returns the last error reported using the default link.

The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called, will reset or change any error code from the last Ingres function call.

Example 1. ingres_errno() example

&#60;?php
$link = ingres_connect($database, $user, $password);

ingres_query("select * from table", $link);

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occured - " . $error_code;
}
?&#62;

See also ingres_error() and ingres_errsqlstate().

Prev | Home | Next
ingres_cursor | Up | ingres_error


ingres_error

(PECL)

ingres_error -- Gets a meaningful error message for the last error generated

Description

string ingres_error ( [resource link] )

Returns a string containing the last error, or NULL if no error has occurred.

If a link resource is passed to ingres_error() it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.

The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.

Example 1. ingres_error() example

&#60;?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");

$error_text = ingres_error();

if ( is_null($error_text) ) {
   echo "An error occured - " . $error_text;
}
?&#62;

See also ingres_errno() and ingres_errsqlstate().

Prev | Home | Next
ingres_errno | Up | ingres_errsqlstate


ingres_errsqlstate

(PECL)

ingres_errsqlstate -- Gets the last SQLSTATE error code generated

Description

string ingres_errsqlstate ( [resource link] )

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

If a link resource is passed to ingres_errsqlstate() it returns the last error recorded for the link. If no link is passed then ingres_errsqlstate() returns the last error reported using the default link.

The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.

Example 1. ingres_errsqlstate() example

&#60;?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");

$error_sqlstate = ingres_errsqlstate();

if ( is_null($error_sqlstate) ) {
   echo "An error occured - " . $error_sqlstate;
}
?&#62;

See also ingres_errno() and ingres_errsqlstate().

Prev | Home | Next
ingres_error | Up | ingres_fetch_array


is_binary

(PHP 5 CVS only)

is_binary -- Finds whether a variable is a native binary string

Description

bool is_binary ( mixed var )

Finds whether the given variable is a native binary string.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a native binary string, FALSE otherwise.

See Also

is_buffer()
is_string()
is_unicode()

Prev | Home | Next
is_array | Up | is_bool


is_buffer

(PHP 5 CVS only)

is_buffer -- Finds whether a variable is a native unicode or binary string

Description

bool is_buffer ( mixed var )

Finds whether the given variable is a native unicode or binary string.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a native unicode or binary string, FALSE otherwise.

See Also

is_binary()
is_string()
is_unicode()

Prev | Home | Next
is_bool | Up | is_callable


is_unicode

(PHP 5 CVS only)

is_unicode -- Finds whether a variable is a unicode string

Description

bool is_unicode ( mixed var )

Finds whether the given variable is a unicode string.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a unicode string, FALSE otherwise.

See Also

is_binary()
is_buffer()
is_string()
unicode_encode()

Prev | Home | Next
is_string | Up | isset


json_decode

(no version information, might be only in CVS)

json_decode -- Decodes a JSON string

Description

mixed json_decode ( string json [, bool assoc] )

Takes a JSON encoded string and converts it into a PHP variable.

Parameters

json

The json string being decoded.

assoc

When TRUE, returned objects will be converted into associative arrays.

Return Values

Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.

Examples

Example 1. json_decode() examples

&#60;?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?&#62;

The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

See Also

json_encode()

Prev | Home | Next
JSON Functions | Up | json_encode


json_encode

(no version information, might be only in CVS)

json_encode -- Returns the JSON representation of a value

Description

string json_encode ( mixed value )

Returns a string containing the JSON representation of value.

Parameters

value

The value being encoded. Can be any type except a resource.

This function only works with UTF-8 encoded data.

Return Values

Returns a JSON encoded string on success.

Examples

Example 1. A json_encode() example

&#60;?php
$arr = array ('a'=&#62;1,'b'=&#62;2,'c'=&#62;3,'d'=&#62;4,'e'=&#62;5);

echo json_encode($arr);
?&#62;

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

See Also

json_decode()

Prev | Home | Next
json_decode | Up | KADM5


kadm5_chpass_principal

(PECL)

kadm5_chpass_principal -- Changes the principal's password

Description

bool kadm5_chpass_principal ( resource handle, string principal, string password )

kadm5_chpass_principal() sets the new password password for the principal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Example of changing principal's password

&#60;?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
KADM5 | Up | kadm5_create_principal


kadm5_create_principal

(PECL)

kadm5_create_principal -- Creates a kerberos principal with the given parameters

Description

bool kadm5_create_principal ( resource handle, string principal [, string password [, array options]] )

kadm5_create_principal() creates a principal with the given password. If password is omitted or is NULL, a random key will be generated.

It is possible to specify several optional parameters within the array options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Example of principal's creation

&#60;?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME =&#62; 0,
                 KADM5_POLICY =&#62; "default",
                 KADM5_ATTRIBUTES =&#62; $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_chpass_principal | Up | kadm5_delete_principal


kadm5_delete_principal

(PECL)

kadm5_delete_principal -- Deletes a kerberos principal

Description

bool kadm5_delete_principal ( resource handle, string principal )

kadm5_delete_principal() remove the principal from the Kerberos database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. kadm5_delete_principal() example

&#60;?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_create_principal | Up | kadm5_destroy


kadm5_destroy

(PECL)

kadm5_destroy -- Closes the connection to the admin server and releases all related resources

Description

bool kadm5_destroy ( resource handle )

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
kadm5_delete_principal | Up | kadm5_flush


kadm5_flush

(PECL)

kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open

Description

bool kadm5_flush ( resource handle )

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
kadm5_destroy | Up | kadm5_get_policies


kadm5_get_policies

(PECL)

kadm5_get_policies -- Gets all policies from the Kerberos database

Description

array kadm5_get_policies ( resource handle )

kadm5_get_policies() returns an array containing the policies's names.

Return Values

Returns array of policies on success, or FALSE on failure.

Examples

Example 1. kadm5_get_policies() example

&#60;?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "&#60;h1&#62;get_policies&#60;/h1&#62;\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy&#60;br /&#62;\n";
}

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_flush | Up | kadm5_get_principal


kadm5_get_principal

(PECL)

kadm5_get_principal -- Gets the principal's entries from the Kerberos database

Description

array kadm5_get_principal ( resource handle, string principal )

kadm5_get_principal() returns an associative array containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT.

Return Values

Returns array of options on success, or FALSE on failure.

Examples

Example 1. kadm5_get_principal() example

&#60;?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "&#60;h1&#62;get_principal burbach@GONICUS.LOCAL&#60;/h1&#62;\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key =&#62; $value) {
    echo "$key: $value&#60;br /&#62;\n";
}

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_get_policies | Up | kadm5_get_principals


kadm5_get_principals

(PECL)

kadm5_get_principals -- Gets all principals from the Kerberos database

Description

array kadm5_get_principals ( resource handle )

kadm5_get_principals() returns an array containing the principals's names.

Return Values

Returns array of principals on success, or FALSE on failure.

Examples

Example 1. kadm5_get_principals() example

&#60;?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "&#60;h1&#62;get_principals&#60;/h1&#62;\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal&#60;br /&#62;\n";
}

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_get_principal | Up | kadm5_init_with_password


kadm5_init_with_password

(PECL)

kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state information

Description

resource kadm5_init_with_password ( string admin_server, string realm, string principal, string password )

kadm5_init_with_password() opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server. The parameter realm defines the authentication domain for the connection.

Return Values

Returns a KADM5 handle on success, or FALSE on failure.

Examples

Example 1. KADM5 initialization example

&#60;?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME =&#62; 0,
                 KADM5_POLICY =&#62; "default",
                 KADM5_ATTRIBUTES =&#62; $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?&#62;

Notes

Note: Connection should be closed after use with kadm5_destroy().

See Also

kadm5_destroy()

Prev | Home | Next
kadm5_get_principals | Up | kadm5_modify_principal


kadm5_modify_principal

(PECL)

kadm5_modify_principal -- Modifies a kerberos principal with the given parameters

Description

bool kadm5_modify_principal ( resource handle, string principal, array options )

kadm5_modify_principal() modifies a principal according to the given options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE, KADM5_FAIL_AUTH_COUNT.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Example of modifying principal

&#60;?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME =&#62; 3451234,
                 KADM5_POLICY =&#62; "gonicus",
                 KADM5_ATTRIBUTES =&#62; $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

kadm5_destroy($handle);
?&#62;

Prev | Home | Next
kadm5_init_with_password | Up | LDAP Functions


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 (specified by name or number). 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.

Returns TRUE on success or FALSE on failure.

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 chgrp(),
lchown()
chown() and
chmod().

Prev | Home | Next
is_writeable | Up | lchown


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 (specified by name or number). Only the superuser may change the owner of a symlink.

Returns TRUE on success or FALSE on failure.

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(),
lchgrp(),
chgrp() and
chmod().

Prev | Home | Next
lchgrp | Up | link


m_checkstatus

(PHP 4 >= 4.3.9, PHP 5)

m_checkstatus -- Check to see if a transaction has completed

Description

int m_checkstatus ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
MCVE (Monetra) Payment Functions | Up | m_completeauthorizations


m_completeauthorizations

(PHP 4 >= 4.3.9, PHP 5)

m_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers

Description

int m_completeauthorizations ( resource conn, int &array )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

array

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_checkstatus | Up | m_connect


m_connect

(PHP 4 >= 4.3.9, PHP 5)

m_connect -- Establish the connection to MCVE

Description

int m_connect ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_completeauthorizations | Up | m_connectionerror


m_connectionerror

(PHP 4 >= 4.3.9, PHP 5)

m_connectionerror -- Get a textual representation of why a connection failed

Description

string m_connectionerror ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_connect | Up | m_deletetrans


m_deletetrans

(PHP 4 >= 4.3.9, PHP 5)

m_deletetrans -- Delete specified transaction from MCVE_CONN structure

Description

bool m_deletetrans ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_connectionerror | Up | m_destroyconn


m_destroyconn

(PHP 4 >= 4.3.9, PHP 5)

m_destroyconn -- Destroy the connection and MCVE_CONN structure

Description

bool m_destroyconn ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

Returns TRUE.

See Also

m_initconn()

Prev | Home | Next
m_deletetrans | Up | m_destroyengine


m_destroyengine

(PHP 4 >= 4.3.9, PHP 5)

m_destroyengine -- Free memory associated with IP/SSL connectivity

Description

void m_destroyengine ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

No value is returned.

Prev | Home | Next
m_destroyconn | Up | m_getcell


m_getcell

(PHP 4 >= 4.3.9, PHP 5)

m_getcell -- Get a specific cell from a comma delimited response by column name

Description

string m_getcell ( resource conn, int identifier, string column, int row )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

column

Its description

row

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_destroyengine | Up | m_getcellbynum


m_getcellbynum

(PHP 4 >= 4.3.9, PHP 5)

m_getcellbynum -- Get a specific cell from a comma delimited response by column number

Description

string m_getcellbynum ( resource conn, int identifier, int column, int row )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

column

Its description

row

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_getcell | Up | m_getcommadelimited


m_getcommadelimited

(PHP 4 >= 4.3.9, PHP 5)

m_getcommadelimited -- Get the RAW comma delimited data returned from MCVE

Description

string m_getcommadelimited ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_getcellbynum | Up | m_getheader


m_getheader

(PHP 4 >= 4.3.9, PHP 5)

m_getheader -- Get the name of the column in a comma-delimited response

Description

string m_getheader ( resource conn, int identifier, int column_num )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

column_num

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_getcommadelimited | Up | m_initconn


m_initconn

(PHP 4 >= 4.3.9, PHP 5)

m_initconn -- Create and initialize an MCVE_CONN structure

Description

resource m_initconn ( void )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns an MCVE_CONN resource.

See Also

m_destroyconn()

Prev | Home | Next
m_getheader | Up | m_initengine


m_initengine

(PHP 4 >= 4.3.9, PHP 5)

m_initengine -- Ready the client for IP/SSL Communication

Description

int m_initengine ( string location )

Warning

This function is currently not documented; only the argument list is available.

Parameters

location

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_initconn | Up | m_iscommadelimited


m_iscommadelimited

(PHP 4 >= 4.3.9, PHP 5)

m_iscommadelimited -- Checks to see if response is comma delimited

Description

int m_iscommadelimited ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_initengine | Up | m_maxconntimeout


m_maxconntimeout

(PHP 4 >= 4.3.9, PHP 5)

m_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE

Description

bool m_maxconntimeout ( resource conn, int secs )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

secs

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_iscommadelimited | Up | m_monitor


m_monitor

(PHP 4 >= 4.3.9, PHP 5)

m_monitor -- Perform communication with MCVE (send/receive data) Non-blocking

Description

int m_monitor ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_maxconntimeout | Up | m_numcolumns


m_numcolumns

(PHP 4 >= 4.3.9, PHP 5)

m_numcolumns -- Number of columns returned in a comma delimited response

Description

int m_numcolumns ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_monitor | Up | m_numrows


m_numrows

(PHP 4 >= 4.3.9, PHP 5)

m_numrows -- Number of rows returned in a comma delimited response

Description

int m_numrows ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_numcolumns | Up | m_parsecommadelimited


m_parsecommadelimited

(PHP 4 >= 4.3.9, PHP 5)

m_parsecommadelimited -- Parse the comma delimited response so m_getcell, etc will work

Description

int m_parsecommadelimited ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_numrows | Up | m_responsekeys


m_responsekeys

(PHP 5 >= 5.1.0RC1)

m_responsekeys -- Returns array of strings which represents the keys that can be used for response parameters on this transaction

Description

array m_responsekeys ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_parsecommadelimited | Up | m_responseparam


m_responseparam

(PHP 4 >= 4.3.9, PHP 5)

m_responseparam -- Get a custom response parameter

Description

string m_responseparam ( resource conn, int identifier, string key )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

key

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_responsekeys | Up | m_returnstatus


m_returnstatus

(PHP 4 >= 4.3.9, PHP 5)

m_returnstatus -- Check to see if the transaction was successful

Description

int m_returnstatus ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_responseparam | Up | m_setblocking


m_setblocking

(PHP 4 >= 4.3.9, PHP 5)

m_setblocking -- Set blocking/non-blocking mode for connection

Description

int m_setblocking ( resource conn, int tf )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_returnstatus | Up | m_setdropfile


m_setdropfile

(PHP 4 >= 4.3.9, PHP 5)

m_setdropfile -- Set the connection method to Drop-File

Description

int m_setdropfile ( resource conn, string directory )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

directory

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setblocking | Up | m_setip


m_setip

(PHP 4 >= 4.3.9, PHP 5)

m_setip -- Set the connection method to IP

Description

int m_setip ( resource conn, string host, int port )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

Its description

port

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setdropfile | Up | m_setssl_cafile


m_setssl

(PHP 4 >= 4.3.9, PHP 5)

m_setssl -- Set the connection method to SSL

Description

int m_setssl ( resource conn, string host, int port )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

Its description

port

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setssl_files | Up | m_settimeout


m_setssl_cafile

(PHP 5 >= 5.1.0RC1)

m_setssl_cafile -- Set SSL CA (Certificate Authority) file for verification of server certificate

Description

int m_setssl_cafile ( resource conn, string cafile )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

cafile

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setip | Up | m_setssl_files


m_setssl_files

(PHP 4 >= 4.3.9, PHP 5)

m_setssl_files -- Set certificate key files and certificates if server requires client certificate verification

Description

int m_setssl_files ( resource conn, string sslkeyfile, string sslcertfile )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

sslkeyfile

Its description

sslcertfile

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setssl_cafile | Up | m_setssl


m_settimeout

(PHP 4 >= 4.3.9, PHP 5)

m_settimeout -- Set maximum transaction time (per trans)

Description

int m_settimeout ( resource conn, int seconds )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

seconds

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_setssl | Up | m_sslcert_gen_hash


m_sslcert_gen_hash

(no version information, might be only in CVS)

m_sslcert_gen_hash -- Generate hash for SSL client certificate verification

Description

string m_sslcert_gen_hash ( string filename )

Warning

This function is currently not documented; only the argument list is available.

Parameters

filename

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_settimeout | Up | m_transactionssent


m_transactionssent

(PHP 4 >= 4.3.9, PHP 5)

m_transactionssent -- Check to see if outgoing buffer is clear

Description

int m_transactionssent ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_sslcert_gen_hash | Up | m_transinqueue


m_transinqueue

(PHP 4 >= 4.3.9, PHP 5)

m_transinqueue -- Number of transactions in client-queue

Description

int m_transinqueue ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_transactionssent | Up | m_transkeyval


m_transkeyval

(PHP 5 >= 5.1.0RC1)

m_transkeyval -- Add key/value pair to a transaction. Replaces deprecated transparam()

Description

int m_transkeyval ( resource conn, int identifier, string key, string value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

key

Its description

value

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_transinqueue | Up | m_transnew


m_transnew

(PHP 4 >= 4.3.9, PHP 5)

m_transnew -- Start a new transaction

Description

int m_transnew ( resource conn )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_transkeyval | Up | m_transsend


m_transsend

(PHP 4 >= 4.3.9, PHP 5)

m_transsend -- Finalize and send the transaction

Description

int m_transsend ( resource conn, int identifier )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_transnew | Up | m_uwait


m_uwait

(PHP 4 >= 4.3.9, PHP 5)

m_uwait -- Wait x microsecs

Description

int m_uwait ( int microsecs )

Warning

This function is currently not documented; only the argument list is available.

Parameters

microsecs

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_transsend | Up | m_validateidentifier


m_validateidentifier

(PHP 5 >= 5.1.0RC1)

m_validateidentifier -- Whether or not to validate the passed identifier on any transaction it is passed to

Description

int m_validateidentifier ( resource conn, int tf )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_uwait | Up | m_verifyconnection


m_verifyconnection

(PHP 4 >= 4.3.9, PHP 5)

m_verifyconnection -- Set whether or not to PING upon connect to verify connection

Description

bool m_verifyconnection ( resource conn, int tf )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_validateidentifier | Up | m_verifysslcert


m_verifysslcert

(PHP 4 >= 4.3.9, PHP 5)

m_verifysslcert -- Set whether or not to verify the server ssl certificate

Description

bool m_verifysslcert ( resource conn, int tf )

Warning

This function is currently not documented; only the argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
m_verifyconnection | Up | Memcache Functions


mb_check_encoding

(no version information, might be only in CVS)

mb_check_encoding -- Check if the string is valid for the specified encoding

Description

bool mb_check_encoding ( [string var [, string encoding]] )

mb_check_encoding() checks if the string is valid for the specified encoding. It is useful to prevent so-called "Invalid Encoding Attack".

Parameters

var

String to check. If it is omitted, this function checks all the input from the beginning of the request.

encoding

Expected encoding.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
Multibyte String Functions | Up | mb_convert_case


mb_list_encodings_alias_names

(no version information, might be only in CVS)

mb_list_encodings_alias_names -- Returns an array of all supported alias encodings

Description

array mb_list_encodings_alias_names ( [string encoding] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mb_language | Up | mb_list_encodings


mb_list_mime_names

(no version information, might be only in CVS)

mb_list_mime_names -- Returns an array or string of all supported mime names

Description

mixed mb_list_mime_names ( [string encoding] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mb_list_encodings | Up | mb_output_handler


mb_stripos

(no version information, might be only in CVS)

mb_stripos -- Finds position of first occurrence of a string within another, case insensitive

Description

int mb_stripos ( string haystack, string needle [, int offset [, string encoding]] )

mb_stripos() returns the numeric position of the first occurrence of needle in the haystack string. Unlike mb_strpos(), mb_stripos() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the position of the first occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

See Also

stripos()
strpos()
mb_strpos()

Prev | Home | Next
mb_strimwidth | Up | mb_stristr


mb_stristr

(no version information, might be only in CVS)

mb_stristr -- Finds first occurrence of a string within another, case insensitive

Description

string mb_stristr ( string haystack, string needle [, bool part [, string encoding]] )

mb_stristr() finds the first occurrence of needle in haystack and returns the portion of haystack. Unlike mb_strstr(), mb_stristr() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end, Default value is FALSE.

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack, or FALSE if needle is not found.

See Also

stristr()
strstr()
mb_strstr()

Prev | Home | Next
mb_stripos | Up | mb_strlen


mb_strrchr

(no version information, might be only in CVS)

mb_strrchr -- Finds the last occurrence of a character in a string within another

Description

string mb_strrchr ( string haystack, string needle [, bool part [, string encoding]] )

mb_strrchr() finds the last occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle. If set to FALSE, it returns all of haystack from the last occurrence of needle to the end, Default value is FALSE.

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack. or FALSE if needle is not found.

See Also

strrchr()
mb_strstr()
mb_strrichr()

Prev | Home | Next
mb_strpos | Up | mb_strrichr


mb_strrichr

(no version information, might be only in CVS)

mb_strrichr -- Finds the last occurrence of a character in a string within another, case insensitive

Description

string mb_strrichr ( string haystack, string needle [, bool part [, string encoding]] )

mb_strrichr() finds the last occurrence of needle in haystack and returns the portion of haystack. Unlike mb_strrchr(), mb_strrichr() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle. If set to FALSE, it returns all of haystack from the last occurrence of needle to the end, Default value is FALSE.

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack. or FALSE if needle is not found.

See Also

mb_stristr()
mb_strrchr()

Prev | Home | Next
mb_strrchr | Up | mb_strripos


mb_strripos

(no version information, might be only in CVS)

mb_strripos -- Finds position of last occurrence of a string within another, case insensitive

Description

int mb_strripos ( string haystack, string needle [, int offset [, string encoding]] )

mb_strripos() performs multi-byte safe strripos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1. Unlike mb_strrpos(), mb_strripos() is case-insensitive.

Parameters

haystack

The string from which to get the position of the last occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the last occurrence of needle in the haystack string, or FALSE if needle is not found.

See Also

strripos()
strrpos()
mb_strrpos()

Prev | Home | Next
mb_strrichr | Up | mb_strrpos


mb_strstr

(no version information, might be only in CVS)

mb_strstr -- Finds first occurrence of a string within another

Description

string mb_strstr ( string haystack, string needle [, bool part [, string encoding]] )

mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end, Default value is FALSE.

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack, or FALSE if needle is not found.

See Also

stristr()
strstr()
mb_stristr()

Prev | Home | Next
mb_strrpos | Up | mb_strtolower


Memcache::addServer

(no version information, might be only in CVS)

Memcache::addServer -- Add a memcached server to connection pool

Description

bool Memcache::addServer ( string host [, int port [, bool persistent [, int weight [, int timeout [, int retry_interval [, bool status [, callback failure_callback]]]]]]] )

Memcache::addServer() adds a server to the connection pool. The connection, which was opened using Memcache::addServer() will be automatically closed at the end of script execution, you can also close it manually with Memcache::close(). You can also use the memcache_add_server() function.

When using this method (as opposed to Memcache::connect()() and Memcache::pconnect()()) the network connection is not established until actually needed. Thus there is no overhead in adding a large number of servers to the pool, even though they might not all be used.

Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover.

Note: This function has been added to Memcache version 2.0.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211.

persistent

Controls the use of a persistent connection. Default to TRUE.

weight

Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

Each failed connection struct has its own timeout and before it has expired the struct will be skipped when selecting backends to serve a request. Once expired the connection will be successfully reconnected or marked as failed for another retry_interval seconds. The typical effect is that each webserver child will retry the connection about every retry_interval seconds when serving a page.

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algoritm. Requests for this server will then failover or fail immediatly depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attemped. The function takes two parameters, the hostname and port of the failed server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::addServer() example

&#60;?php

/* OO API */

$memcache = new Memcache;
$memcache-&#62;addServer('memcache_host', 11211);
$memcache-&#62;addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?&#62;

See Also

Memcache::connect()
Memcache::pconnect()
Memcache::close()
Memcache::setServerParams()
Memcache::getServerStatus()

Prev | Home | Next
Memcache::add | Up | Memcache::close


Memcache::getExtendedStats

(no version information, might be only in CVS)

Memcache::getExtendedStats -- Get statistics from all servers in pool

Description

array Memcache::getExtendedStats ( [string type [, int slabid [, int limit]]] )

Memcache::getExtendedStats() returns a two-dimensional associative array with server statistics. Array keys correspond to host:port of server and values contain the individual server statistics. A failed server will have its corresponding entry set to FALSE. You can also use the memcache_get_extended_stats() function.

Note: This function has been added to Memcache version 2.0.0.

Parameters

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump. Default value is 100.

Return Values

Returns a two-dimensional associative array of server statistics or FALSE on failure.

Examples

Example 1. Memcache::getExtendedStats() example

&#60;?php
    $memcache_obj = new Memcache;
    $memcache_obj-&#62;addServer('memcache_host', 11211);
    $memcache_obj-&#62;addServer('failed_host', 11211);

    $stats = $memcache_obj-&#62;getExtendedStats();
    print_r($stats);
?&#62;

The above example will output:

Array
(
    [memcache_host:11211] => Array
        (
            [pid] => 3756
            [uptime] => 603011
            [time] => 1133810435
            [version] => 1.1.12
            [rusage_user] => 0.451931
            [rusage_system] => 0.634903
            [curr_items] => 2483
            [total_items] => 3079
            [bytes] => 2718136
            [curr_connections] => 2
            [total_connections] => 807
            [connection_structures] => 13
            [cmd_get] => 9748
            [cmd_set] => 3096
            [get_hits] => 5976
            [get_misses] => 3772
            [bytes_read] => 3448968
            [bytes_written] => 2318883
            [limit_maxbytes] => 33554432
        )

    [failed_host:11211] => false
)

See Also

Memcache::getVersion()
Memcache::getStats()

Prev | Home | Next
Memcache::get | Up | Memcache::getServerStatus


Memcache::getServerStatus

(no version information, might be only in CVS)

Memcache::getServerStatus -- Returns server status

Description

int Memcache::getServerStatus ( string host [, int port] )

Memcache::getServerStatus() returns a the servers online/offline status. You can also use memcache_get_server_status() function.

Note: This function has been added to Memcache version 2.1.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211.

Return Values

Returns a the servers status. 0 if server is failed, non-zero otherwise

Examples

Example 1. Memcache::getServerStatus() example

&#60;?php

/* OO API */
$memcache = new Memcache;
$memcache-&#62;addServer('memcache_host', 11211);
echo $memcache-&#62;getServerStatus('memcache_host', 11211);

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_server_status($memcache, 'memcache_host', 11211);

?&#62;

See Also

Memcache::addServer()
Memcache::setServerParams()

Prev | Home | Next
Memcache::getExtendedStats | Up | Memcache::getStats


Memcache::setCompressThreshold

(no version information, might be only in CVS)

Memcache::setCompressThreshold -- Enable automatic compression of large values

Description

bool Memcache::setCompressThreshold ( int threshold [, float min_savings] )

Memcache::setCompressThreshold() enables automatic compression of large values. You can also use the memcache_set_compress_threshold() function.

Note: This function has been added to Memcache version 2.0.0.

Parameters

threshold

Controls the minimum value length before attempting to compress automatically.

min_saving

Specifies the minimum amount of savings to actually store the value compressed. The supplied value must be between 0 and 1. Default value is 0.2 giving a minimum 20% compression savings.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::setCompressThreshold() example

&#60;?php

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj-&#62;addServer('memcache_host', 11211);
$memcache_obj-&#62;setCompressThreshold(20000, 0.2);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);

?&#62;

Prev | Home | Next
Memcache::set | Up | Memcache::setServerParams


Memcache::setServerParams

(no version information, might be only in CVS)

Memcache::setServerParams -- Changes server parameters and status at runtime

Description

bool Memcache::setServerParams ( string host [, int port [, int timeout [, int retry_interval [, bool status [, callback failure_callback]]]]] )

Memcache::setServerParams() changes server parameters at runtime. You can also use the memcache_set_server_params() function.

Note: This function has been added to Memcache version 2.1.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algoritm. Requests for this server will then failover or fail immediatly depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attemped. The function takes two parameters, the hostname and port of the failed server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Memcache::setServerParams() example

&#60;?php

function _callback_memcache_failure($host, $port) {
    print "memcache '$host:$port' failed";
}

/* OO API */

$memcache = new Memcache;

// Add the server in offline mode
$memcache-&#62;addServer('memcache_host', 11211, false, 1, 1, -1, false);

// Bring the server back online
$memcache-&#62;setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_server_params($memcache_obj, 'memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

?&#62;

See Also

Memcache::addServer()
Memcache::getServerStatus()

Prev | Home | Next
Memcache::setCompressThreshold | Up | Mhash Functions


memory_get_peak_usage

(no version information, might be only in CVS)

memory_get_peak_usage -- Returns the peak of memory allocated by PHP

Description

int memory_get_peak_usage ( [bool real_usage] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

memory_get_peak_usage() will only be defined if your PHP is compiled with the --enable-memory-limit configuration option.

Parameters

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

Return Values

Returns the memory peak in bytes.

ChangeLog

Version | Description
5.2.0 | real_usage was added.

See Also

memory_get_usage()
memory_limit

Prev | Home | Next
main | Up | memory_get_usage


ming_keypress

(PHP 5)

ming_keypress -- Returns the action flag for keyPress(char)

Description

int ming_keypress ( string char )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFVideoStream->setDimension() | Up | ming_setcubicthreshold


ming_useconstants

(PHP 5)

ming_useconstants -- Use constant pool

Description

void ming_useconstants ( int use )

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
ming_setscale | Up | ming_useswfversion


mysqli_embedded_server_end

(PHP 5 >= 5.1.0RC1)

mysqli_embedded_server_end --

Description

void mysqli_embedded_server_end ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_dump_debug_info | Up | mysqli_embedded_server_start


mysqli_embedded_server_start

(PHP 5 >= 5.1.0RC1)

mysqli_embedded_server_start --

Description

bool mysqli_embedded_server_start ( bool start, array arguments, array groups )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_embedded_server_end | Up | mysqli_enable_reads_from_master


mysqli_get_charset

(PHP 5 >= 5.1.0RC1)

mysqli_get_charset -- Returns a character set object

Description

object mysqli_get_charset ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_free_result | Up | mysqli_get_client_info


mysqli_get_warnings

(PHP 5 >= 5.1.0RC1)

mysqli_get_warnings --

Description

object mysqli_get_warnings ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_get_server_version | Up | mysqli_info


mysqli_set_charset

(PHP 5 >= 5.1.0RC1)

mysqli_set_charset

(no version information, might be only in CVS)

mysqli->set_charset -- Sets the default client character set

Description

Procedural style:

bool mysqli_set_charset ( mysqli link, string charset )

Object oriented style (method):

class mysqli {

bool set_charset ( string charset )

}

Sets the default character set to be used when sending data from and to the database server.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

charset

The charset to be set as default.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above). It can be downloaded at http://dev.mysql.com/downloads/connector/php/.

Examples

Example 1. Object oriented style

&#60;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!$mysqli-&#62;set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli-&#62;error);
} else {
    printf("Current character set: %s\n", $mysqli-&#62;character_set_name());
}

$mysqli-&#62;close();
?&#62;

Example 2. Procedural style

&#60;?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?&#62;

The above example will output:

Current character set: utf8

See Also

mysqli_character_set_name()
mysqli_real_escape_string()

Prev | Home | Next
mysqli_server_init | Up | mysqli_set_local_infile_default


mysqli_set_local_infile_default

(PHP 5)

mysqli_set_local_infile_default -- Unsets user defined handler for load local infile command

Description

void mysqli_set_local_infile_default ( mysqli link )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_set_charset | Up | mysqli_set_local_infile_handler


mysqli_set_local_infile_handler

(PHP 5)

mysqli_set_local_infile_handler -- Set callback functions for LOAD DATA LOCAL INFILE command

Description

bool mysqli_set_local_infile_handler ( mysqli link, callback read_func )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_set_local_infile_default | Up | mysqli_set_opt


mysqli_slave_query

(PHP 5)

mysqli_slave_query -- Force execution of a query on a slave in a master/slave setup

Description

bool mysqli_slave_query ( mysqli link, string query )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_set_opt | Up | mysqli_sqlstate


mysqli_stmt_attr_get

(PHP 5)

mysqli_stmt_attr_get --

Description

int mysqli_stmt_attr_get ( mysqli_stmt stmt, int attr )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_stmt_affected_rows | Up | mysqli_stmt_attr_set


mysqli_stmt_attr_set

(PHP 5)

mysqli_stmt_attr_set --

Description

int mysqli_stmt_attr_set ( mysqli_stmt stmt, int attr, int mode )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_stmt_attr_get | Up | mysqli_stmt_bind_param


mysqli_stmt_field_count

(PHP 5)

mysqli_stmt_field_count -- Returns the number of field in the given statement

Description

int mysqli_stmt_field_count ( mysqli_stmt stmt )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_stmt_fetch | Up | mysqli_stmt_free_result


mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0RC1)

mysqli_stmt_get_warnings --

Description

object mysqli_stmt_get_warnings ( mysqli_stmt stmt )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_stmt_free_result | Up | mysqli_stmt_init


mysqli_stmt_insert_id

(PHP 5)

mysqli_stmt_insert_id -- Get the ID generated from the previous INSERT operation

Description

mixed mysqli_stmt_insert_id ( mysqli_stmt stmt )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
mysqli_stmt_init | Up | mysqli_stmt_num_rows


newt_bell

(PECL)

newt_bell -- Send a beep to the terminal

Description

void newt_bell ( void )

This function sends a beep to the terminal.

Note: Depending on the terminal's settings, this beep may or may not be audible.

Prev | Home | Next
Newt Functions | Up | newt_button_bar


newt_button

(PECL)

newt_button --

Description

resource newt_button ( int left, int top, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_button_bar | Up | newt_centered_window


newt_button_bar

(PECL)

newt_button_bar --

Description

resource newt_button_bar ( array &buttons )

Warning

This function is currently not documented; only the argument list is available.

Parameters

buttons

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_bell | Up | newt_button


newt_centered_window

(PECL)

newt_centered_window -- Open a centered window of the specified size

Description

int newt_centered_window ( int width, int height [, string title] )

Open a centered window of the specified size.

Parameters

width

Window width

height

Window height

title

Window title

Return Values

Undefined value.

See Also

newt_pop_window()
newt_open_window()

Prev | Home | Next
newt_button | Up | newt_checkbox_get_value


newt_checkbox

(PECL)

newt_checkbox --

Description

resource newt_checkbox ( int left, int top, string text, string def_value [, string seq] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

def_value

Its description

seq

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree | Up | newt_clear_key_buffer


newt_checkbox_get_value

(PECL)

newt_checkbox_get_value --

Description

string newt_checkbox_get_value ( resource checkbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_centered_window | Up | newt_checkbox_set_flags


newt_checkbox_set_flags

(PECL)

newt_checkbox_set_flags --

Description

void newt_checkbox_set_flags ( resource checkbox, int flags, int sense )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkbox

Its description

flags

Its description

sense

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_get_value | Up | newt_checkbox_set_value


newt_checkbox_set_value

(PECL)

newt_checkbox_set_value --

Description

void newt_checkbox_set_value ( resource checkbox, string value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkbox

Its description

value

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_set_flags | Up | newt_checkbox_tree_add_item


newt_checkbox_tree

(PECL)

newt_checkbox_tree --

Description

resource newt_checkbox_tree ( int left, int top, int height [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

height

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_set_width | Up | newt_checkbox


newt_checkbox_tree_add_item

(PECL)

newt_checkbox_tree_add_item -- *

Description

void newt_checkbox_tree_add_item ( resource checkboxtree, string text, mixed data, int flags, int index [, int ...] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

text

Its description

data

Its description

flags

Its description

index

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_set_value | Up | newt_checkbox_tree_find_item


newt_checkbox_tree_find_item

(PECL)

newt_checkbox_tree_find_item --

Description

array newt_checkbox_tree_find_item ( resource checkboxtree, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_add_item | Up | newt_checkbox_tree_get_current


newt_checkbox_tree_get_current

(PECL)

newt_checkbox_tree_get_current --

Description

mixed newt_checkbox_tree_get_current ( resource checkboxtree )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_find_item | Up | newt_checkbox_tree_get_entry_value


newt_checkbox_tree_get_entry_value

(PECL)

newt_checkbox_tree_get_entry_value --

Description

string newt_checkbox_tree_get_entry_value ( resource checkboxtree, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_get_current | Up | newt_checkbox_tree_get_multi_selection


newt_checkbox_tree_get_multi_selection

(PECL)

newt_checkbox_tree_get_multi_selection --

Description

array newt_checkbox_tree_get_multi_selection ( resource checkboxtree, string seqnum )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

seqnum

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_get_entry_value | Up | newt_checkbox_tree_get_selection


newt_checkbox_tree_get_selection

(PECL)

newt_checkbox_tree_get_selection --

Description

array newt_checkbox_tree_get_selection ( resource checkboxtree )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_get_multi_selection | Up | newt_checkbox_tree_multi


newt_checkbox_tree_multi

(PECL)

newt_checkbox_tree_multi --

Description

resource newt_checkbox_tree_multi ( int left, int top, int height, string seq [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

height

Its description

seq

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_get_selection | Up | newt_checkbox_tree_set_current


newt_checkbox_tree_set_current

(PECL)

newt_checkbox_tree_set_current --

Description

void newt_checkbox_tree_set_current ( resource checkboxtree, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_multi | Up | newt_checkbox_tree_set_entry_value


newt_checkbox_tree_set_entry

(PECL)

newt_checkbox_tree_set_entry --

Description

void newt_checkbox_tree_set_entry ( resource checkboxtree, mixed data, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

data

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_set_entry_value | Up | newt_checkbox_tree_set_width


newt_checkbox_tree_set_entry_value

(PECL)

newt_checkbox_tree_set_entry_value --

Description

void newt_checkbox_tree_set_entry_value ( resource checkboxtree, mixed data, string value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkboxtree

Its description

data

Its description

value

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_set_current | Up | newt_checkbox_tree_set_entry


newt_checkbox_tree_set_width

(PECL)

newt_checkbox_tree_set_width --

Description

void newt_checkbox_tree_set_width ( resource checkbox_tree, int width )

Warning

This function is currently not documented; only the argument list is available.

Parameters

checkbox_tree

Its description

width

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_checkbox_tree_set_entry | Up | newt_checkbox_tree


newt_clear_key_buffer

(PECL)

newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional input

Description

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

See Also

newt_wait_for_key()

Prev | Home | Next
newt_checkbox | Up | newt_cls


newt_cls

(PECL)

newt_cls --

Description

void newt_cls ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_clear_key_buffer | Up | newt_compact_button


newt_compact_button

(PECL)

newt_compact_button --

Description

resource newt_compact_button ( int left, int top, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_cls | Up | newt_component_add_callback


newt_component_add_callback

(PECL)

newt_component_add_callback --

Description

void newt_component_add_callback ( resource component, mixed func_name, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

component

Its description

func_name

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_compact_button | Up | newt_component_takes_focus


newt_component_takes_focus

(PECL)

newt_component_takes_focus --

Description

void newt_component_takes_focus ( resource component, bool takes_focus )

Warning

This function is currently not documented; only the argument list is available.

Parameters

component

Its description

takes_focus

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_component_add_callback | Up | newt_create_grid


newt_create_grid

(PECL)

newt_create_grid --

Description

resource newt_create_grid ( int cols, int rows )

Warning

This function is currently not documented; only the argument list is available.

Parameters

cols

Its description

rows

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_component_takes_focus | Up | newt_cursor_off


newt_cursor_off

(PECL)

newt_cursor_off --

Description

void newt_cursor_off ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_create_grid | Up | newt_cursor_on


newt_cursor_on

(PECL)

newt_cursor_on --

Description

void newt_cursor_on ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_cursor_off | Up | newt_delay


newt_delay

(PECL)

newt_delay --

Description

void newt_delay ( int microseconds )

Warning

This function is currently not documented; only the argument list is available.

Parameters

microseconds

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_cursor_on | Up | newt_draw_form


newt_draw_form

(PECL)

newt_draw_form --

Description

void newt_draw_form ( resource form )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_delay | Up | newt_draw_root_text


newt_draw_root_text

(PECL)

newt_draw_root_text -- Displays the string text at the position indicated

Description

void newt_draw_root_text ( int left, int top, string text )

Displays the string text at the position indicated.

Parameters

left

Column number

Note: If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Note: If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Examples

Example 1. A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

&#60;?php
 newt_init();
 newt_cls();

 newt_draw_root_text (2, 0, "Some root text");
 newt_refresh();
 sleep(1);

 newt_draw_root_text (-30, 0, "Root text in the other corner");
 newt_refresh();
 sleep(1);

 newt_finished();
?&#62;

See Also

newt_push_help_line()
newt_pop_help_line()

Prev | Home | Next
newt_draw_form | Up | newt_entry_get_value


newt_entry

(PECL)

newt_entry --

Description

resource newt_entry ( int left, int top, int width [, string init_value [, int flags]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

width

Its description

init_value

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_entry_set | Up | newt_finished


newt_entry_get_value

(PECL)

newt_entry_get_value --

Description

string newt_entry_get_value ( resource entry )

Warning

This function is currently not documented; only the argument list is available.

Parameters

entry

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_draw_root_text | Up | newt_entry_set_filter


newt_entry_set

(PECL)

newt_entry_set --

Description

void newt_entry_set ( resource entry, string value [, bool cursor_at_end] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

entry

Its description

value

Its description

cursor_at_end

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_entry_set_flags | Up | newt_entry


newt_entry_set_filter

(PECL)

newt_entry_set_filter --

Description

void newt_entry_set_filter ( resource entry, callback filter, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

entry

Its description

filter

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_entry_get_value | Up | newt_entry_set_flags


newt_entry_set_flags

(PECL)

newt_entry_set_flags --

Description

void newt_entry_set_flags ( resource entry, int flags, int sense )

Warning

This function is currently not documented; only the argument list is available.

Parameters

entry

Its description

flags

Its description

sense

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_entry_set_filter | Up | newt_entry_set


newt_finished

(PECL)

newt_finished -- Uninitializes newt interface

Description

int newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

Return Values

Returns 1 on success, 0 on failure.

See Also

newt_init()

Prev | Home | Next
newt_entry | Up | newt_form_add_component


newt_form

(PECL)

newt_form -- Create a form

Description

resource newt_form ( [resource vert_bar [, string help [, int flags]]] )

Create a new form.

Parameters

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

Return Values

Resource link to the created form component.

Examples

Example 1. A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

&#60;?php
newt_init();
newt_cls();

$myform = newt_form();
$button = newt_button (5, 12, "Quit");

newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?&#62;

See Also

newt_form_run()
newt_run_form()
newt_form_add_component()
newt_form_add_components()
newt_form_destroy()

Prev | Home | Next
newt_form_watch_fd | Up | newt_get_screen_size


newt_form_add_component

(PECL)

newt_form_add_component -- Adds a single component to the form

Description

void newt_form_add_component ( resource form, resource component )

Adds a single component to the form which is passed as the first parameter.

Parameters

form

Form to which component will be added

component

Component to add to the form

See Also

newt_form_add_components()

Prev | Home | Next
newt_finished | Up | newt_form_add_components


newt_form_add_components

(PECL)

newt_form_add_components -- Add several components to the form

Description

void newt_form_add_components ( resource form, array components )

Adds several components to the form which is passed as the first parameter.

Parameters

form

Form to which components will be added

components

Array of components to add to the form

See Also

newt_form_add_component()

Prev | Home | Next
newt_form_add_component | Up | newt_form_add_host_key


newt_form_add_host_key

(no version information, might be only in CVS)

newt_form_add_host_key --

Description

void newt_form_add_host_key ( resource form, int key )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

key

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_add_components | Up | newt_form_destroy


newt_form_destroy

(PECL)

newt_form_destroy -- Destroys a form

Description

void newt_form_destroy ( resource form )

This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.

Parameters

form

Form component, which is going to be destroyed

See Also

newt_form_run()
newt_run_form()

Prev | Home | Next
newt_form_add_host_key | Up | newt_form_get_current


newt_form_get_current

(PECL)

newt_form_get_current --

Description

resource newt_form_get_current ( resource form )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_destroy | Up | newt_form_run


newt_form_run

(PECL)

newt_form_run -- Runs a form

Description

void newt_form_run ( resource form, array &exit_struct )

This function runs the form passed to it.

Parameters

form

Form component

exit_struct

Array, used for returning information after running the form component. Keys and values are described in the following table:

Table 1. Form Exit Structure

Index Key | Value Type | Description
reason | integer | The reason, why the form has been exited. Possible values are defined here.
watch | resource | Resource link, specified in newt_form_watch_fd()
key | integer | Hotkey
component | resource | Component, which caused the form to exit

See Also

newt_run_form()

Prev | Home | Next
newt_form_get_current | Up | newt_form_set_background


newt_form_set_background

(PECL)

newt_form_set_background --

Description

void newt_form_set_background ( resource from, int background )

Warning

This function is currently not documented; only the argument list is available.

Parameters

from

Its description

background

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_run | Up | newt_form_set_height


newt_form_set_height

(PECL)

newt_form_set_height --

Description

void newt_form_set_height ( resource form, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

height

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_set_background | Up | newt_form_set_size


newt_form_set_size

(PECL)

newt_form_set_size --

Description

void newt_form_set_size ( resource form )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_set_height | Up | newt_form_set_timer


newt_form_set_timer

(PECL)

newt_form_set_timer --

Description

void newt_form_set_timer ( resource form, int milliseconds )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

milliseconds

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_set_size | Up | newt_form_set_width


newt_form_set_width

(PECL)

newt_form_set_width --

Description

void newt_form_set_width ( resource form, int width )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

width

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_set_timer | Up | newt_form_watch_fd


newt_form_watch_fd

(PECL)

newt_form_watch_fd --

Description

void newt_form_watch_fd ( resource form, resource stream [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

form

Its description

stream

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_form_set_width | Up | newt_form


newt_get_screen_size

(PECL)

newt_get_screen_size -- Fills in the passed references with the current size of the terminal

Description

void newt_get_screen_size ( int &cols, int &rows )

Fills in the passed references with the current size of the terminal.

Parameters

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Return Values

This function returns values in an argument, passed by reference.

Examples

Example 1. A newt_get_screen_size() example

This code prints out the screen size of your terminal.

&#60;?php
 newt_init();
 newt_get_screen_size (&#38;$cols, &#38;$rows);
 newt_finished();

 print "Your terminal size is: {$cols}x{$rows}\n";
?&#62;

The above example will output:

Your terminal size is: 138x47

Prev | Home | Next
newt_form | Up | newt_grid_add_components_to_form


newt_grid_add_components_to_form

(PECL)

newt_grid_add_components_to_form --

Description

void newt_grid_add_components_to_form ( resource grid, resource form, bool recurse )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

form

Its description

recurse

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_get_screen_size | Up | newt_grid_basic_window


newt_grid_basic_window

(PECL)

newt_grid_basic_window --

Description

resource newt_grid_basic_window ( resource text, resource middle, resource buttons )

Warning

This function is currently not documented; only the argument list is available.

Parameters

text

Its description

middle

Its description

buttons

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_add_components_to_form | Up | newt_grid_free


newt_grid_free

(PECL)

newt_grid_free --

Description

void newt_grid_free ( resource grid, bool recurse )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

recurse

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_basic_window | Up | newt_grid_get_size


newt_grid_get_size

(PECL)

newt_grid_get_size --

Description

void newt_grid_get_size ( resouce grid, int &width, int &height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

width

Its description

height

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_free | Up | newt_grid_h_close_stacked


newt_grid_h_close_stacked

(PECL)

newt_grid_h_close_stacked --

Description

resource newt_grid_h_close_stacked ( int element1_type, resource element1 [, int ... [, resource ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

element1_type

Its description

element1

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_get_size | Up | newt_grid_h_stacked


newt_grid_h_stacked

(PECL)

newt_grid_h_stacked --

Description

resource newt_grid_h_stacked ( int element1_type, resource element1 [, int ... [, resource ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

element1_type

Its description

element1

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_h_close_stacked | Up | newt_grid_place


newt_grid_place

(PECL)

newt_grid_place --

Description

void newt_grid_place ( resource grid, int left, int top )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

left

Its description

top

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_h_stacked | Up | newt_grid_set_field


newt_grid_set_field

(PECL)

newt_grid_set_field --

Description

void newt_grid_set_field ( resource grid, int col, int row, int type, resource val, int pad_left, int pad_top, int pad_right, int pad_bottom, int anchor [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

col

Its description

row

Its description

type

Its description

val

Its description

pad_left

Its description

pad_top

Its description

pad_right

Its description

pad_bottom

Its description

anchor

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_place | Up | newt_grid_simple_window


newt_grid_simple_window

(PECL)

newt_grid_simple_window --

Description

resource newt_grid_simple_window ( resource text, resource middle, resource buttons )

Warning

This function is currently not documented; only the argument list is available.

Parameters

text

Its description

middle

Its description

buttons

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_set_field | Up | newt_grid_v_close_stacked


newt_grid_v_close_stacked

(PECL)

newt_grid_v_close_stacked --

Description

resource newt_grid_v_close_stacked ( int element1_type, resource element1 [, int ... [, resource ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

element1_type

Its description

element1

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_simple_window | Up | newt_grid_v_stacked


newt_grid_v_stacked

(PECL)

newt_grid_v_stacked --

Description

resource newt_grid_v_stacked ( int element1_type, resource element1 [, int ... [, resource ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

element1_type

Its description

element1

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_v_close_stacked | Up | newt_grid_wrapped_window_at


newt_grid_wrapped_window

(PECL)

newt_grid_wrapped_window --

Description

void newt_grid_wrapped_window ( resource grid, string title )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

title

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_wrapped_window_at | Up | newt_init


newt_grid_wrapped_window_at

(PECL)

newt_grid_wrapped_window_at --

Description

void newt_grid_wrapped_window_at ( resource grid, string title, int left, int top )

Warning

This function is currently not documented; only the argument list is available.

Parameters

grid

Its description

title

Its description

left

Its description

top

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_grid_v_stacked | Up | newt_grid_wrapped_window


newt_init

(PECL)

newt_init -- Initialize newt

Description

int newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

Return Values

Returns 1 on success, 0 on failure.

See Also

newt_finished()

Prev | Home | Next
newt_grid_wrapped_window | Up | newt_label_set_text


newt_label

(PECL)

newt_label --

Description

resource newt_label ( int left, int top, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_label_set_text | Up | newt_listbox_append_entry


newt_label_set_text

(PECL)

newt_label_set_text --

Description

void newt_label_set_text ( resource label, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

label

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_init | Up | newt_label


newt_listbox

(PECL)

newt_listbox --

Description

resource newt_listbox ( int left, int top, int height [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

height

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_set_width | Up | newt_listitem_get_data


newt_listbox_append_entry

(PECL)

newt_listbox_append_entry --

Description

void newt_listbox_append_entry ( resource listbox, string text, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

text

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_label | Up | newt_listbox_clear_selection


newt_listbox_clear

(PECL)

newt_listbox_clear --

Description

void newt_listbox_clear ( resource listobx )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listobx

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_clear_selection | Up | newt_listbox_delete_entry


newt_listbox_clear_selection

(PECL)

newt_listbox_clear_selection --

Description

void newt_listbox_clear_selection ( resource listbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_append_entry | Up | newt_listbox_clear


newt_listbox_delete_entry

(PECL)

newt_listbox_delete_entry --

Description

void newt_listbox_delete_entry ( resource listbox, mixed key )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

key

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_clear | Up | newt_listbox_get_current


newt_listbox_get_current

(PECL)

newt_listbox_get_current --

Description

string newt_listbox_get_current ( resource listbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_delete_entry | Up | newt_listbox_get_selection


newt_listbox_get_selection

(PECL)

newt_listbox_get_selection --

Description

array newt_listbox_get_selection ( resource listbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_get_current | Up | newt_listbox_insert_entry


newt_listbox_insert_entry

(PECL)

newt_listbox_insert_entry --

Description

void newt_listbox_insert_entry ( resource listbox, string text, mixed data, mixed key )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

text

Its description

data

Its description

key

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_get_selection | Up | newt_listbox_item_count


newt_listbox_item_count

(PECL)

newt_listbox_item_count --

Description

int newt_listbox_item_count ( resource listbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_insert_entry | Up | newt_listbox_select_item


newt_listbox_select_item

(PECL)

newt_listbox_select_item --

Description

void newt_listbox_select_item ( resource listbox, mixed key, int sense )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

key

Its description

sense

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_item_count | Up | newt_listbox_set_current_by_key


newt_listbox_set_current

(PECL)

newt_listbox_set_current --

Description

void newt_listbox_set_current ( resource listbox, int num )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

num

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_set_current_by_key | Up | newt_listbox_set_data


newt_listbox_set_current_by_key

(PECL)

newt_listbox_set_current_by_key --

Description

void newt_listbox_set_current_by_key ( resource listbox, mixed key )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

key

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_select_item | Up | newt_listbox_set_current


newt_listbox_set_data

(PECL)

newt_listbox_set_data --

Description

void newt_listbox_set_data ( resource listbox, int num, mixed data )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

num

Its description

data

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_set_current | Up | newt_listbox_set_entry


newt_listbox_set_entry

(PECL)

newt_listbox_set_entry --

Description

void newt_listbox_set_entry ( resource listbox, int num, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

num

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_set_data | Up | newt_listbox_set_width


newt_listbox_set_width

(PECL)

newt_listbox_set_width --

Description

void newt_listbox_set_width ( resource listbox, int width )

Warning

This function is currently not documented; only the argument list is available.

Parameters

listbox

Its description

width

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox_set_entry | Up | newt_listbox


newt_listitem

(PECL)

newt_listitem --

Description

resource newt_listitem ( int left, int top, string text, bool is_default, resouce prev_item, mixed data [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

is_default

Its description

prev_item

Its description

data

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listitem_set | Up | newt_open_window


newt_listitem_get_data

(PECL)

newt_listitem_get_data --

Description

mixed newt_listitem_get_data ( resource item )

Warning

This function is currently not documented; only the argument list is available.

Parameters

item

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listbox | Up | newt_listitem_set


newt_listitem_set

(PECL)

newt_listitem_set --

Description

void newt_listitem_set ( resource item, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

item

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_listitem_get_data | Up | newt_listitem


newt_open_window

(PECL)

newt_open_window -- Open a window of the specified size and position

Description

int newt_open_window ( int left, int top, int width, int height [, string title] )

Open a window of the specified size and position.

Parameters

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

Return Values

Returns 1 on success, 0 on failure.

See Also

newt_pop_window()
newt_centered_window()

Prev | Home | Next
newt_listitem | Up | newt_pop_help_line


newt_pop_help_line

(PECL)

newt_pop_help_line -- Replaces the current help line with the one from the stack

Description

void newt_pop_help_line ( void )

Replaces the current help line with the one from the stack.

Note: It's important not to call to newt_pop_help_line() more than newt_push_help_line().

See Also

newt_push_help_line()

Prev | Home | Next
newt_open_window | Up | newt_pop_window


newt_pop_window

(PECL)

newt_pop_window -- Removes the top window from the display

Description

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

See Also

newt_open_window()
newt_centered_window()

Prev | Home | Next
newt_pop_help_line | Up | newt_push_help_line


newt_push_help_line

(PECL)

newt_push_help_line -- Saves the current help line on a stack, and displays the new line

Description

void newt_push_help_line ( [string text] )

Saves the current help line on a stack, and displays the new line.

Parameters

text

New help text message

Note: If not specified, the help line is cleared.

See Also

newt_pop_help_line()

Prev | Home | Next
newt_pop_window | Up | newt_radio_get_current


newt_radio_get_current

(PECL)

newt_radio_get_current --

Description

resource newt_radio_get_current ( resource set_member )

Warning

This function is currently not documented; only the argument list is available.

Parameters

set_member

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_push_help_line | Up | newt_radiobutton


newt_radiobutton

(PECL)

newt_radiobutton --

Description

resource newt_radiobutton ( int left, int top, string text, bool is_default [, resource prev_button] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

text

Its description

is_default

Its description

prev_button

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_radio_get_current | Up | newt_redraw_help_line


newt_redraw_help_line

(PECL)

newt_redraw_help_line --

Description

void newt_redraw_help_line ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_radiobutton | Up | newt_reflow_text


newt_reflow_text

(PECL)

newt_reflow_text --

Description

string newt_reflow_text ( string text, int width, int flex_down, int flex_up, int &actual_width, int &actual_height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

text

Its description

width

Its description

flex_down

Its description

flex_up

Its description

actual_width

Its description

actual_height

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_redraw_help_line | Up | newt_refresh


newt_refresh

(PECL)

newt_refresh -- Updates modified portions of the screen

Description

void newt_refresh ( void )

To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.

Prev | Home | Next
newt_reflow_text | Up | newt_resize_screen


newt_resize_screen

(PECL)

newt_resize_screen --

Description

void newt_resize_screen ( [bool redraw] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

redraw

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_refresh | Up | newt_resume


newt_resume

(PECL)

newt_resume -- Resume using the newt interface after calling newt_suspend()

Description

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

See Also

newt_suspend()

Prev | Home | Next
newt_resize_screen | Up | newt_run_form


newt_run_form

(PECL)

newt_run_form -- Runs a form

Description

resource newt_run_form ( resource form )

This function runs the form passed to it.

Parameters

form

Form component

Return Values

The component which caused the form to stop running.

Note: Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.

See Also

newt_form_run()
newt_form_destroy()

Prev | Home | Next
newt_resume | Up | newt_scale_set


newt_scale

(PECL)

newt_scale --

Description

resource newt_scale ( int left, int top, int width, int full_value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

width

Its description

full_value

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_scale_set | Up | newt_scrollbar_set


newt_scale_set

(PECL)

newt_scale_set --

Description

void newt_scale_set ( resource scale, int amount )

Warning

This function is currently not documented; only the argument list is available.

Parameters

scale

Its description

amount

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_run_form | Up | newt_scale


newt_scrollbar_set

(PECL)

newt_scrollbar_set --

Description

void newt_scrollbar_set ( resource scrollbar, int where, int total )

Warning

This function is currently not documented; only the argument list is available.

Parameters

scrollbar

Its description

where

Its description

total

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_scale | Up | newt_set_help_callback


newt_set_help_callback

(PECL)

newt_set_help_callback --

Description

void newt_set_help_callback ( mixed function )

Warning

This function is currently not documented; only the argument list is available.

Parameters

function

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_scrollbar_set | Up | newt_set_suspend_callback


newt_set_suspend_callback

(PECL)

newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend key

Description

void newt_set_suspend_callback ( callback function, mixed data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parameters

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

See Also

newt_suspend()
newt_resume()

Prev | Home | Next
newt_set_help_callback | Up | newt_suspend


newt_suspend

(PECL)

newt_suspend -- Tells newt to return the terminal to its initial state

Description

void newt_suspend ( void )

Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).

See Also

newt_resume()

Prev | Home | Next
newt_set_suspend_callback | Up | newt_textbox_get_num_lines


newt_textbox

(PECL)

newt_textbox --

Description

resource newt_textbox ( int left, int top, int width, int height [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

width

Its description

height

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_textbox_set_text | Up | newt_vertical_scrollbar


newt_textbox_get_num_lines

(PECL)

newt_textbox_get_num_lines --

Description

int newt_textbox_get_num_lines ( resource textbox )

Warning

This function is currently not documented; only the argument list is available.

Parameters

textbox

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_suspend | Up | newt_textbox_reflowed


newt_textbox_reflowed

(PECL)

newt_textbox_reflowed --

Description

resource newt_textbox_reflowed ( int left, int top, char *text, int width, int flex_down, int flex_up [, int flags] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

*text

Its description

width

Its description

flex_down

Its description

flex_up

Its description

flags

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_textbox_get_num_lines | Up | newt_textbox_set_height


newt_textbox_set_height

(PECL)

newt_textbox_set_height --

Description

void newt_textbox_set_height ( resource textbox, int height )

Warning

This function is currently not documented; only the argument list is available.

Parameters

textbox

Its description

height

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_textbox_reflowed | Up | newt_textbox_set_text


newt_textbox_set_text

(PECL)

newt_textbox_set_text --

Description

void newt_textbox_set_text ( resource textbox, string text )

Warning

This function is currently not documented; only the argument list is available.

Parameters

textbox

Its description

text

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_textbox_set_height | Up | newt_textbox


newt_vertical_scrollbar

(PECL)

newt_vertical_scrollbar --

Description

resource newt_vertical_scrollbar ( int left, int top, int height [, int normal_colorset [, int thumb_colorset]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

left

Its description

top

Its description

height

Its description

normal_colorset

Its description

thumb_colorset

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_textbox | Up | newt_wait_for_key


newt_wait_for_key

(PECL)

newt_wait_for_key -- Doesn't return until a key has been pressed

Description

void newt_wait_for_key ( void )

This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.

See Also

newt_clear_key_buffer()

Prev | Home | Next
newt_vertical_scrollbar | Up | newt_win_choice


newt_win_choice

(PECL)

newt_win_choice --

Description

int newt_win_choice ( string title, string button1_text, string button2_text, string format [, mixed args [, mixed ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

button1_text

Its description

button2_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_wait_for_key | Up | newt_win_entries


newt_win_entries

(PECL)

newt_win_entries --

Description

int newt_win_entries ( string title, string text, int suggested_width, int flex_down, int flex_up, int data_width, array &items, string button1 [, string ...] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

text

Its description

suggested_width

Its description

flex_down

Its description

flex_up

Its description

data_width

Its description

items

Its description

button1

Its description

button2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_win_choice | Up | newt_win_menu


newt_win_menu

(PECL)

newt_win_menu --

Description

int newt_win_menu ( string title, string text, int suggestedWidth, int flexDown, int flexUp, int maxListHeight, array items, int &listItem [, string button1 [, string ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

text

Its description

suggestedWidth

Its description

flexDown

Its description

flexUp

Its description

maxListHeight

Its description

items

Its description

listItem

Its description

button1

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_win_entries | Up | newt_win_message


newt_win_message

(PECL)

newt_win_message --

Description

void newt_win_message ( string title, string button_text, string format [, mixed args [, mixed ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

button_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_win_menu | Up | newt_win_messagev


newt_win_messagev

(PECL)

newt_win_messagev --

Description

void newt_win_messagev ( string title, string button_text, string format, array args )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

button_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_win_message | Up | newt_win_ternary


newt_win_ternary

(PECL)

newt_win_ternary --

Description

int newt_win_ternary ( string title, string button1_text, string button2_text, string button3_text, string format [, mixed args [, mixed ...]] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
newt_win_messagev | Up | NSAPI-specific Functions


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().

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 ext/mbstrings mb_output_handler and ext/sessions URL-Rewriter (AKA session.use_trans_sid).

Prev | Home | Next
http_negotiate_language | Up | ob_etaghandler


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().

Prev | Home | Next
ob_deflatehandler | Up | ob_inflatehandler


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.

Prev | Home | Next
ob_etaghandler | Up | http_parse_cookie


oci_bind_array_by_name

(no version information, might be only in CVS)

oci_bind_array_by_name -- Binds PHP array to Oracle PL/SQL array by name

Description

bool oci_bind_array_by_name ( resource statement, string name, array &var_array, int max_table_length [, int max_item_length [, int type]] )

Binds the PHP array var_array to the Oracle placeholder name, which points to Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

Parameters

statement

A valid OCI statement identifier.

name

The Oracle placeholder.

var_array

An array.

max_table_length

Sets the maximum length both for incoming and result arrays.

max_item_length

Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will use find the longest element in the incoming array and will use it as maximum length for array items.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. oci_bind_array_by_name()example

&#60;?php

$c = oci_connect("scott", "tiger");

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$statement = oci_parse($c, $create);
oci_execute($statement);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg);
oci_execute($statement);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    FOR i IN 1..5 LOOP
      INSERT INTO bind_example VALUES (c1(i));
    END LOOP;
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg_body);
oci_execute($statement);

$statement = oci_parse($c, "BEGIN ARRAYBINDPKG1.iobind(:c1); END;");

$array = array("one", "two", "three", "four", "five");

oci_bind_array_by_name($statement, ":c1", $array, 5, -1, SQLT_CHR);

oci_execute($statement);

var_dump($array);

?&#62;

Notes

Note: This function is available since OCI8 release 1.2.

Prev | Home | Next
Oracle Functions | Up | oci_bind_by_name


OCI-Collection->assignElem

(no version information, might be only in CVS)

OCI-Collection->assignElem -- Assigns a value to the element of the collection

Description

class OCI-Collection {

bool assignElem ( int index, mixed value )

}

Assigns a value to the element with index index.

Parameters

index

The element index. First index is 1.

value

Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Collection->getElem

Prev | Home | Next
OCI-Collection->assign | Up | OCI-Collection->free


OCI-Collection->getElem

(no version information, might be only in CVS)

OCI-Collection->getElem -- Returns value of the element

Description

class OCI-Collection {

mixed getElem ( int index )

}

Returns element's value with the index index (1-based).

Parameters

index

The element index. First index is 1.

Return Values

Returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.

See Also

OCI-Collection->assignElem

Prev | Home | Next
OCI-Collection->free | Up | OCI-Collection->max


OCI-Lob->free

(no version information, might be only in CVS)

OCI-Lob->free -- Frees resources associated with the LOB descriptor

Description

class OCI-Lob {

bool free ( void )

}

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
OCI-Lob->flush | Up | OCI-Lob->getBuffering


OCI-Lob->getBuffering

(no version information, might be only in CVS)

OCI-Lob->getBuffering -- Returns current state of buffering for the large object

Description

class OCI-Lob {

bool getBuffering ( void )

}

Tells whether the buffering for the large object is on or off.

Return Values

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

See Also

OCI-Lob->setBuffering

Prev | Home | Next
OCI-Lob->free | Up | OCI-Lob->import


OCI-Lob->saveFile

(no version information, might be only in CVS)

OCI-Lob->saveFile -- Alias of oci_lob_import()

Description

This function is an alias of: oci_lob_import().

Prev | Home | Next
OCI-Lob->save | Up | OCI-Lob->seek


OCI-Lob->setBuffering

(no version information, might be only in CVS)

OCI-Lob->setBuffering -- Changes current state of buffering for the large object

Description

class OCI-Lob {

bool setBuffering ( bool on_off )

}

Sets the buffering for the large object, depending on the value of the on_off parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. oci_lob_flush() should be used to flush buffers, when you have finished working with the large object.

Parameters

on_off

TRUE for on and FALSE for off.

Return Values

Returns TRUE on success or FALSE on failure. Repeated calls to this method with the same flag will return TRUE.

See Also

OCI-Lob->getBuffering

Prev | Home | Next
OCI-Lob->seek | Up | OCI-Lob->size


OCI-Lob->writeTemporary

(no version information, might be only in CVS)

OCI-Lob->writeTemporary -- Writes temporary large object

Description

class OCI-Lob {

bool writeTemporary ( string data [, int lob_type] )

}

Creates a temporary large object and writes data to it.

You should use OCI-Lob->close when you are done with this object.

Parameters

data

The data to write.

lob_type

Can be one of the following:

OCI_TEMP_BLOB is used to create temporary BLOBs
OCI_TEMP_CLOB (default value) is used to create temporary CLOBs

Return Values

Returns TRUE on success or FALSE on failure.

See Also

OCI-Lob->close

Prev | Home | Next
OCI-Lob->write | Up | OCI-Lob->writeToFile


OCI-Lob->writeToFile

(no version information, might be only in CVS)

OCI-Lob->writeToFile -- Alias of oci_lob_export()

Description

This function is an alias of: oci_lob_export().

Prev | Home | Next
OCI-Lob->writeTemporary | Up | oci_new_collection


openssl_csr_get_public_key

(no version information, might be only in CVS)

openssl_csr_get_public_key -- Returns the public key of a CERT

Description

mixed openssl_csr_get_public_key ( mixed csr, bool use_shortnames )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
openssl_csr_export | Up | openssl_csr_get_subject


openssl_csr_get_subject

(no version information, might be only in CVS)

openssl_csr_get_subject -- Returns the subject of a CERT

Description

mixed openssl_csr_get_subject ( mixed csr, bool use_shortnames )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
openssl_csr_get_public_key | Up | openssl_csr_new


openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_free -- Frees a private key

Description

void openssl_pkey_free ( resource key )

This function frees a private key created by openssl_pkey_new().

Prev | Home | Next
openssl_pkey_export | Up | openssl_pkey_get_details


openssl_pkey_get_details

(no version information, might be only in CVS)

openssl_pkey_get_details -- Returns an array with the key details (bits, pkey, type)

Description

resource openssl_pkey_get_details ( resource key )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
openssl_pkey_free | Up | openssl_pkey_get_private


OrbitEnum

(no version information, might be only in CVS)

OrbitEnum -- Use CORBA enums

Description

new OrbitEnum ( string id )

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.

This class represents the enumeration identified with the id parameter.

Parameters

id

Can be either the name of the enumeration (e.g "MyEnum"), or the full repository id (e.g. "IDL:MyEnum:1.0").

Examples

Example 1. Sample IDL file

enum MyEnum {
    a,b,c,d,e
};

Example 2. PHP code for accessing MyEnum

&#60;?php
$enum = new OrbitEnum ("MyEnum");

echo $enum-&#62;a;    /* write 0 */
echo $enum-&#62;c;    /* write 2 */
echo $enum-&#62;e;    /* write 4 */
?&#62;

Prev | Home | Next
Satellite CORBA client extension [deprecated] | Up | OrbitObject


OrbitObject

(no version information, might be only in CVS)

OrbitObject -- Access CORBA objects

Description

new OrbitObject ( string ior )

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.

This class provides access to a CORBA object.

Parameters

ior

Should be a string containing the IOR (Interoperable Object Reference) that identifies the remote object.

Examples

Example 1. Sample IDL file

interface MyInterface {
    void SetInfo (string info);
    string GetInfo();

    attribute int value;
}

Example 2. PHP code for accessing MyInterface

&#60;?php
$obj = new OrbitObject ($ior);

$obj-&#62;SetInfo ("A 2GooD object");

echo $obj-&#62;GetInfo();

$obj-&#62;value = 42;

echo $obj-&#62;value;
?&#62;

Prev | Home | Next
OrbitEnum | Up | OrbitStruct


OrbitStruct

(no version information, might be only in CVS)

OrbitStruct -- Use CORBA structs

Description

new OrbitStruct ( string id )

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.

This class represents the structure identified with the id parameter.

Parameters

id

Can be either the name of the struct (e.g "MyStruct"), or the full repository id (e.g. "IDL:MyStruct:1.0").

Examples

Example 1. Sample IDL file

struct MyStruct {
    short shortvalue;
    string stringvalue;
};

interface SomeInterface {
  void SetValues (MyStruct values);
  MyStruct GetValues();
}

Example 2. PHP code for accessing MyStruct

&#60;?php
$obj = new OrbitObject ($ior);

$initial_values = new OrbitStruct ("IDL:MyStruct:1.0");
$initial_values-&#62;shortvalue = 42;
$initial_values-&#62;stringvalue = "HGTTG";

$obj-&#62;SetValues ($initial_values);

$values = $obj-&#62;GetValues();

echo $values-&#62;shortvalue;
echo $values-&#62;stringvalue;
?&#62;

Prev | Home | Next
OrbitObject | Up | satellite_caught_exception


PDF_activate_item

(PECL)

PDF_activate_item -- Activate structure element or other content item

Description

bool PDF_activate_item ( resource pdfdoc, int id )

Activates a previously created structure element or other content item. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF Functions | Up | PDF_add_annotation


PDF_add_nameddest

(PECL)

PDF_add_nameddest -- Create named destination

Description

bool PDF_add_nameddest ( resource pdfdoc, string name, string optlist )

Creates a named destination on an arbitrary page in the current document. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_add_locallink | Up | PDF_add_note


PDF_begin_document

(PECL)

PDF_begin_document -- Create new PDF file

Description

int PDF_begin_document ( resource pdfdoc, string filename, string optlist )

Creates a new PDF file subject to various options.

Prev | Home | Next
PDF_attach_file | Up | PDF_begin_font


PDF_begin_font

(PECL)

PDF_begin_font -- Start a Type 3 font definition

Description

bool PDF_begin_font ( resource pdfdoc, string filename, float a, float b, float c, float d, float e, float f, string optlist )

Starts a Type 3 font definition.

Prev | Home | Next
PDF_begin_document | Up | PDF_begin_glyph


PDF_begin_glyph

(PECL)

PDF_begin_glyph -- Start glyph definition for Type 3 font

Description

bool PDF_begin_glyph ( resource pdfdoc, string glyphname, float wx, float llx, float lly, float urx, float ury )

Starts a glyph definition for a Type 3 font.

Prev | Home | Next
PDF_begin_font | Up | PDF_begin_item


PDF_begin_item

(PECL)

PDF_begin_item -- Open structure element or other content item

Description

int PDF_begin_item ( resource pdfdoc, string tag, string optlist )

Opens a structure element or other content item with attributes supplied as options.

Prev | Home | Next
PDF_begin_glyph | Up | PDF_begin_layer


PDF_begin_layer

(PECL)

PDF_begin_layer -- Start layer

Description

bool PDF_begin_layer ( resource pdfdoc, int layer )

Starts a layer for subsequent output on the page. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

Prev | Home | Next
PDF_begin_item | Up | PDF_begin_page_ext


PDF_begin_page_ext

(PECL)

PDF_begin_page_ext -- Start new page

Description

bool PDF_begin_page_ext ( resource pdfdoc, float width, float height, string optlist )

Adds a new page to the document, and specifies various options. The parameters width and height are the dimensions of the new page in points. Returns TRUE on success or FALSE on failure.

Table 1. Common Page Sizes in Points

name | size
A0 | 2380?3368
A1 | 1684?2380
A2 | 1190?1684
A3 | 842?1190
A4 | 595?842
A5 | 421?595
A6 | 297?421
B5 | 501?709
letter (8.5"?11") | 612?792
legal (8.5"?14") | 612?1008
ledger (17"?11") | 1224?792
11"?17" | 792?1224

Prev | Home | Next
PDF_begin_layer | Up | PDF_begin_page


PDF_create_action

(PECL)

PDF_create_action -- Create action for objects or events

Description

int PDF_create_action ( resource pdfdoc, string type, string optlist )

Creates an action which can be applied to various objects and events.

Prev | Home | Next
PDF_continue_text | Up | PDF_create_annotation


PDF_create_annotation

(PECL)

PDF_create_annotation -- Create rectangular annotation

Description

bool PDF_create_annotation ( resource pdfdoc, float llx, float lly, float urx, float ury, string type, string optlist )

Creates a rectangular annotation on the current page.

Prev | Home | Next
PDF_create_action | Up | PDF_create_bookmark


PDF_create_bookmark

(PECL)

PDF_create_bookmark -- Create bookmark

Description

int PDF_create_bookmark ( resource pdfdoc, string text, string optlist )

Creates a bookmark subject to various options.

Prev | Home | Next
PDF_create_annotation | Up | PDF_create_field


PDF_create_field

(PECL)

PDF_create_field -- Create form field

Description

bool PDF_create_field ( resource pdfdoc, float llx, float lly, float urx, float ury, string name, string type, string optlist )

Creates a form field on the current page subject to various options.

Prev | Home | Next
PDF_create_bookmark | Up | PDF_create_fieldgroup


PDF_create_fieldgroup

(PECL)

PDF_create_fieldgroup -- Create form field group

Description

bool PDF_create_fieldgroup ( resource pdfdoc, string name, string optlist )

Creates a form field group subject to various options.

Prev | Home | Next
PDF_create_field | Up | PDF_create_gstate


PDF_create_gstate

(PECL)

PDF_create_gstate -- Create graphics state object

Description

int PDF_create_gstate ( resource pdfdoc, string optlist )

Creates a graphics state object subject to various options.

Prev | Home | Next
PDF_create_fieldgroup | Up | PDF_create_pvf


PDF_create_pvf

(PECL)

PDF_create_pvf -- Create PDFlib virtual file

Description

bool PDF_create_pvf ( resource pdfdoc, string filename, string data, string optlist )

Creates a named virtual read-only file from data provided in memory.

Prev | Home | Next
PDF_create_gstate | Up | PDF_create_textflow


PDF_create_textflow

(PECL)

PDF_create_textflow -- Create textflow object

Description

int PDF_create_textflow ( resource pdfdoc, string text, string optlist )

Preprocesses text for later formatting and creates a textflow object.

Prev | Home | Next
PDF_create_pvf | Up | PDF_curveto


PDF_define_layer

(PECL)

PDF_define_layer -- Create layer definition

Description

int PDF_define_layer ( resource pdfdoc, string name, string optlist )

Creates a new layer definition.

This function requires PDF 1.5.

Prev | Home | Next
PDF_curveto | Up | PDF_delete_pvf


PDF_delete_pvf

(PECL)

PDF_delete_pvf -- Delete PDFlib virtual file

Description

int PDF_delete_pvf ( resource pdfdoc, string filename )

Deletes a named virtual file and frees its data structures (but not the contents).

Prev | Home | Next
PDF_define_layer | Up | PDF_delete_textflow


PDF_delete_textflow

(PECL)

PDF_delete_textflow -- Delete textflow object

Description

bool PDF_delete_textflow ( resource pdfdoc, int textflow )

Deletes a textflow and the associated data structures.

Prev | Home | Next
PDF_delete_pvf | Up | PDF_delete


PDF_encoding_set_char

(PECL)

PDF_encoding_set_char -- Add glyph name and/or Unicode value

Description

bool PDF_encoding_set_char ( resource pdfdoc, string encoding, int slot, string glyphname, int uv )

Adds a glyph name and/or Unicode value to a custom encoding.

Prev | Home | Next
PDF_delete | Up | PDF_end_document


PDF_end_document

(PECL)

PDF_end_document -- Close PDF file

Description

bool PDF_end_document ( resource pdfdoc, string optlist )

Closes the generated PDF file and applies various options.

Prev | Home | Next
PDF_encoding_set_char | Up | PDF_end_font


PDF_end_font

(PECL)

PDF_end_font -- Terminate Type 3 font definition

Description

bool PDF_end_font ( resource pdfdoc )

Terminates a Type 3 font definition.

Prev | Home | Next
PDF_end_document | Up | PDF_end_glyph


PDF_end_glyph

(PECL)

PDF_end_glyph -- Terminate glyph definition for Type 3 font

Description

bool PDF_end_glyph ( resource pdfdoc )

Terminates a glyph definition for a Type 3 font.

Prev | Home | Next
PDF_end_font | Up | PDF_end_item


PDF_end_item

(PECL)

PDF_end_item -- Close structure element or other content item

Description

bool PDF_end_item ( resource pdfdoc, int id )

Closes a structure element or other content item.

Prev | Home | Next
PDF_end_glyph | Up | PDF_end_layer


PDF_end_layer

(PECL)

PDF_end_layer -- Deactivate all active layers

Description

bool PDF_end_layer ( resource pdfdoc )

Deactivates all active layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

Prev | Home | Next
PDF_end_item | Up | PDF_end_page_ext


PDF_end_page_ext

(PECL)

PDF_end_page_ext -- Finish page

Description

bool PDF_end_page_ext ( resource pdfdoc, string optlist )

Finishes a page, and applies various options. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_end_layer | Up | PDF_end_page


PDF_fill_imageblock

(PECL)

PDF_fill_imageblock -- Fill image block with variable data

Description

int PDF_fill_imageblock ( resource pdfdoc, int page, string blockname, int image, string optlist )

Fills an image block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

Prev | Home | Next
PDF_endpath | Up | PDF_fill_pdfblock


PDF_fill_pdfblock

(PECL)

PDF_fill_pdfblock -- Fill PDF block with variable data

Description

int PDF_fill_pdfblock ( resource pdfdoc, int page, string blockname, int contents, string optlist )

Fills a PDF block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

Prev | Home | Next
PDF_fill_imageblock | Up | PDF_fill_stroke


PDF_fill_textblock

(PECL)

PDF_fill_textblock -- Fill text block with variable data

Description

int PDF_fill_textblock ( resource pdfdoc, int page, string blockname, string text, string optlist )

Fills a text block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

Prev | Home | Next
PDF_fill_stroke | Up | PDF_fill


PDF_fit_image

(PECL)

PDF_fit_image -- Place image or template

Description

bool PDF_fit_image ( resource pdfdoc, int image, float x, float y, string optlist )

Places an image or template on the page, subject to various options. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_findfont | Up | PDF_fit_pdi_page


PDF_fit_pdi_page

(PECL)

PDF_fit_pdi_page -- Place imported PDF page

Description

bool PDF_fit_pdi_page ( resource pdfdoc, int page, float x, float y, string optlist )

Places an imported PDF page on the page, subject to various options. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_fit_image | Up | PDF_fit_textflow


PDF_fit_textflow

(PECL)

PDF_fit_textflow -- Format textflow in rectangular area

Description

string PDF_fit_textflow ( resource pdfdoc, int textflow, float llx, float lly, float urx, float ury, string optlist )

Formats the next portion of a textflow into a rectangular area.

Prev | Home | Next
PDF_fit_pdi_page | Up | PDF_fit_textline


PDF_fit_textline

(PECL)

PDF_fit_textline -- Place single line of text

Description

bool PDF_fit_textline ( resource pdfdoc, string text, float x, float y, string optlist )

Places a single line of text on the page, subject to various options. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_fit_textflow | Up | PDF_get_apiname


PDF_get_apiname

(PECL)

PDF_get_apiname -- Get name of unsuccessfull API function

Description

string PDF_get_apiname ( resource pdfdoc )

Gets the name of the API function which threw the last exception or failed.

Prev | Home | Next
PDF_fit_textline | Up | PDF_get_buffer


PDF_get_errmsg

(PECL)

PDF_get_errmsg -- Get error text

Description

string PDF_get_errmsg ( resource pdfdoc )

Gets the text of the last thrown exception or the reason for a failed function call.

Prev | Home | Next
PDF_get_buffer | Up | PDF_get_errnum


PDF_get_errnum

(PECL)

PDF_get_errnum -- Get error number

Description

int PDF_get_errnum ( resource pdfdoc )

Gets the number of the last thrown exception or the reason for a failed function call.

Prev | Home | Next
PDF_get_errmsg | Up | PDF_get_font


PDF_info_textflow

(PECL)

PDF_info_textflow -- Query textflow state

Description

float PDF_info_textflow ( resource pdfdoc, int textflow, string keyword )

Queries the current state of a textflow.

Prev | Home | Next
PDF_get_value | Up | PDF_initgraphics


PDF_load_font

(PECL)

PDF_load_font -- Search and prepare font

Description

int PDF_load_font ( resource pdfdoc, string fontname, string encoding, string optlist )

Searches for a font and prepares it for later use.

Prev | Home | Next
PDF_lineto | Up | PDF_load_iccprofile


PDF_load_iccprofile

(PECL)

PDF_load_iccprofile -- Search and prepare ICC profile

Description

int PDF_load_iccprofile ( resource pdfdoc, string profilename, string optlist )

Searches for an ICC profile, and prepares it for later use.

Prev | Home | Next
PDF_load_font | Up | PDF_load_image


PDF_load_image

(PECL)

PDF_load_image -- Open image file

Description

int PDF_load_image ( resource pdfdoc, string imagetype, string filename, string optlist )

Opens a disk-based or virtual image file subject to various options.

Prev | Home | Next
PDF_load_iccprofile | Up | PDF_makespotcolor


PDF_process_pdi

(PECL)

PDF_process_pdi -- Process imported PDF document

Description

int PDF_process_pdi ( resource pdfdoc, int doc, int page, string optlist )

Processes certain elements of an imported PDF document.

Prev | Home | Next
PDF_place_pdi_page | Up | PDF_rect


PDF_resume_page

(PECL)

PDF_resume_page -- Resume page

Description

bool PDF_resume_page ( resource pdfdoc, string optlist )

Resumes a page to add more content to it.

Prev | Home | Next
PDF_restore | Up | PDF_rotate


PDF_set_gstate

(PECL)

PDF_set_gstate -- Activate graphics state object

Description

bool PDF_set_gstate ( resource pdfdoc, int gstate )

Activates a graphics state object.

Prev | Home | Next
PDF_set_duration | Up | PDF_set_horiz_scaling


PDF_set_layer_dependency

(PECL)

PDF_set_layer_dependency -- Define relationships among layers

Description

bool PDF_set_layer_dependency ( resource pdfdoc, string type, string optlist )

Defines hierarchical and group relationships among layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

Prev | Home | Next
PDF_set_info | Up | PDF_set_leading


PDF_setdashpattern

(PECL)

PDF_setdashpattern -- Set dash pattern

Description

bool PDF_setdashpattern ( resource pdfdoc, string optlist )

Sets a dash pattern defined by an option list. Returns TRUE on success or FALSE on failure.

Prev | Home | Next
PDF_setdash | Up | PDF_setflat


PDF_shading

(PECL)

PDF_shading -- Define blend

Description

int PDF_shading ( resource pdfdoc, string shtype, float x0, float y0, float x1, float y1, float c1, float c2, float c3, float c4, string optlist )

Defines a blend from the current fill color to another color.

This function requires PDF 1.4 or above.

Prev | Home | Next
PDF_shading_pattern | Up | PDF_shfill


PDF_shading_pattern

(PECL)

PDF_shading_pattern -- Define shading pattern

Description

int PDF_shading_pattern ( resource pdfdoc, int shading, string optlist )

Defines a shading pattern using a shading object.

This function requires PDF 1.4 or above.

Prev | Home | Next
PDF_setrgbcolor | Up | PDF_shading


PDF_shfill

(PECL)

PDF_shfill -- Fill area with shading

Description

bool PDF_shfill ( resource pdfdoc, int shading )

Fills an area with a shading, based on a shading object.

This function requires PDF 1.4 or above.

Prev | Home | Next
PDF_shading | Up | PDF_show_boxed


PDF_suspend_page

(PECL)

PDF_suspend_page -- Suspend page

Description

bool PDF_suspend_page ( resource pdfdoc, string optlist )

Suspends the current page so that it can later be resumed with PDF_resume_page().

Prev | Home | Next
PDF_stroke | Up | PDF_translate


PDF_utf8_to_utf16

(PECL)

PDF_utf8_to_utf16 -- Convert string from UTF-8 to UTF-16

Description

string PDF_utf8_to_utf16 ( resource pdfdoc, string utf8string, string ordering )

Converts a string from UTF-8 format to UTF-16.

Prev | Home | Next
PDF_utf16_to_utf8 | Up | PDO Functions


PDF_utf16_to_utf8

(PECL)

PDF_utf16_to_utf8 -- Convert string from UTF-16 to UTF-8

Description

string PDF_utf16_to_utf8 ( resource pdfdoc, string utf16string )

Converts a string from UTF-16 format to UTF-8.

Prev | Home | Next
PDF_translate | Up | PDF_utf8_to_utf16


PDO->getAvailableDrivers()

(no version information, might be only in CVS)

PDO->getAvailableDrivers() -- Return an array of available PDO drivers

Description

class PDO {

array getAvailableDrivers ( void )

}

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO->__construct(). This is a static method.

Return Values

PDO->getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Examples

Example 1. A PDO->getAvailableDrivers() example

&#60;?php
print_r(PDO::getAvailableDrivers());
?&#62;

The above example will output something similar to:

Array
(
    [0] => mysql
    [1] => sqlite
)

Prev | Home | Next
PDO->getAttribute() | Up | PDO->lastInsertId()


PDO::pgsqlLOBCreate

(no version information, might be only in CVS)

PDO::pgsqlLOBCreate -- Creates a new large object

Description

string PDO::pgsqlLOBCreate ( void )

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling PDO::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Note: This function must be called within a transaction.

Parameters

PDO::pgsqlLOBCreate() takes no parameters.

Return Values

Returns the OID of the newly created large object on success, or FALSE on failure.

Examples

Example 1. A PDO::pgsqlLOBCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

&#60;?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db-&#62;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db-&#62;beginTransaction();
$oid = $db-&#62;pgsqlLOBCreate();
$stream = $db-&#62;pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db-&#62;prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt-&#62;execute(array($some_id, $oid));
$db-&#62;commit();
?&#62;

See Also

PDO::pgsqlLOBOpen()
PDO::pgsqlLOBUnlink()
pg_lo_create()

Prev | Home | Next
PDO_PGSQL DSN | Up | PDO::pgsqlLOBOpen


PDO::pgsqlLOBOpen

(no version information, might be only in CVS)

PDO::pgsqlLOBOpen -- Opens an existing large object stream

Description

resource PDO::pgsqlLOBOpen ( string oid [, string mode] )

PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid. If mode is r, the stream is opened for reading, if mode is w, then the stream will be opened for writing. You can use all the usual filesystem functions, such as fread(), fwrite() and fgets() to manipulate the contents of the stream.

Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

Parameters

oid

A large object identifier.

mode

If mode is r, open the stream for reading. If mode is w, open the stream for writing.

Return Values

Returns a stream resource on success, or FALSE on failure.

Examples

Example 1. A PDO::pgsqlLOBOpen() example

Following on from the PDO::pgsqlLOBCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

&#60;?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db-&#62;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db-&#62;beginTransaction();
$stmt = $db-&#62;prepare("select oid from BLOBS where ident = ?");
$stmt-&#62;execute(array($some_id));
$stmt-&#62;bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt-&#62;fetch(PDO::FETCH_BOUND);
fpassthru($lob);
?&#62;

See Also

PDO::pgsqlLOBCreate()
PDO::pgsqlLOBUnlink()
pg_lo_open()

Prev | Home | Next
PDO::pgsqlLOBCreate | Up | PDO::pgsqlLOBUnlink


PDO::pgsqlLOBUnlink

(no version information, might be only in CVS)

PDO::pgsqlLOBUnlink -- Deletes the large object

Description

bool PDO::pgsqlLOBUnlink ( string oid )

Deletes a large object from the database identified by OID.

Note: This function must be called within a transaction.

Parameters

oid

A large object identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

&#60;?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db-&#62;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db-&#62;beginTransaction();
$db-&#62;pgsqlLOBUnlink($oid);
$stmt = $db-&#62;prepare("DELETE FROM BLOBS where ident = ?");
$stmt-&#62;execute(array($some_id));
$db-&#62;commit();
?&#62;

See Also

PDO::pgsqlLOBOpen()
PDO::pgsqlLOBCreate()

Prev | Home | Next
PDO::pgsqlLOBOpen | Up | Printer Functions


PDO->sqliteCreateAggregate()

(no version information, might be only in CVS)

PDO->sqliteCreateAggregate() -- Registers an aggregating User Defined Function for use in SQL statements

Description

class PDO {

bool sqliteCreateAggregate ( string function_name, callback step_func, callback finalize_func [, int num_args] )

}

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.

This method is similar to PDO->sqliteCreateFunction() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this method and PDO->sqliteCreateFunction() is that two functions are required to manage the aggregate.

Parameters

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as: step ( mixed context, int rownumber, mixed value1 [, mixed value2 [, mixed ..]] )

context will be NULL for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber will hold the current row number.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as: fini ( mixed context, int rownumber )

context will hold the return value from the very last call to the step function.

rownumber will hold the number of rows over which the aggregate was performed.

The return value of this function will be used as the return value for the aggregate.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Examples

Example 1. max_length aggregation function example

&#60;?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('sqlite::memory:');
$db-&#62;exec("CREATE TABLE strings(a)");
$insert = $db-&#62;prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
    $insert-&#62;execute(array($str));
}
$insert = null;

function max_len_step(&#38;$context, $rownumber, $string)
{
    if (strlen($string) &#62; $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&#38;$context, $rownumber)
{
    return $context;
}

$db-&#62;sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db-&#62;query('SELECT max_len(a) from strings')-&#62;fetchAll());

?&#62;

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip: It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip: You can use PDO->sqliteCreateFunction() and PDO->sqliteCreateAggregate() to override SQLite native SQL functions.

Note: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

PDO->sqliteCreateFunction()
sqlite_create_function()
sqlite_create_aggregate()

Prev | Home | Next
PDO_SQLITE DSN | Up | PDO->sqliteCreateFunction()


PDO->sqliteCreateFunction()

(no version information, might be only in CVS)

PDO->sqliteCreateFunction() -- Registers a User Defined Function for use in SQL statements

Description

class PDO {

bool sqliteCreateFunction ( string function_name, callback callback [, int num_args] )

}

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.

This method allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Examples

Example 1. PDO::sqliteCreateFunction() example

&#60;?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db-&#62;sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db-&#62;query('SELECT md5rev(filename) FROM files')-&#62;fetchAll();
?&#62;

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach() loop after you have queried for the data.

Tip: You can use PDO->sqliteCreateFunction() and PDO->sqliteCreateAggregate() to override SQLite native SQL functions.

Note: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

PDO->sqliteCreateAggregate()
sqlite_create_function()
sqlite_create_aggregate()

Prev | Home | Next
PDO->sqliteCreateAggregate() | Up | Secure Shell2 Functions


PDOStatement->bindValue()

(no version information, might be only in CVS)

PDOStatement->bindValue() -- Binds a value to a parameter

Description

class PDOStatement {

bool bindValue ( mixed parameter, mixed value [, int data_type] )

}

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.

Parameters

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

value

The value to bind to the parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Execute a prepared statement with named placeholders

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; :calories AND colour = :colour');
$sth-&#62;bindValue(':calories', $calories, PDO::PARAM_INT);
$sth-&#62;bindValue(':colour', $colour, PDO::PARAM_STR);
$sth-&#62;execute();
?&#62;

Example 2. Execute a prepared statement with question mark placeholders

&#60;?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh-&#62;prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories &#60; ? AND colour = ?');
$sth-&#62;bindValue(1, $calories, PDO::PARAM_INT);
$sth-&#62;bindValue(2, $colour, PDO::PARAM_STR);
$sth-&#62;execute();
?&#62;

See Also

PDO->prepare()
PDOStatement->execute()
PDOStatement->bindParam()

Prev | Home | Next
PDOStatement->bindParam() | Up | PDOStatement->closeCursor()


PDOStatement->closeCursor()

(no version information, might be only in CVS)

PDOStatement->closeCursor() -- Closes the cursor, enabling the statement to be executed again.

Description

class PDOStatement {

bool closeCursor ( void )

}

PDOStatement->closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.

PDOStatement->closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:

&#60;?php
do {
    while ($stmt-&#62;fetch())
        ;
    if (!$stmt-&#62;nextRowset())
        break;
} while (true);
?&#62;

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A PDOStatement->closeCursor() example

In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement->closeCursor() on $stmt before executing the $otherStmt PDOStatement object.

&#60;?php
/* Create a PDOStatement object */
$stmt = $dbh-&#62;prepare('SELECT foo FROM bar');

/* Create a second PDOStatement object */
$otherStmt = $dbh-&#62;prepare('SELECT foobaz FROM foobar');

/* Execute the first statement */
$stmt-&#62;execute();

/* Fetch only the first row from the results */
$stmt-&#62;fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt-&#62;closeCursor();

/* Now we can execute the second statement */
$otherStmt-&#62;execute();
?&#62;

See Also

PDOStatement->execute()

Prev | Home | Next
PDOStatement->bindValue() | Up | PDOStatement->columnCount()


PDOStatement->fetchColumn()

(no version information, might be only in CVS)

PDOStatement->fetchColumn() -- Returns a single column from the next row of a result set

Description

class PDOStatement {

string fetchColumn ( [int column_number] )

}

Returns a single column from the next row of a result set or FALSE if there are no more rows.

Parameters

column_number

0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement->fetchColumn() fetches the first column.

Return Values

PDOStatement->fetchColumn() returns a single column in the next row of a result set.

Warning

There is no way to return another column from the same row if you use PDOStatement->fetchColumn() to retrieve data.

Examples

Example 1. Return first column of the next row

&#60;?php
$sth = $dbh-&#62;prepare("SELECT name, colour FROM fruit");
$sth-&#62;execute();

/* Fetch the first column from the next row in the result set */
print("Fetch the first column from the next row in the result set:\n");
$result = $sth-&#62;fetchColumn();
print("name = $result\n");

print("Fetch the second column from the next row in the result set:\n");
$result = $sth-&#62;fetchColumn(1);
print("colour = $result\n");
?&#62;

The above example will output:

Fetch the first column from the next row in the result set:
name = lemon
Fetch the second column from the next row in the result set:
colour = red

See Also

PDO->query()
PDOStatement->fetch()
PDOStatement->fetchAll()
PDO->prepare()
PDOStatement->setFetchMode()

Prev | Home | Next
PDOStatement->fetchAll() | Up | PDOStatement->fetchObject()


PDOStatement->fetchObject()

(no version information, might be only in CVS)

PDOStatement->fetchObject() -- Fetches the next row and returns it as an object.

Description

class PDOStatement {

mixed fetchObject ( [string class_name [, array ctor_args]] )

}

Fetches the next row and returns it as an object. This function is an
alternative to PDOStatement->fetch() with
PDO::FETCH_CLASS or
PDO::FETCH_OBJ style.

Parameters

class_name

Name of the created class, defaults to stdClass.

ctor_args

Elements of this array are passed to the constructor.

Return Values

Returns an instance of the required class with property names that correspond to the column names or FALSE in case of an error.

See Also

PDOStatement->fetch()

Prev | Home | Next
PDOStatement->fetchColumn() | Up | PDOStatement->getAttribute()


pg_fetch_all_columns

(PHP 5 >= 5.1.0RC1)

pg_fetch_all_columns -- Fetches all rows in a particular result column as an array

Description

array pg_fetch_all_columns ( resource result [, int column] )

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.

Note: This function sets NULL fields to PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Return Values

An array with all values in the result column.

FALSE is returned if column is larger than the number of columns in the result, or on any other error.

Examples

Example 1. pg_fetch_all_columns() example

&#60;?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?&#62;

See Also

pg_fetch_all()

Prev | Home | Next
pg_execute | Up | pg_fetch_all


pg_field_table

(no version information, might be only in CVS)

pg_field_table -- Returns the name or oid of the tables field

Description

mixed pg_field_table ( resource result, int field_number, bool oid_only )

pg_field_table() returns the name of the table that field belongs to, or the table's oid if oid_only is TRUE.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

oid_only

By default the tables name that field belongs to is returned but if oid_only is set to TRUE, then the oid will instead be returned.

Return Values

On success either the fields table name or oid. Or, FALSE on failure.

Examples

Example 1. Getting table information about a field

&#60;?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "SELECT bar FROM foo");

echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);

$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?&#62;

The above example will output something similar to:

foo
14379580

bool(false)

Notes

Note: Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

See Also

pg_field_name()
pg_field_type()

Prev | Home | Next
pg_field_size | Up | pg_field_type_oid


pg_transaction_status

(PHP 5 >= 5.1.0RC1)

pg_transaction_status -- Returns the current in-transaction status of the server.

Description

int pg_transaction_status ( resource connection )

Returns the current in-transaction status of the server.

Caution

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

Examples

Example 1. pg_transaction_status() example

&#60;?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_transaction_status($dbconn);
  if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 'Connection is bad';
  } else if ($stat === PGSQL_TRANSACTION_IDLE) {
      echo 'Connection is currently idle';
  } else {
      echo 'Connection is in a transaction state';
  }
?&#62;

Prev | Home | Next
pg_trace | Up | pg_tty


Phar::apiVersion

(no version information, might be only in CVS)

Phar::apiVersion -- Returns the api version

Description

string Phar::apiVersion ( void )

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer.

Parameters

Return Values

The API version string as in "1.0.0".

Examples

Example 1. A Phar::apiVersion() example

&#60;?php
echo Phar::apiVersion();
?&#62;

The above example will output:

1.0.0

Prev | Home | Next
Phar archive stream and classes | Up | Phar->begin


Phar->begin

(no version information, might be only in CVS)

Phar->begin -- Begin a Phar modification transaction

Description

void Phar->begin ( void )

Although technically unnecessary, the begin() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the begin()/commit() pair of methods is provided for this purpose.

Phar transactions are per-archive, a transaction active on the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Examples

Example 1. A Phar->begin() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p-&#62;count() . " entries\n";
$p-&#62;begin();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']-&#62;setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']-&#62;setMetaData(42);
$p-&#62;setStub("&#60;?php
function __autoload($class)
{
    include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p-&#62;commit();
?&#62;

See Also

Phar->commit()
Phar->getStub()

Prev | Home | Next
Phar::apiVersion | Up | Phar::canCompress


Phar::canCompress

(no version information, might be only in CVS)

Phar::canCompress -- Returns whether phar extension supports compression using either zlib or bzip2

Description

bool Phar::canCompress ( [int type] )

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

Parameters

type

Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

Return Values

TRUE if compression/decompression is available, FALSE if not.

Examples

Example 1. A Phar::canCompress() example

&#60;?php
if (Phar::canCompress()) {
    echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 'no compression available';
}
?&#62;

See Also

PharFileInfo::isCompressed()

Prev | Home | Next
Phar->begin | Up | Phar::canWrite


Phar::canWrite

(no version information, might be only in CVS)

Phar::canWrite -- Returns whether phar extension supports writing and creating phars

Description

bool Phar::canWrite ( void )

This method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

Parameters

Return Values

TRUE if write access is enabled, FALSE if it is disabled.

Examples

Example 1. A Phar::canWrite() example

&#60;?php
if (Phar::canWrite()) {
    file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?&#62;

See Also

phar.readonly

Prev | Home | Next
Phar::canCompress | Up | Phar->commit


Phar->commit

(no version information, might be only in CVS)

Phar->commit -- End a Phar modification transaction by writing the Phar archive to disk

Description

void Phar->commit ( void )

Although technically unnecessary, the begin() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The begin()/commit() pair of methods is provided for this purpose.

Phar transactions are per-archive, a transaction active on the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Errors/Exceptions

PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example 1. A Phar->commit() example

&#60;?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p-&#62;begin();
var_dump($p-&#62;getStub());
$p-&#62;setStub("&#60;?php
function __autoload(\$class)
{
    include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p-&#62;commit();
var_dump($p-&#62;getStub());
?&#62;

The above example will output:

string(24) "<?php __HALT_COMPILER();"
string(195) "<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"

See Also

Phar->begin()

Prev | Home | Next
Phar::canWrite | Up | Phar->compressAllFilesBZIP2


Phar->compressAllFilesBZIP2

(no version information, might be only in CVS)

Phar->compressAllFilesBZIP2 -- Compresses all files in the current Phar archive using Bzip2 compression

Description

bool Phar->compressAllFilesBZIP2 ( void )

This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example 1. A Phar->compressAllFilesBZIP2() example

&#60;?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file-&#62;getFileName());
    var_dump($file-&#62;isCompressed());
    var_dump($file-&#62;isCompressedBZIP2());
    var_dump($file-&#62;isCompressedGZ());
}
$p-&#62;compressAllFilesBZIP2();
foreach ($p as $file) {
    var_dump($file-&#62;getFileName());
    var_dump($file-&#62;isCompressed());
    var_dump($file-&#62;isCompressedBZIP2());
    var_dump($file-&#62;isCompressedGZ());
}
?&#62;

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)

See Also

PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
Phar->uncompressAllFiles()
Phar->compressAllFilesGZ()

Prev | Home | Next
Phar->commit | Up | Phar->compressAllFilesGZ


Phar->compressAllFilesGZ

(no version information, might be only in CVS)

Phar->compressAllFilesGZ -- Compresses all files in the current Phar archive using Gzip compression

Description

bool Phar->compressAllFilesGZ ( void )

This method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example 1. A Phar->compressAllFilesGZ() example

&#60;?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file-&#62;getFileName());
    var_dump($file-&#62;isCompressed());
    var_dump($file-&#62;isCompressedBZIP2());
    var_dump($file-&#62;isCompressedGZ());
}
$p-&#62;compressAllFilesGZ();
foreach ($p as $file) {
    var_dump($file-&#62;getFileName());
    var_dump($file-&#62;isCompressed());
    var_dump($file-&#62;isCompressedBZIP2());
    var_dump($file-&#62;isCompressedGZ());
}
?&#62;

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
Phar->uncompressAllFiles()
Phar->compressAllFilesBZIP2()

Prev | Home | Next
Phar->compressAllFilesBZIP2 | Up | Phar::__construct


Phar::__construct

(no version information, might be only in CVS)

Phar::__construct -- Construct a Phar archive object

Description

void Phar::__construct ( string fname [, int flags [, string alias]] )

Parameters

fname

Path to an existing Phar archive

flags

flags to pass to parent class RecursiveDirectoryIterator. See SPL RecursiveDirectoryIterator docs

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

Errors/Exceptions

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Examples

Example 1. A Phar::__construct() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', CURRENT_AS_FILEINFO | KEY_AS_FILENAME,
                  'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?&#62;

Prev | Home | Next
Phar->compressAllFilesGZ | Up | Phar->count


Phar->count

(no version information, might be only in CVS)

Phar->count -- Returns the number of entries (files) in the Phar archive

Description

int Phar->count ( void )

Parameters

Return Values

The number of files contained within this phar, or 0 (the number zero) if none.

Examples

Example 1. A Phar->count() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p-&#62;count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p-&#62;count() . " entries\n";
?&#62;

The above example will output:

The new phar has 0 entries
The new phar has 1 entries

Prev | Home | Next
Phar::__construct | Up | Phar->getMetaData


Phar->getMetaData

(no version information, might be only in CVS)

Phar->getMetaData -- Returns phar archive meta-data

Description

int Phar->getMetaData ( void )

Parameters

Return Values

any PHP variable that can be serialized and is stored as meta-data for the Phar archive, or NULL if no meta-data is stored.

Examples

Example 1. A Phar->getMetaData() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
$p['file.php'] = '&#60;?php echo "hello";';
$p-&#62;setMetaData(array('bootstrap' =&#62; 'file.php'));
var_dump($p-&#62;getMetaData());
?&#62;

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

PharFileInfo->setMetaData()

Prev | Home | Next
Phar->count | Up | Phar->getModified


Phar->getModified

(no version information, might be only in CVS)

Phar->getModified -- Return whether phar was modified

Description

bool Phar->getModified ( void )

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

Parameters

Return Values

TRUE if the phar has been modified since opened, FALSE if not.

Prev | Home | Next
Phar->getMetaData | Up | Phar->getSignature


Phar->getSignature

(no version information, might be only in CVS)

Phar->getSignature -- Return MD5/SHA1 signature of a Phar archive

Description

array Phar->getSignature ( void )

Returns the verification signature of a phar archive in a hexadecimal string.

Parameters

Return Values

Array with the opened archive's signature in "hash" key and "md5" or "sha1" in "hash_type". This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all phars if the phar.require_hash INI variable is set to true.

Prev | Home | Next
Phar->getModified | Up | Phar->getStub


Phar->getStub

(no version information, might be only in CVS)

Phar->getStub -- Return the PHP loader or bootstrap stub of a Phar archive

Description

string Phar->getStub ( void )

One of the features that differentiates a Phar archive from other familiar archive formats like tar or zip is that a Phar archive is explicitly designed to be included to allow distributing an application or library that can be run without extraction directly from the archive. In order to accomplish this, Phar archives contain a bootstrap loader, or stub written in PHP that can perform any action.

Warning

All stubs must end with __HALT_COMPILER(); or the file is not a valid Phar archive.

Return Values

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

Errors/Exceptions

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

Examples

Example 1. A Phar->getStub() example

$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p-&#62;getStub();
echo "==NEXT==\n";
$p-&#62;setStub("&#60;?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
echo $p-&#62;getStub();

The above example will output:

<?php __HALT_COMPILER();
==NEXT==
<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();

See Also

Phar->setStub()

Prev | Home | Next
Phar->getSignature | Up | Phar->getVersion


Phar->getVersion

(no version information, might be only in CVS)

Phar->getVersion -- Return version info of Phar archive

Description

string Phar->getVersion ( void )

Returns the API version of an opened Phar archive.

Parameters

Return Values

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

See Also

Phar::apiVersion()

Prev | Home | Next
Phar->getStub | Up | Phar->isFlushingToPhar


Phar->isFlushingToPhar

(no version information, might be only in CVS)

Phar->isFlushingToPhar -- Used to determine whether a Phar creation transaction is active

Description

void Phar->isFlushingToPhar ( void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar->commit() is needed to enable saving changes.

Phar transactions are per-archive, a transaction active on the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Examples

Example 1. A Phar->isFlushingToPhar() example

&#60;?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p-&#62;isFlushingToPhar());
var_dump($p2-&#62;isFlushingToPhar());
?&#62;
=2=
&#60;?php
$p-&#62;begin();
var_dump($p-&#62;isFlushingToPhar());
var_dump($p2-&#62;isFlushingToPhar());
$p-&#62;commit();
?&#62;
=3=
&#60;?php
var_dump($p-&#62;isFlushingToPhar());
var_dump($p2-&#62;isFlushingToPhar());
?&#62;

The above example will output:

bool(true)
bool(true)
=2=
bool(false)
bool(true)
=3=
bool(true)
bool(true)

See Also

Phar->begin()
Phar->commit()

Prev | Home | Next
Phar->getVersion | Up | Phar::loadPhar


Phar::loadPhar

(no version information, might be only in CVS)

Phar::loadPhar -- Loads any phar archive with an alias

Description

bool Phar::loadPhar ( string filename [, string alias] )

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

Parameters

filename

the full or relative path to the phar archive to open

alias

The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

Examples

Example 1. A Phar::loadPhar() example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

&#60;?php
try {
    Phar::loadPhar('/path/to/phar.phar', 'my.phar');
    echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
    echo $e;
}
?&#62;

See Also

Phar::mapPhar()

Prev | Home | Next
Phar->isFlushingToPhar | Up | Phar::mapPhar


Phar::mapPhar

(no version information, might be only in CVS)

Phar::mapPhar -- Reads the currently executed file (a phar) and registers its manifest

Description

bool Phar::mapPhar ( [string alias] )

This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.

Parameters

alias

The alias with which this phar should be referred to.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.

Examples

Example 1. A Phar::mapPhar() example

mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.

Here is a sample Phar loader stub that uses mapPhar.

&#60;?php
function __autoload($class)
{
    include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
    Phar::mapPhar('me.phar');
    include 'phar://me.phar/startup.php';
} catch (PharException $e) {
    echo $e-&#62;getMessage();
    die('Cannot initialize Phar');
}
__HALT_COMPILER();

See Also

Phar::loadPhar()

Prev | Home | Next
Phar::loadPhar | Up | Phar::offsetExists


Phar::offsetExists

(no version information, might be only in CVS)

Phar::offsetExists -- determines whether a file exists in the phar

Description

bool Phar::offsetExists ( string offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset() is called.

Parameters

offset

The filename (relative path) to look for in a Phar.

Return Values

Returns TRUE if the file exists within the phar, or FALSE if not.

Examples

Example 1. A Phar::offsetExists() example

&#60;?php
$p = new Phar(dirname(__FILE__) . '/my.phar', 0, 'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?&#62;

The above example will output:

bool(true)
bool(false)

See Also

Phar::offsetGet()
Phar::offsetSet()
Phar::offsetUnset()

Prev | Home | Next
Phar::mapPhar | Up | Phar::offsetGet


Phar::offsetGet

(no version information, might be only in CVS)

Phar::offsetGet -- get a PharFileInfo object for a specific file

Description

int Phar::offsetGet ( string offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetGet is used for retrieving files from a Phar archive.

Parameters

offset

The filename (relative path) to look for in a Phar.

Return Values

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

Errors/Exceptions

This method throws BadMethodCallException if the file does not exist in the Phar archive.

Examples

Example 1. A Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, offsetGet is automatically called when using the [] angle bracket operator

&#60;?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
    // automatically calls offsetGet()
    echo $p['exists.txt'];
    echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
    echo $e;
}
?&#62;

The above example will output:

file exists
Entry doesnotexist.txt does not exist

See Also

Phar::offsetExists()
Phar::offsetSet()
Phar::offsetUnset()

Prev | Home | Next
Phar::offsetExists | Up | Phar::offsetSet


Phar::offsetSet

(no version information, might be only in CVS)

Phar::offsetSet -- set the contents of an internal file to those of an external file

Description

void Phar::offsetSet ( string offset, string value )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

Parameters

offset

The filename (relative path) to modify in a Phar.

value

Content of the file.

Return Values

No return values.

Errors/Exceptions

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Examples

Example 1. A Phar::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

&#60;?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?&#62;

See Also

Phar::offsetExists()
Phar::offsetGet()
Phar::offsetUnset()

Prev | Home | Next
Phar::offsetGet | Up | Phar::offsetUnset


Phar::offsetUnset

(no version information, might be only in CVS)

Phar::offsetUnset -- remove a file from a phar

Description

bool Phar::offsetUnset ( string offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parameters

offset

The filename (relative path) to modify in a Phar.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Examples

Example 1. A Phar::offsetUnset() example

&#60;?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // deletes file.txt from my.phar by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?&#62;

See Also

Phar::offsetExists()
Phar::offsetGet()
Phar::offsetSet()

Prev | Home | Next
Phar::offsetSet | Up | Phar->setMetaData


Phar->setMetaData

(no version information, might be only in CVS)

Phar->setMetaData -- Sets phar archive meta-data

Description

int Phar->setMetaData ( mixed metadata )

setMetaData() should only be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo->setMetaData() should be used for file-specific meta-data. Meta-data can significantly slow down the performance of loading a phar archive if the data is large. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parameters

metadata

Any PHP variable containing information to store that describes the phar archive

Examples

Example 1. A Phar->setMetaData() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '&#60;?php echo "hello"';
    $p-&#62;setMetaData(array('bootstrap' =&#62; 'file.php'));
    var_dump($p-&#62;getMetaData());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?&#62;

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

Phar->getMetaData()

Prev | Home | Next
Phar::offsetUnset | Up | Phar->setStub


Phar->setStub

(no version information, might be only in CVS)

Phar->setStub -- Used to set the PHP loader or bootstrap stub of a Phar archive

Description

void Phar->setStub ( string stub )

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

&#60;?php
include 'myphar.phar';
?&#62;

The loader is not accessed when including a file through the phar stream wrapper like so:

&#60;?php
include 'phar://myphar.phar/somefile.php';
?&#62;

Errors/Exceptions

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example 1. A Phar->setStub() example

&#60;?php
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['a.php'] = '&#60;?php var_dump("Hello");';
    $p-&#62;setStub('&#60;?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?&#62;');
    include 'phar://brandnewphar.phar/a.php';
    var_dump($p-&#62;getStub());
    $p['b.php'] = '&#60;?php var_dump("World");';
    $p-&#62;setStub('&#60;?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?&#62;');
    include 'phar://brandnewphar.phar/b.php';
    var_dump($p-&#62;getStub());
} catch (Exception $e) {
    echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?&#62;

The above example will output:

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

See Also

Phar->getStub()

Prev | Home | Next
Phar->setMetaData | Up | Phar->uncompressAllFiles


Phar->uncompressAllFiles

(no version information, might be only in CVS)

Phar->uncompressAllFiles -- Uncompresses all files in the current Phar archive

Description

bool Phar->uncompressAllFiles ( void )

This method decompresses all files in the Phar archive. If any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files, and any files compressed using bzip2 compression require the bzip2 extension to decompress the files. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not enabled and any files are compressed using bzip2 compression, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example 1. A Phar->uncompressAllFiles() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p-&#62;compressAllFilesGZ();
    foreach ($p as $file) {
        var_dump($file-&#62;getFileName());
        var_dump($file-&#62;isCompressed());
        var_dump($file-&#62;isCompressedBZIP2());
        var_dump($file-&#62;isCompressedGZ());
    }
    $p-&#62;uncompressAllFiles();
    foreach ($p as $file) {
        var_dump($file-&#62;getFileName());
        var_dump($file-&#62;isCompressed());
        var_dump($file-&#62;isCompressedBZIP2());
        var_dump($file-&#62;isCompressedGZ());
    }
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?&#62;

The above example will output:

string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
Phar->compressAllFilesBZIP2()
Phar->compressAllFilesGZ()

Prev | Home | Next
Phar->setStub | Up | PharFileInfo->chmod


PharFileInfo->chmod

(no version information, might be only in CVS)

PharFileInfo->chmod -- Sets file-specific meta-data saved with a file

Description

void PharFileInfo->chmod ( int permissions )

PharFileInfo->chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable.

Parameters

permissions

permissions (see chmod())

Examples

Example 1. A PharFileInfo->chmod() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.sh'] = '#!/usr/local/lib/php
    &#60;?php echo "hi"; ?&#62;';
    // set executable bit
    $p['file.sh']-&#62;chmod(0555);
    var_dump($p['file.sh']-&#62;isExecutable());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?&#62;

The above example will output:

bool(true)

Prev | Home | Next
Phar->uncompressAllFiles | Up | PharFileInfo::__construct


PharFileInfo::__construct

(no version information, might be only in CVS)

PharFileInfo::__construct -- Construct a Phar entry object

Description

void PharFileInfo::__construct ( string entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

Parameters

entry

The full url to retrieve a file. If you wish to retrieve the information for the file my/file.php from the phar boo.phar, the entry should be phar://boo.phar/my/file.php.

Errors/Exceptions

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

Examples

Example 1. A PharFileInfo::__construct() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['testfile.txt'] = "hi\nthere\ndude";
    $file = $p['testfile.txt'];
    foreach ($file as $line =&#62; $text) {
        echo "line number $line: $text";
    }
    // this also works
    $file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
    foreach ($file as $line =&#62; $text) {
        echo "line number $line: $text";
    }
} catch (Exception $e) {
    echo 'Phar operations failed: ', $e;
}
?&#62;

The above example will output:

line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude

Prev | Home | Next
PharFileInfo->chmod | Up | PharFileInfo->getCompressedSize


PharFileInfo->getCompressedSize

(no version information, might be only in CVS)

PharFileInfo->getCompressedSize -- Returns the actual size of the file (with compression) inside the Phar archive

Description

int PharFileInfo->getCompressedSize ( void )

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize()

Return Values

The size in bytes of the file within the Phar archive on disk.

Examples

Example 1. A PharFileInfo->getCompressedSize() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file-&#62;getCompressedSize();
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?&#62;

The above example will output:

2

See Also

PharFileInfo->isCompressed()

Prev | Home | Next
PharFileInfo::__construct | Up | PharFileInfo->getCRC32


PharFileInfo->getCRC32

(no version information, might be only in CVS)

PharFileInfo->getCRC32 -- Returns CRC32 code or throws an exception if not CRC checked

Description

int PharFileInfo->getCRC32 ( void )

This returns the crc32() checksum of the file within the Phar archive.

Return Values

The crc32() checksum of the file within the Phar archive.

Errors/Exceptions

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

Examples

Example 1. A PharFileInfo->getCRC32() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file-&#62;getCRC32();
} catch (Exception $e) {
    echo 'Write operations on my.phar.phar failed: ', $e;
}
?&#62;

The above example will output:

3633523372

Prev | Home | Next
PharFileInfo->getCompressedSize | Up | PharFileInfo->getMetaData


PharFileInfo->getMetaData

(no version information, might be only in CVS)

PharFileInfo->getMetaData -- Returns file-specific meta-data saved with a file

Description

int PharFileInfo->getMetaData ( void )

Return meta-data that was saved in the Phar archive's manifest for this file.

Parameters

Return Values

any PHP variable that can be serialized and is stored as meta-data for the file, or NULL if no meta-data is stored.

Examples

Example 1. A PharFileInfo->getMetaData() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']-&#62;setMetaData(array('user' =&#62; 'bill', 'mime-type' =&#62; 'text/plain'));
    var_dump($p['file.txt']-&#62;getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?&#62;

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

PharFileInfo->setMetaData()

Prev | Home | Next
PharFileInfo->getCRC32 | Up | PharFileInfo->getPharFlags


PharFileInfo->getPharFlags

(no version information, might be only in CVS)

PharFileInfo->getPharFlags -- Returns the Phar file entry flags

Description

int PharFileInfo->getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

Return Values

The Phar flags (always 0 in the current implementation)

Examples

Example 1. A PharFileInfo->getPharFlags() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file-&#62;getPharFlags());
} catch (Exception $e) {
    echo 'Could not create/modify my.phar: ', $e;
}
?&#62;

The above example will output:

int(0)

Prev | Home | Next
PharFileInfo->getMetaData | Up | PharFileInfo->isCompressed


PharFileInfo->isCompressed

(no version information, might be only in CVS)

PharFileInfo->isCompressed -- Returns whether the entry is compressed

Description

bool PharFileInfo->isCompressed ( void )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Return Values

TRUE if the file is compressed within the Phar archive, FALSE if not.

Examples

Example 1. A PharFileInfo->isCompressed() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile2.txt']-&#62;setCompressedGZ();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    var_dump($file-&#62;isCompressed());
    var_dump($file2-&#62;isCompressed());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?&#62;

The above example will output:

bool(false)
bool(true)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressedBZIP2()

Prev | Home | Next
PharFileInfo->getPharFlags | Up | PharFileInfo->isCompressedBZIP2


PharFileInfo->isCompressedBZIP2

(no version information, might be only in CVS)

PharFileInfo->isCompressedBZIP2 -- Returns whether the entry is compressed using bzip2

Description

bool PharFileInfo->isCompressedBZIP2 ( void )

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

Return Values

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

Examples

Example 1. A PharFileInfo->isCompressedBZIP2() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']-&#62;setCompressedGZ();
    $p['myfile3.txt']-&#62;setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file-&#62;isCompressedBZIP2());
    var_dump($file2-&#62;isCompressedBZIP2());
    var_dump($file3-&#62;isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?&#62;

The above example will output:

bool(false)
bool(false)
bool(true)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()

Prev | Home | Next
PharFileInfo->isCompressed | Up | PharFileInfo->isCompressedGZ


PharFileInfo->isCompressedGZ

(no version information, might be only in CVS)

PharFileInfo->isCompressedGZ -- Returns whether the entry is compressed using gz

Description

bool PharFileInfo->isCompressedGZ ( void )

This returns whether a file is compressed within a Phar archive with Gzip compression.

Return Values

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

Examples

Example 1. A PharFileInfo->isCompressedGZ() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']-&#62;setCompressedGZ();
    $p['myfile3.txt']-&#62;setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file-&#62;isCompressedGZ());
    var_dump($file2-&#62;isCompressedGZ());
    var_dump($file3-&#62;isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?&#62;

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedBZIP2()
PharFileInfo->isCompressed()

Prev | Home | Next
PharFileInfo->isCompressedBZIP2 | Up | PharFileInfo->isCRCChecked


PharFileInfo->isCRCChecked

(no version information, might be only in CVS)

PharFileInfo->isCRCChecked -- Returns whether file entry has had its CRC verified

Description

bool PharFileInfo->isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

Return Values

TRUE if the file has had its CRC verified, FALSE if not.

Examples

Example 1. A PharFileInfo->isCRCChecked() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file-&#62;isCRCChecked());
} catch (Exception $e) {
    echo 'Create/modify operations failed on my.phar: ', $e;
}
?&#62;

The above example will output:

bool(true)

Prev | Home | Next
PharFileInfo->isCompressedGZ | Up | PharFileInfo->setCompressedBZIP2


PharFileInfo->setCompressedBZIP2

(no version information, might be only in CVS)

PharFileInfo->setCompressedBZIP2 -- Compresses the current Phar entry within the phar using Bzip2 compression

Description

bool PharFileInfo->setCompressedBZIP2 ( void )

This method compresses the file inside the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using gzip compression, the zlib extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

Examples

Example 1. A PharFileInfo->setCompressedBZIP2() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file-&#62;isCompressedBZIP2());
    $p['myfile.txt']-&#62;setCompressedBZIP2();
    var_dump($file-&#62;isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?&#62;

The above example will output:

bool(false)
bool(true)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
Phar->compressAllFilesBZIP2()

Prev | Home | Next
PharFileInfo->isCRCChecked | Up | PharFileInfo->setCompressedGZ


PharFileInfo->setCompressedGZ

(no version information, might be only in CVS)

PharFileInfo->setCompressedGZ -- Compresses the current Phar entry within the phar using gz compression

Description

bool PharFileInfo->setCompressedGZ ( void )

This method compresses the file inside the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

Examples

Example 1. A PharFileInfo->setCompressedGZ() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file-&#62;isCompressedGZ());
    $p['myfile.txt']-&#62;setCompressedGZ();
    var_dump($file-&#62;isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?&#62;

The above example will output:

bool(false)
bool(true)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedBZIP2()
PharFileInfo->isCompressed()
PharFileInfo->isCompressedBZIP2()
PharFileInfo->isCompressed()
Phar->compressAllFilesGZ()

Prev | Home | Next
PharFileInfo->setCompressedBZIP2 | Up | PharFileInfo->setMetaData


PharFileInfo->setMetaData

(no version information, might be only in CVS)

PharFileInfo->setMetaData -- Sets file-specific meta-data saved with a file

Description

int PharFileInfo->setMetaData ( mixed metadata )

setMetaData() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar, although it is possible to set them with the PharFileInfo->chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

Parameters

metadata

Any PHP variable containing information to store alongside a file

Examples

Example 1. A PharFileInfo->setMetaData() example

&#60;?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']-&#62;setMetaData(array('user' =&#62; 'bill', 'mime-type' =&#62; 'text/plain'));
    var_dump($p['file.txt']-&#62;getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?&#62;

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

PharFileInfo->getMetaData()

Prev | Home | Next
PharFileInfo->setCompressedGZ | Up | PharFileInfo->setUncompressed


PharFileInfo->setUncompressed

(no version information, might be only in CVS)

PharFileInfo->setUncompressed -- Uncompresses the current Phar entry within the phar, if it is compressed

Description

bool PharFileInfo->setUncompressed ( void )

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Examples

Example 1. A PharFileInfo->setUncompressed() example

&#60;?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file-&#62;setCompressedGZ();
    var_dump($file-&#62;isCompressed());
    $p['myfile.txt']-&#62;setUncompressed();
    var_dump($file-&#62;isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?&#62;

The above example will output:

bool(true)
bool(false)

See Also

PharFileInfo->getCompressedSize()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressedBZIP2()
PharFileInfo->isCompressedGZ()
PharFileInfo->isCompressed()
Phar->uncompressAllFiles()

Prev | Home | Next
PharFileInfo->setMetaData | Up | PHP Options&Information


posix_mknod

(PHP 5 >= 5.1.0RC1)

posix_mknod -- Create a special or ordinary file (POSIX.1)

Description

bool posix_mknod ( string pathname, int mode [, int major [, int minor]] )

Creates a special or ordinary file.

Parameters

pathname

The file to create

mode

This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.

major

The major device kernel identifier (required to pass when you're using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier (defaults to 0).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A posix_mknod() example

&#60;?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLK;   // file type
$permissions = 0777;     // octal
$major = 1;
$minor = 8;              // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?&#62;

See Also

posix_mkfifo()

Prev | Home | Next
posix_mkfifo | Up | posix_setegid


preg_last_error

(no version information, might be only in CVS)

preg_last_error -- Returns the error code of the last PCRE regex execution

Description

int preg_last_error ( void )

Returns the error code of the last PCRE regex execution.

Return Values

Returns one of the following constants (explained on their own page):

PREG_NO_ERROR
PREG_INTERNAL_ERROR
PREG_BACKTRACK_LIMIT_ERROR (see also pcre.backtrack_limit)
PREG_RECURSION_LIMIT_ERROR (see also pcre.recursion_limit)
PREG_BAD_UTF8_ERROR

Prev | Home | Next
preg_grep | Up | preg_match_all


ps_add_bookmark

(PECL)

ps_add_bookmark -- Add bookmark to current page

Description

int ps_add_bookmark ( resource psdoc, string text [, int parent [, int open]] )

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

The bookmark has no meaning if the document is printed or viewed, but it will be used if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text used for displaying the bookmark.

parent

A bookmark previously created by this function which is used as the parent of the new bookmark.

open

If open is unequal to zero the bookmark will be shown open by the pdf viewer.

Return Values

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent. The value is greater zero if the function succeeds. In case of an error zero will be returned.

See Also

ps_add_launchlink()
ps_add_pdflink()
ps_add_weblink()

Prev | Home | Next
PostScript document creation | Up | ps_add_launchlink


ps_add_launchlink

(PECL)

ps_add_launchlink -- Adds link which launches file

Description

bool ps_add_launchlink ( resource psdoc, float llx, float lly, float urx, float ury, string filename )

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The path of the program to be started, when the link is clicked on.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_add_locallink()
ps_add_pdflink()
ps_add_weblink()

Prev | Home | Next
ps_add_bookmark | Up | ps_add_locallink


ps_add_locallink

(PECL)

ps_add_locallink -- Adds link to a page in the same document

Description

bool ps_add_locallink ( resource psdoc, float llx, float lly, float urx, float ury, int page, string dest )

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

page

The number of the page displayed when clicking on the link.

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_add_launchlink()
ps_add_pdflink()
ps_add_weblink()

Prev | Home | Next
ps_add_launchlink | Up | ps_add_note


ps_add_note

(PECL)

ps_add_note -- Adds note to current page

Description

bool ps_add_note ( resource psdoc, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open )

Adds a note at a certain position on the page. Notes are like little rectangular sheets with text on it, which can be placed anywhere on a page. They are shown either folded or unfolded. If unfolded, the specified icon is used as a placeholder.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

contents

The text of the note.

title

The title of the note as displayed in the header of the note.

icon

The icon shown if the note is folded. This parameter can be set to comment, insert, note, paragraph, newparagraph, key, or help.

open

If open is unequal to zero the note will be shown unfolded after opening the document with a pdf viewer.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_add_pdflink()
ps_add_launchlink()
ps_add_locallink()
ps_add_weblink()

Prev | Home | Next
ps_add_locallink | Up | ps_add_pdflink


ps_add_pdflink

(PECL)

ps_add_pdflink -- Adds link to a page in a second pdf document

Description

bool ps_add_pdflink ( resource psdoc, float llx, float lly, float urx, float ury, string filename, int page, string dest )

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The name of the pdf document to be opened when clicking on this link.

page

The page number of the destination pdf document

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_add_launchlink()
ps_add_locallink()
ps_add_weblink()

Prev | Home | Next
ps_add_note | Up | ps_add_weblink


ps_add_weblink

(PECL)

ps_add_weblink -- Adds link to a web location

Description

bool ps_add_weblink ( resource psdoc, float llx, float lly, float urx, float ury, string url )

Places a hyperlink at the given position pointing to a web page. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

url

The url of the hyperlink to be opened when clicking on this link, e.g. http://www.php.net.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_add_launchlink()
ps_add_locallink()
ps_add_pdflink()

Prev | Home | Next
ps_add_pdflink | Up | ps_arc


ps_arc

(PECL)

ps_arc -- Draws an arc counterclockwise

Description

bool ps_arc ( resource psdoc, float x, float y, float radius, float alpha, float beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn counterclockwise (use ps_arcn() to draw clockwise). The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The start angle given in degrees.

beta

The end angle given in degrees.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_arcn()

Prev | Home | Next
ps_add_weblink | Up | ps_arcn


ps_arcn

(no version information, might be only in CVS)

ps_arcn -- Draws an arc clockwise

Description

bool ps_arcn ( resource psdoc, float x, float y, float radius, float alpha, float beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn clockwise (use ps_arc() to draw counterclockwise). The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The starting angle given in degrees.

beta

The end angle given in degrees.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_arc()

Prev | Home | Next
ps_arc | Up | ps_begin_page


ps_begin_page

(PECL)

ps_begin_page -- Start a new page

Description

bool ps_begin_page ( resource psdoc, float width, float height )

Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Though PostScript does not know different page sizes, pslib places a bounding box for each page into the document. This size is evaluated by some PostScript viewers and will have precedence over the BoundingBox in the Header of the document. This can lead to unexpected results when you set a BoundingBox whose lower left corner is not (0, 0), because the bounding box of the page will always have a lower left corner (0, 0) and overwrites the global setting.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. The lower left corner of the bounding box is set to (0, 0). If ps_findfont() was called before, then the header has been output already, and the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.

Note: Up to version 0.2.6 of pslib, this function will always overwrite the BoundingBox and Orientation, if it has been set before with ps_set_info() and ps_findfont() has not been called before.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the page in pixel, e.g. 596 for A4 format.

height

The height of the page in pixel, e.g. 842 for A4 format.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_end_page()
ps_findfont()
ps_set_info()

Prev | Home | Next
ps_arcn | Up | ps_begin_pattern


ps_begin_pattern

(PECL)

ps_begin_pattern -- Start a new pattern

Description

int ps_begin_pattern ( resource psdoc, float width, float height, float xstep, float ystep, int painttype )

Starts a new pattern. A pattern is like a page containing e.g. a drawing which can be used for filling areas. It is used like a color by calling ps_setcolor() and setting the color space to pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the pattern in pixel.

height

The height of the pattern in pixel.

x-step

The distance in pixel of placements of the pattern in horizontal direction.

y-step

The distance in pixel of placements of the pattern in vertical direction.

painttype

Must be 1 or 2.

Return Values

The identifier of the pattern or FALSE in case of an error.

Examples

Example 1. Creating and using a pattern

&#60;?php
$ps = ps_new();

if (!ps_open_file($ps, "pattern.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");

$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?&#62;

See Also

ps_end_pattern()
ps_setcolor()
ps_shading_pattern()

Prev | Home | Next
ps_begin_page | Up | ps_begin_template


ps_begin_template

(PECL)

ps_begin_template -- Start a new template

Description

int ps_begin_template ( resource psdoc, float width, float height )

Starts a new template. A template is called a form in the postscript language. It is created similar to a pattern but used like an image. Templates are often used for drawings which are placed several times through out the document, e.g. like a company logo. All drawing functions may be used within a template. The template will not be drawn until it is placed by ps_place_image().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the template in pixel.

height

The height of the template in pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Creating and using a template

&#60;?php
$ps = ps_new();

if (!ps_open_file($ps, "template.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "template.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Template example");

$pstemplate = ps_begin_template($ps, 30.0, 30.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 30, 30);
ps_moveto($ps, 0, 30);
ps_lineto($ps, 30, 0);
ps_stroke($ps);
ps_end_template($ps);

ps_begin_page($ps, 596, 842);
ps_place_image($ps, $pstemplate, 20.0, 20.0, 1.0);
ps_place_image($ps, $pstemplate, 50.0, 30.0, 0.5);
ps_place_image($ps, $pstemplate, 70.0, 70.0, 0.6);
ps_place_image($ps, $pstemplate, 30.0, 50.0, 1.3);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?&#62;

See Also

ps_end_template()

Prev | Home | Next
ps_begin_pattern | Up | ps_circle


ps_circle

(PECL)

ps_circle -- Draws a circle

Description

bool ps_circle ( resource psdoc, float x, float y, float radius )

Draws a circle with its middle point at (x, y). The circle starts and ends at position (x+radius, y). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x+radius, y) then there will be a gap in the path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_arc()
ps_arcn()

Prev | Home | Next
ps_begin_template | Up | ps_clip


ps_clip

(PECL)

ps_clip -- Clips drawing to current path

Description

bool ps_clip ( resource psdoc )

Takes the current path and uses it to define the border of a clipping area. Everything drawn outside of that area will not be visible.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_closepath()

Prev | Home | Next
ps_circle | Up | ps_close_image


ps_close

(PECL)

ps_close -- Closes a PostScript document

Description

bool ps_close ( resource psdoc )

Closes the PostScript document.

This function writes the trailer of the PostScript document. It also writes the bookmark tree. ps_close() does not free any resources, which is done by ps_delete().

This function is also called by ps_delete() if it has not been called before.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_open_file()
ps_delete()

Prev | Home | Next
ps_close_image | Up | ps_closepath_stroke


ps_close_image

(PECL)

ps_close_image -- Closes image and frees memory

Description

void ps_close_image ( resource psdoc, int imageid )

Closes an image and frees its resources. Once an image is closed it cannot be used anymore.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

Resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

Return Values

Returns NULL on success or FALSE on failure.

See Also

ps_open_image()
ps_open_image_file()

Prev | Home | Next
ps_clip | Up | ps_close


ps_closepath

(PECL)

ps_closepath -- Closes path

Description

bool ps_closepath ( resource psdoc )

Connects the last point with the first point of a path. The resulting path can be used for stroking, filling, clipping, etc..

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_clip()
ps_closepath_stroke()

Prev | Home | Next
ps_closepath_stroke | Up | ps_continue_text


ps_closepath_stroke

(PECL)

ps_closepath_stroke -- Closes and strokes path

Description

bool ps_closepath_stroke ( resource psdoc )

Connects the last point with first point of a path and draws the resulting closed line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_closepath()

Prev | Home | Next
ps_close | Up | ps_closepath


ps_continue_text

(PECL)

ps_continue_text -- Continue text in next line

Description

bool ps_continue_text ( resource psdoc, string text )

Output a text one line below the last line. The line spacing is taken from the value "leading" which must be set with ps_set_value(). The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to output.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_show()
ps_show_xy()
ps_show_boxed()

Prev | Home | Next
ps_closepath | Up | ps_curveto


ps_curveto

(PECL)

ps_curveto -- Draws a curve

Description

bool ps_curveto ( resource psdoc, float x1, float y1, float x2, float y2, float x3, float y3 )

Add a section of a cubic Bézier curve described by the three given control points to the current path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x1

x-coordinate of first control point.

y1

y-coordinate of first control point.

x2

x-coordinate of second control point.

y2

y-coordinate of second control point.

x3

x-coordinate of third control point.

y3

y-coordinate of third control point.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_lineto()

Prev | Home | Next
ps_continue_text | Up | ps_delete


ps_delete

(PECL)

ps_delete -- Deletes all resources of a PostScript document

Description

bool ps_delete ( resource psdoc )

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a trailor containing PostScript comments like the number of pages in the document and adding the bookmark hierarchy.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_close()

Prev | Home | Next
ps_curveto | Up | ps_end_page


ps_end_page

(PECL)

ps_end_page -- End a page

Description

bool ps_end_page ( resource psdoc )

Ends a page which was started with ps_begin_page(). Ending a page will leave the current drawing context, which e.g. requires to reload fonts if they were loading within the page, and to set many other drawing parameters like the line width, or color..

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_begin_page()

Prev | Home | Next
ps_delete | Up | ps_end_pattern


ps_end_pattern

(PECL)

ps_end_pattern -- End a pattern

Description

bool ps_end_pattern ( resource psdoc )

Ends a pattern which was started with ps_begin_pattern(). Once a pattern has been ended, it can be used like a color to fill areas.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_begin_pattern()

Prev | Home | Next
ps_end_page | Up | ps_end_template


ps_end_template

(PECL)

ps_end_template -- End a template

Description

bool ps_end_template ( resource psdoc )

Ends a template which was started with ps_begin_template(). Once a template has been ended, it can be used like an image.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_begin_template()

Prev | Home | Next
ps_end_pattern | Up | ps_fill_stroke


ps_fill

(PECL)

ps_fill -- Fills the current path

Description

bool ps_fill ( resource psdoc )

Fills the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_fill_stroke()
ps_stroke()

Prev | Home | Next
ps_fill_stroke | Up | ps_findfont


ps_fill_stroke

(PECL)

ps_fill_stroke -- Fills and strokes the current path

Description

bool ps_fill_stroke ( resource psdoc )

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_fill()
ps_stroke()

Prev | Home | Next
ps_end_template | Up | ps_fill


ps_findfont

(PECL)

ps_findfont -- Loads a font

Description

int ps_findfont ( resource psdoc, string fontname, string encoding [, bool embed] )

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

The name of the afm file must be fontname.afm. If the font shall be embedded the file fontname.pfb containing the font outline must be present as well.

Calling ps_findfont() before the first page requires to output the postscript header which includes the BoundingBox for the whole document. Usually the BoundingBox is set with the first call of ps_begin_page() which now comes after ps_findfont(). Consequently the BoundingBox has not been set and a warning will be issued when ps_findfont() is called. In order to prevent this situation, one should call ps_set_parameter() to set the BoundingBox before ps_findfont() is called.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontname

The name of the font.

encoding

ps_findfont() will try to load the file passed in the parameter encoding. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

encoding can be NULL or the empty string if the default encoding (TeXBase1) shall be used.

If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

embed

If set to a value >0 the font will be embedded into the document. This requires the font outline (.pfb file) to be present.

Return Values

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

See Also

ps_begin_page()
ps_setfont()

Prev | Home | Next
ps_fill | Up | ps_get_buffer


ps_get_buffer

(PECL)

ps_get_buffer -- Fetches the full buffer containig the generated PS data

Description

string ps_get_buffer ( resource psdoc )

This function is not implemented yet. It will always return an empty string. The idea for a later implementation is to write the contents of the postscript file into an internal buffer if in memory creation is requested, and retrieve the buffer content with this function. Currently, documents created in memory are send to the browser without buffering.

Warning

This function is currently not documented; only the argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

See Also

ps_open_file()

Prev | Home | Next
ps_findfont | Up | ps_get_parameter


ps_get_parameter

(PECL)

ps_get_parameter -- Gets certain parameters

Description

string ps_get_parameter ( resource psdoc, string name [, float modifier] )

Gets several parameters which were directly set by ps_set_parameter() or indirectly by one of the other functions. Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

The parameter name can have the following values.

fontname

The name of the currently active font or the font whose identifier is passed in parameter modifier.

fontencoding

The encoding of the currently active font.

dottedversion

The version of the underlying pslib library in the format <major>.<minor>.<subminor>

scope

The current drawing scope. Can be object, document, null, page, pattern, path, template, prolog, font, glyph.

ligaturedisolvechar

The character which dissolves a ligature. If your are using a font which contains the ligature `ff' and `|' is the char to dissolve the ligature, then `f|f' will result in two `f' instead of the ligature `ff'.

imageencoding

The encoding used for encoding images. Can be either hex or 85. hex encoding uses two bytes in the postscript file each byte in the image. 85 stand for Ascii85 encoding.

linenumbermode

Set to paragraph if lines are numbered within a paragraph or box if they are numbered within the surrounding box.

linebreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will add a line break.

parbreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will start a new paragraph.

hyphenation

Only used if text is output with ps_show_boxed(). If set to true the paragraph will be hyphenated if a hypen dictionary is set and exists.

hyphendict

Filename of the dictionary used for hyphenation pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the parameter.

modifier

An identifier needed if a parameter of a resource is requested, e.g. the size of an image. In such a case the resource id is passed.

Return Values

Returns the value of the parameter or FALSE in case of an error.

See Also

ps_set_parameter()

Prev | Home | Next
ps_get_buffer | Up | ps_get_value


ps_get_value

(PECL)

ps_get_value -- Gets certain values

Description

float ps_get_value ( resource psdoc, string name [, float modifier] )

Gets several values which were set by ps_set_value(). Values are by definition float values.

The parameter name can have the following values.

fontsize

The size of the currently active font or the font whose identifier is passed in parameter modifier.

font

The currently active font itself.

imagewidth

The width of the image whose id is passed in the parameter modifier.

imageheight

The height of the image whose id is passed in the parameter modifier.

capheight

The height of a capital M in the currently active font or the font whose identifier is passed in parameter modifier.

ascender

The ascender of the currently active font or the font whose identifier is passed in parameter modifier.

descender

The descender of the currently active font or the font whose identifier is passed in parameter modifier.

italicangle

The italicangle of the currently active font or the font whose identifier is passed in parameter modifier.

underlineposition

The underlineposition of the currently active font or the font whose identifier is passed in parameter modifier.

underlinethickness

The underlinethickness of the currently active font or the font whose identifier is passed in parameter modifier.

textx

The current x-position for text output.

texty

The current y-position for text output.

textrendering

The current mode for text rendering.

textrise

The space by which text is risen above the base line.

leading

The distance between text lines in points.

wordspacing

The space between words as a multiple of the width of a space char.

charspacing

The space between chars. If charspacing is != 0.0 ligatures will always be dissolved.

hyphenminchars

Minimum number of chars hyphenated at the end of a word.

parindent

Indention of the first n line in a paragraph.

numindentlines

Number of line in a paragraph to indent if parindent != 0.0.

parskip

Distance between paragraphs.

linenumberspace

Overall space in front of each line for the line number.

linenumbersep

Space between the line and the line number.

major

The major version number of pslib.

minor

The minor version number of pslib.

subminor, revision

The subminor version number of pslib.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the value.

modifier

The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image.

Return Values

Returns the value of the parameter or FALSE.

See Also

ps_set_value()

Prev | Home | Next
ps_get_parameter | Up | ps_hyphenate


ps_hyphenate

(PECL)

ps_hyphenate -- Hyphenates a word

Description

array ps_hyphenate ( resource psdoc, string text )

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars (set by ps_set_value()) and the parameter hyphendict (set by ps_set_parameter()). hyphendict must be set before calling this function.

This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale for more information.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.

Return Values

An array of integers indicating the position of possible breaks in the text or FALSE in case of an error.

Examples

Example 1. Hyphennate a text

&#60;?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i&#60;strlen($word); $i++) {
  echo $word[$i];
  if(in_array($i, $hyphens))
    echo "-";
}
ps_delete($psdoc);
?&#62;

The above example will output:

Ko-ordi-na-ten-sys-tem

See Also

ps_show_boxed()
locale(1)

Prev | Home | Next
ps_get_value | Up | ps_lineto


ps_lineto

(PECL)

ps_lineto -- Draws a line

Description

bool ps_lineto ( resource psdoc, float x, float y )

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the end point of the line.

y

y-coordinate of the end point of the line.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Drawing a rectangle

&#60;?php
$ps = ps_new();
if (!ps_open_file($ps, "rectangle.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Lineto example");

ps_begin_page($ps, 596, 842);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?&#62;

See Also

ps_moveto()

Prev | Home | Next
ps_hyphenate | Up | ps_makespotcolor


ps_makespotcolor

(PECL)

ps_makespotcolor -- Create spot color

Description

int ps_makespotcolor ( resource psdoc, string name [, float reserved] )

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor(). When the document is not printed but displayed by an postscript viewer the given color in the specified color space is use.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the spot color, e.g. Pantone 5565.

Return Values

The id of the new spot color or 0 in case of an error.

Examples

Example 1. Creating and using a spot color

&#60;?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);

ps_delete($ps);
?&#62;

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

See Also

ps_setcolor()

Prev | Home | Next
ps_lineto | Up | ps_moveto


ps_moveto

(PECL)

ps_moveto -- Sets current point

Description

bool ps_moveto ( resource psdoc, float x, float y )

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the point to move to.

y

y-coordinate of the point to move to.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_lineto()

Prev | Home | Next
ps_makespotcolor | Up | ps_new


ps_new

(PECL)

ps_new -- Creates a new PostScript document object

Description

resource ps_new ( void )

Creates a new document instance. It does not create the file on disk or in memory, it just sets up everything. ps_new() is usually followed by a call of ps_open_file() to actually create the postscript document.

Return Values

Resource of PostScript document or FALSE on failure. The return value is passed to all other functions as the first argument.

See Also

ps_delete()

Prev | Home | Next
ps_moveto | Up | ps_open_file


ps_open_file

(PECL)

ps_open_file -- Opens a file for output

Description

bool ps_open_file ( resource psdoc [, string filename] )

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

filename

The name of the postscript file. If filename is not passed the document will be created in memory and all output will go straight to the browser.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_close()

Prev | Home | Next
ps_new | Up | ps_open_image_file


ps_open_image

(PECL)

ps_open_image -- Reads an image for later placement

Description

int ps_open_image ( resource psdoc, string type, string source, string data, int lenght, int width, int height, int components, int bpc, string params )

Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory. The image data is a sequence of pixels starting in th upper left corner and ending in the lower right corner. Each pixel consists of components color components, and each component has bpc bits.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

source

Not used.

data

The image data.

length

The length of the image data.

width

The width of the image.

height

The height of the image.

components

The number of components for each pixel. This can be 1 (gray scale images), 3 (rgb images), or 4 (cmyk, rgba images).

bpc

Number of bits per component (quite often 8).

params

Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

See Also

ps_open_image_file()
ps_place_image()
ps_close_image()

Prev | Home | Next
ps_open_image_file | Up | ps_place_image


ps_open_image_file

(PECL)

ps_open_image_file -- Opens image from file

Description

int ps_open_image_file ( resource psdoc, string type, string filename [, string stringparam [, int intparam]] )

Loads an image for later use.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

filename

The name of the file containing the image data.

stringparam

Not used.

intparam

Not used.

Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

See Also

ps_open_image()
ps_place_image()
ps_close_image()

Prev | Home | Next
ps_open_file | Up | ps_open_image


ps_place_image

(PECL)

ps_place_image -- Places image on the page

Description

bool ps_place_image ( resource psdoc, int imageid, float x, float y, float scale )

Places a formerly loaded image on the page. The image can be scaled. If the image shall be rotated as well, you will have to rotate the coordinate system before with ps_rotate().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

The resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

x

x-coordinate of the lower left corner of the image.

y

y-coordinate of the lower left corner of the image.

scale

The scaling factor for the image. A scale of 1.0 will result in a resolution of 72 dpi, because each pixel is equivalent to 1 point.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_open_image()
ps_open_image_file()

Prev | Home | Next
ps_open_image | Up | ps_rect


ps_rect

(PECL)

ps_rect -- Draws a rectangle

Description

bool ps_rect ( resource psdoc, float x, float y, float width, float height )

Draws a rectangle with its lower left corner at (x, y). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the lower left corner of the rectangle.

y

y-coordinate of the lower left corner of the rectangle.

width

The width of the image.

height

The height of the image.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_arc()
ps_cirle()
ps_lineto()

Prev | Home | Next
ps_place_image | Up | ps_restore


ps_restore

(PECL)

ps_restore -- Restore previously save context

Description

bool ps_restore ( resource psdoc )

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore(). All coordinate transformations, line style settings, color settings, etc. are being restored to the state before the call of ps_save().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_save()

Prev | Home | Next
ps_rect | Up | ps_rotate


ps_rotate

(PECL)

ps_rotate -- Sets rotation factor

Description

bool ps_rotate ( resource psdoc, float rot )

Sets the rotation of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

rot

Angle of rotation in degree.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Rotation of the coordinate system

&#60;?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);

ps_delete($ps);
?&#62;

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

See Also

ps_scale()
ps_translate()

Prev | Home | Next
ps_restore | Up | ps_save


ps_save

(PECL)

ps_save -- Save current context

Description

bool ps_save ( resource psdoc )

Saves the current graphics context, containing colors, translation and rotation settings and some more. A saved context can be restored with ps_restore().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_restore()

Prev | Home | Next
ps_rotate | Up | ps_scale


ps_scale

(PECL)

ps_scale -- Sets scaling factor

Description

bool ps_scale ( resource psdoc, float x, float y )

Sets horizontal and vertical scaling of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

Scaling factor in horizontal direction.

y

Scaling factor in vertical direction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_rotate()
ps_translate()

Prev | Home | Next
ps_save | Up | ps_set_border_color


ps_set_border_color

(PECL)

ps_set_border_color -- Sets color of border for annotations

Description

bool ps_set_border_color ( resource psdoc, float red, float green, float blue )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the color of the rectangle's border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

red

The red component of the border color.

green

The green component of the border color.

blue

The blue component of the border color.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_set_border_dash()
ps_set_border_style()

Prev | Home | Next
ps_scale | Up | ps_set_border_dash


ps_set_border_dash

(PECL)

ps_set_border_dash -- Sets length of dashes for border of annotations

Description

bool ps_set_border_dash ( resource psdoc, float black, float white )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the length of the black and white portion of a dashed border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

black

The length of the dash.

white

The length of the gap between dashes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_set_border_color()
ps_set_border_style()

Prev | Home | Next
ps_set_border_color | Up | ps_set_border_style


ps_set_border_style

(PECL)

ps_set_border_style -- Sets border style of annotations

Description

bool ps_set_border_style ( resource psdoc, string style, float width )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the appearance and width of the border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

style

style can be solid or dashed.

width

The line width of the border.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_set_border_color()
ps_set_border_dash()

Prev | Home | Next
ps_set_border_dash | Up | ps_set_info


ps_set_info

(PECL)

ps_set_info -- Sets information fields of document

Description

bool ps_set_info ( resource p, string key, string val )

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. If the document is converted to pdf this fields will also be used for the document information.

The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

This function will have no effect anymore when the header of the postscript file has been already written. It must be called before the first page or the first call of ps_findfont().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

key

The name of the information field to set. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.

value

The value of the information field. The field Orientation can be set to either Portrait or Landscape. The BoundingBox is a string consisting of four numbers. The first two numbers are the coordinates of the lower left corner of the page. The last two numbers are the coordinates of the upper right corner.

Note: Up to version 0.2.6 of pslib, the BoundingBox and Orientation will be overwritten by ps_begin_page(), unless ps_findfont() has been called before.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_findfont()
ps_begin_page()

Prev | Home | Next
ps_set_border_style | Up | ps_set_parameter


ps_set_parameter

(PECL)

ps_set_parameter -- Sets certain parameters

Description

bool ps_set_parameter ( resource psdoc, string name, string value )

Sets several parameters which are used by many functions. Parameters are by definition string values.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

For a list of possible names see ps_get_parameter().

value

The value of the parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_get_parameters()
ps_set_value()

Prev | Home | Next
ps_set_info | Up | ps_set_text_pos


ps_set_text_pos

(PECL)

ps_set_text_pos -- Sets position for text output

Description

bool ps_set_text_pos ( resource psdoc, float x, float y )

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.

If you want to output text at a certain position it is more convenient to use ps_show_xy() instead of setting the text position and calling ps_show().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the new text position.

y

y-coordinate of the new text position.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Placing text at a given position

&#60;?php
$ps = ps_new();
if (!ps_open_file($ps, "text.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Text placement example");

ps_begin_page($ps, 596, 842);
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_setfont($ps, $psfont, 8.0);
ps_show_xy($ps, "Some text at (100, 100)", 100, 100);

ps_set_value($ps, "textx", 100);
ps_set_value($ps, "texty", 120);
ps_show($ps, "Some text at (100, 120)");
ps_end_page($ps);

ps_delete($ps);
?&#62;

See Also

ps_set_value()
ps_show()

Prev | Home | Next
ps_set_parameter | Up | ps_set_value


ps_set_value

(PECL)

ps_set_value -- Sets certain values

Description

bool ps_set_value ( resource psdoc, string name, float value )

Sets several values which are used by many functions. Parameters are by definition float values.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

The name can be one of the following:

textrendering

The way how text is shown.

textx

The x coordinate for text output.

texty

The y coordinate for text output.

wordspacing

The distance between words relative to the width of a space.

leading

The distance between lines in pixels.

value

The value of the parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_get_value()
ps_set_parameter()

Prev | Home | Next
ps_set_text_pos | Up | ps_setcolor


ps_setcolor

(PECL)

ps_setcolor -- Sets current color

Description

bool ps_setcolor ( resource psdoc, string type, string colorspace, float c1, float c2, float c3, float c4 )

Sets the color for drawing, filling, or both.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The parameter type can be both, fill, or fillstroke.

colorspace

The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.

c1

Depending on the colorspace this is either the red component (rgb), the cyan component (cmyk), the gray value (gray), the identifier of the spot color or the identifier of the pattern.

c2

Depending on the colorspace this is either the green component (rgb), the magenta component (cmyk).

c3

Depending on the colorspace this is either the blue component (rgb), the yellow component (cmyk).

c4

This must only be set in cmyk colorspace and specifies the black component.

Bugs

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ps_set_value | Up | ps_setdash


ps_setdash

(PECL)

ps_setdash -- Sets appearance of a dashed line

Description

bool ps_setdash ( resource psdoc, float on, float off )

Sets the length of the black and white portions of a dashed line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

on

The length of the dash.

off

The length of the gap between dashes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setpolydash()

Prev | Home | Next
ps_setcolor | Up | ps_setflat


ps_setflat

(PECL)

ps_setflat -- Sets flatness

Description

bool ps_setflat ( resource psdoc, float value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The value must be between 0.2 and 1.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ps_setdash | Up | ps_setfont


ps_setfont

(PECL)

ps_setfont -- Sets font to use for following output

Description

bool ps_setfont ( resource psdoc, int fontid, float size )

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font results in an error.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontid

The font identifier as returned by ps_findfont().

size

The size of the font.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_findfont()
ps_set_text_pos() for an example.

Prev | Home | Next
ps_setflat | Up | ps_setgray


ps_setgray

(no version information, might be only in CVS)

ps_setgray -- Sets gray value

Description

bool ps_setgray ( resource psdoc, float gray )

Sets the gray value for all following drawing operations.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

gray

The value must be between 0 (white) and 1 (black).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setcolor()

Prev | Home | Next
ps_setfont | Up | ps_setlinecap


ps_setlinecap

(PECL)

ps_setlinecap -- Sets appearance of line ends

Description

bool ps_setlinecap ( resource psdoc, int type )

Sets how line ends look like.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of line ends. Possible values are PS_LINECAP_BUTT, PS_LINECAP_ROUND, or PS_LINECAP_SQUARED.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setlinejoin()
ps_setlinewidth()
ps_setmiterlimit()

Prev | Home | Next
ps_setgray | Up | ps_setlinejoin


ps_setlinejoin

(PECL)

ps_setlinejoin -- Sets how contected lines are joined

Description

bool ps_setlinejoin ( resource psdoc, int type )

Sets how lines are joined.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The way lines are joined. Possible values are PS_LINEJOIN_MITER, PS_LINEJOIN_ROUND, or PS_LINEJOIN_BEVEL.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setlinecap()
ps_setlinewidth()
ps_setmiterlimit()

Prev | Home | Next
ps_setlinecap | Up | ps_setlinewidth


ps_setlinewidth

(PECL)

ps_setlinewidth -- Sets width of a line

Description

bool ps_setlinewidth ( resource psdoc, float width )

Sets the line width for all following drawing operations.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of lines in points.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setlinecap()
ps_setlinejoin()
ps_setmiterlimit()

Prev | Home | Next
ps_setlinejoin | Up | ps_setmiterlimit


ps_setmiterlimit

(PECL)

ps_setmiterlimit -- Sets the miter limit

Description

bool ps_setmiterlimit ( resource psdoc, float value )

If two lines join in a small angle and the line join is set to PS_LINEJOIN_MITER, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The maximum ratio between the miter length and the line width. Larger values (> 10) will result in very long spikes when two lines meet in a small angle. Keep the default unless you know what you are doing.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_setlinecap()
ps_setlinejoin()
ps_setlinewidth()

Prev | Home | Next
ps_setlinewidth | Up | ps_setpolydash


ps_setpolydash

(PECL)

ps_setpolydash -- Sets appearance of a dashed line

Description

bool ps_setpolydash ( resource psdoc, float arr )

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

arr

arr is a list of length elements alternately for the black and white portion.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Drawing a dashed line

&#60;?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
   print "Cannot open PostScript file\n";
     exit;
}

ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");

ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?&#62;

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

See Also

ps_setdash()

Prev | Home | Next
ps_setmiterlimit | Up | ps_shading_pattern


ps_shading

(PECL)

ps_shading -- Creates a shading for later use

Description

int ps_shading ( resource psdoc, string type, float x0, float y0, float x1, float y1, float c1, float c2, float c3, float c4, string optlist )

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).

x0, x1, y0, y1

The coordinates x0, y0, x1, y1 are the start and end point of the shading. If the type of shading is radial the two points are the middle points of a starting and ending circle.

c1, c2, c3, c4

See ps_setcolor() for their meaning.

optlist

If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.

Return Values

Returns the identifier of the pattern or FALSE in case of an error.

See Also

ps_shading_pattern()
ps_shfill()

Prev | Home | Next
ps_shading_pattern | Up | ps_shfill


ps_shading_pattern

(PECL)

ps_shading_pattern -- Creates a pattern based on a shading

Description

int ps_shading_pattern ( resource psdoc, int shadingid, string optlist )

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

optlist

This argument is not currently used.

Return Values

The identifier of the pattern or FALSE in case of an error.

See Also

ps_shading()
ps_shfill()

Prev | Home | Next
ps_setpolydash | Up | ps_shading


ps_shfill

(PECL)

ps_shfill -- Fills an area with a shading

Description

bool ps_shfill ( resource psdoc, int shadingid )

Fills an area with a shading, which has to be created before with ps_shading(). This is an alternative way to creating a pattern from a shading ps_shading_pattern() and using the pattern as the filling color.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_shading()
ps_shading_pattern()

Prev | Home | Next
ps_shading | Up | ps_show_boxed


ps_show

(PECL)

ps_show -- Output text

Description

bool ps_show ( resource psdoc, string text )

Output a text at the current text position. The text position can be set by storing the x and y coordinates into the values textx and texty with the function ps_set_value(). The function will issue an error if a font was not set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_continue_text()
ps_show_xy()
ps_setfont()

Prev | Home | Next
ps_show_xy | Up | ps_string_geometry


ps_show_boxed

(PECL)

ps_show_boxed -- Output text in a box

Description

int ps_show_boxed ( resource psdoc, string text, float left, float bottom, float width, float height, string hmode [, string feature] )

Outputs a text in a given box. The lower left corner of the box is at (left, bottom). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter hyphenation is set to true and the parameter hyphendict contains a valid filename for a hyphenation file. The line spacing is taken from the value leading. Paragraphs can be separated by an empty line just like in TeX. If the value parindent is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter numindentlines. In order to prevent indenting of the first m paragraphs set the value parindentskip to a positive number.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output into the given box.

left

x-coordinate of the lower left corner of the box.

bottom

y-coordinate of the lower left corner of the box.

width

Width of the box.

height

Height of the box.

hmode

The parameter hmode can be "justify", "fulljustify", "right", "left", or "center". The difference of "justify" and "fulljustify" just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.

feature

Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output, the following parameters and values are evaluated.

leading (value)

Distance between baselines of two consecutive lines.

linebreak (parameter)

Set to "true" if you want a carriage return to start a new line instead of treating it as a space. Defaults to "false".

parbreak (parameter)

Set to "true" if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to "true".

hyphenation (parameter)

Set to "true" in order to turn hyphenation on. This requires a dictionary to be set with the parameter "hyphendict". Defaults to "false".

hyphendict (parameter)

Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value "numindentlines".

parskip (value)

Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.

numindentlines (value)

Number of lines from the start of the paragraph which will be indented. Defaults to 1.

parindentskip (value)

Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.

linenumbermode (parameter)

Set how lines are to be numbered. Possible values are "box" for numbering lines in the whole box or "paragraph" to number lines within each paragraph.

linenumberspace (value)

The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.

linenumbersep (value)

The space between the column with line numbers and the line itself. Defaults to 5.

Hyphenation

Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

/usr/share/apps/koffice/hyphdicts/
/usr/lib/scribus/dicts/
/usr/lib/openoffice/share/dict/ooo/

Currently scribus appears to have the most complete hyphenation dictionaries.

Return Values

Number of characters that could not be written.

See Also

ps_continue_text()

Prev | Home | Next
ps_shfill | Up | ps_show_xy


ps_show_xy

(PECL)

ps_show_xy -- Output text at given position

Description

bool ps_show_xy ( resource psdoc, string text, float x, float y )

Output a text at the given text position.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

x

x-coordinate of the lower left corner of the box surrounding the text.

y

y-coordinate of the lower left corner of the box surrounding the text.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_continue_text()
ps_show()

Prev | Home | Next
ps_show_boxed | Up | ps_show


ps_string_geometry

(PECL)

ps_string_geometry -- Gets geometry of a string

Description

array ps_string_geometry ( resource psdoc, string text [, int fontid [, float size]] )

This function is similar to ps_stringwidth() but returns an array of dimensions containing the width, ascender, and descender of the text.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the geometry is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

See Also

ps_continue_text()
ps_stringwidth()

Prev | Home | Next
ps_show | Up | ps_stringwidth


ps_stringwidth

(PECL)

ps_stringwidth -- Gets width of a string

Description

float ps_stringwidth ( resource psdoc, string text [, int fontid [, float size]] )

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the width is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

Width of a string in points.

See Also

ps_string_geometry()

Prev | Home | Next
ps_string_geometry | Up | ps_stroke


ps_stroke

(PECL)

ps_stroke -- Draws the current path

Description

bool ps_stroke ( resource psdoc )

Draws the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_closepath_stroke()
ps_fill()
ps_fill_stroke()

Prev | Home | Next
ps_stringwidth | Up | ps_symbol_name


ps_symbol

(PECL)

ps_symbol -- Output a glyph

Description

bool ps_symbol ( resource psdoc, int ord )

Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ps_symbol_name()
ps_symbol_width()

Prev | Home | Next
ps_symbol_width | Up | ps_translate


ps_symbol_name

(PECL)

ps_symbol_name -- Gets name of a glyph

Description

string ps_symbol_name ( resource psdoc, int ord [, int fontid] )

This function needs an Adobe font metrics file to know which glyphs are available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

Return Values

The name of a glyph in the given font.

See Also

ps_symbol()
ps_symbol_width()

Prev | Home | Next
ps_stroke | Up | ps_symbol_width


ps_symbol_width

(PECL)

ps_symbol_width -- Gets width of a glyph

Description

float ps_symbol_width ( resource psdoc, int ord [, int fontid [, float size]] )

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

The width of a glyph in points.

See Also

ps_symbol()
ps_symbol_name()

Prev | Home | Next
ps_symbol_name | Up | ps_symbol


ps_translate

(PECL)

ps_translate -- Sets translation

Description

bool ps_translate ( resource psdoc, float x, float y )

Sets a new initial point of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the origin of the translated coordinate system.

y

y-coordinate of the origin of the translated coordinate system.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Translation of the coordinate system

&#60;?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_delete($ps);
?&#62;

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

See Also

ps_scale()
ps_rotate()

Prev | Home | Next
ps_symbol | Up | Pspell Functions


px_close

(PECL)

px_close -- Closes a paradox database

Description

bool px_close ( resource pxdoc )

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_open_fp()
The example at px_new()

Prev | Home | Next
Paradox File Access | Up | px_create_fp


px_create_fp

(PECL)

px_create_fp -- Create a new paradox database

Description

bool px_create_fp ( resource pxdoc, resource file, array fielddesc )

Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.

Note: Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Note: This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

File handle as returned by fopen().

fielddesc

fielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Creating a Paradox database with two fields

&#60;?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
  /* Error handling */
}
px_set_parameter($pxdoc, "tablename", "testtable");
for($i=-50; $i&#60;50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?&#62;

See Also

px_new()
px_put_record()
fopen()

Prev | Home | Next
px_close | Up | px_date2string


px_date2string

(no version information, might be only in CVS)

px_date2string -- Converts a date into a string.

Description

string px_date2string ( resource pxdoc, int value, string format )

Turns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

value

Value as stored in paradox database field of type PX_FIELD_DATE.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Turn a paradox date into a human readable form

&#60;?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px, $days, "n/d/Y")."\n";

px_delete($px);
?&#62;

The above example will output:

7/15/1917
7/15/1917

See Also

px_timestamp2string()
jdtogregorian()

Prev | Home | Next
px_create_fp | Up | px_delete_record


px_delete

(PECL)

px_delete -- Deletes resource of paradox database

Description

bool px_delete ( resource pxdoc )

Deletes the resource of the paradox file and frees all memory.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
px_delete_record | Up | px_get_field


px_delete_record

(PECL)

px_delete_record -- Deletes record from paradox database

Description

bool px_delete_record ( resource pxdoc, int num )

This function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Prev | Home | Next
px_date2string | Up | px_delete


px_get_field

(PECL)

px_get_field -- Returns the specification of a single field

Description

array px_get_field ( resource pxdoc, int fieldno )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

fieldno

Number of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.

Return Values

Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.

Prev | Home | Next
px_delete | Up | px_get_info


px_get_info

(PECL)

px_get_info -- Return lots of information about a paradox file

Description

array px_get_info ( resource pxdoc )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.

fileversion

Version of file multiplied by 10, e.g. 70.

tablename

Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

recordsize

Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.

numdatablocks

The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.

numindexfields

Number of fields used for the primary index. The fields do always start with field number 1.

codepage

The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().

See Also

px_numfields()
px_numrecords()

Prev | Home | Next
px_get_field | Up | px_get_parameter


px_get_parameter

(PECL)

px_get_parameter -- Gets a parameter

Description

string px_get_parameter ( resource pxdoc, string name )

Gets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.

inputencoding

The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.

Return Values

Returns the value of the parameter or FALSE on failure.

Prev | Home | Next
px_get_info | Up | px_get_record


px_get_record

(PECL)

px_get_record -- Returns record of paradox database

Description

array px_get_record ( resource pxdoc, int num [, int mode] )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys of the returned array into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp (PX_FIELD_TIMESTAMP) and date (PX_FIELD_DATE) are floating point respectively int values counting milliseconds respectively days starting at the beginning of julian calendar. Use the functions px-timestamp2string() and px-date2string() to convert them into a character representation.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

px_retrieve_record()

Prev | Home | Next
px_get_parameter | Up | px_get_schema


px_get_schema

(PECL)

px_get_schema -- Returns the database schema

Description

array px_get_schema ( resource pxdoc [, int mode] )

px_get_schema() returns the database schema.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

mode

If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of the returned array will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.

Return Values

Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types. size is the number of bytes this field consumes in the record. The total of all field sizes is equal to the record size as it can be retrieved with px-get-info().

Prev | Home | Next
px_get_record | Up | px_get_value


px_get_value

(PECL)

px_get_value -- Gets a value

Description

float px_get_value ( resource pxdoc, string name )

Gets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

Return Values

Returns the value of the parameter or FALSE on failure.

Prev | Home | Next
px_get_schema | Up | px_insert_record


px_insert_record

(PECL)

px_insert_record -- Inserts record into paradox database

Description

int px_insert_record ( resource pxdoc, array data )

Inserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.

Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

Return Values

Returns FALSE on failure or the record number in case of success.

Examples

Example 1. Set the date/time fields in a paradox database to the current date/time

&#60;?php
$px = px_new();
$fp = fopen("test.db", "w+");
px_create_fp($px, $fp, array(array("timestamp", "@"), array("time", "T"), array("date", "D")));

$curdate = getdate();
$jd = gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days = $jd - 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs = $curdate["hours"]*3600 + $curdate["minutes"]*60 + $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));

$curtimestamp = microtime(true);
$days = (int) ($curtimestamp/86400);
$secs = $curtimestamp - ($days * 86400.0);
$days += 2440588; /* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
for($i=0; $i&#60;2; $i++) {
    $rec = px_retrieve_record($px, $i);
    echo px_timestamp2string($px, $rec["timestamp"], "n/d/Y H:i:s")."\n";
    echo px_date2string($px, $rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?&#62;

The above example will output:

2/21/2006 21:42:30
2/21/2006
2/21/2006 20:42:30
2/21/2006

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

See Also

px_update_record()

Prev | Home | Next
px_get_value | Up | px_new


px_new

(PECL)

px_new -- Create a new paradox object

Description

resource px_new ( void )

Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it just creates an instance of a paradox object. This function must not be called if the object oriented interface is used. Use new paradox_db() instead.

Return Values

Returns FALSE on failure.

Examples

Example 1. Opening a Paradox database

&#60;?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
  /* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?&#62;

If you prefer the object oriented API, then the above example will look like the following.

Example 2. Opening a Paradox database

&#60;?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc-&#62;open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc-&#62;close();
fclose($fp);
?&#62;

See Also

px_delete()
px_open_fp()

Prev | Home | Next
px_insert_record | Up | px_numfields


px_numfields

(PECL)

px_numfields -- Returns number of fields in a database

Description

int px_numfields ( resource pxdoc )

Get the number of fields in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the array returned by px_get_info().

Prev | Home | Next
px_new | Up | px_numrecords


px_numrecords

(PECL)

px_numrecords -- Returns number of records in a database

Description

int px_numrecords ( resource pxdoc )

Get the number of records in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the array returned by px_get_info().

Prev | Home | Next
px_numfields | Up | px_open_fp


px_open_fp

(PECL)

px_open_fp -- Open paradox database

Description

bool px_open_fp ( resource pxdoc, resource file )

Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

file is the return value from fopen() with the actual database file as parameter. Make sure the database is writable if you plan to update or insert records.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

fopen()
The example at px_new()

Prev | Home | Next
px_numrecords | Up | px_put_record


px_put_record

(PECL)

px_put_record -- Stores record into paradox database

Description

bool px_put_record ( resource pxdoc, array record [, int recpos] )

Stores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

record

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

recpos

This optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
px_open_fp | Up | px_retrieve_record


px_retrieve_record

(PECL)

px_retrieve_record -- Returns record of paradox database

Description

array px_retrieve_record ( resource pxdoc, int num [, int mode] )

This function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

px_get_record()

Prev | Home | Next
px_put_record | Up | px_set_blob_file


px_set_blob_file

(PECL)

px_set_blob_file -- Sets the file where blobs are read from

Description

bool px_set_blob_file ( resource pxdoc, string filename )

Sets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.

Calling px_put_record(),
px_insert_record(), or
px_update_record() without calling
px_set_blob_file() will result in truncated blob fields
unless the data fits into the database file.

Calling this function twice will close the first blob file and open the new one.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
px_retrieve_record | Up | px_set_parameter


px_set_parameter

(PECL)

px_set_parameter -- Sets a parameter

Description

bool px_set_parameter ( resource pxdoc, string name, string value )

Sets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

Depending on the parameter you want to set, name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

The value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_get_info() to determine the DOS code page.

Prev | Home | Next
px_set_blob_file | Up | px_set_tablename


px_set_tablename

(PECL)

px_set_tablename -- Sets the name of a table (deprecated)

Description

void px_set_tablename ( resource pxdoc, string name )

Sets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

tablename

The name of the table. If it is not set explicitly it will be set to the name of the database file.

Return Values

Returns NULL on success or FALSE on failure.

See Also

px_set_parameter()

Prev | Home | Next
px_set_parameter | Up | px_set_targetencoding


px_set_targetencoding

(PECL)

px_set_targetencoding -- Sets the encoding for character fields (deprecated)

Description

bool px_set_targetencoding ( resource pxdoc, string encoding )

Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database file. The encoding can be any string identifier known to iconv or recode. On unix systems run iconv -l for a list of available encodings.

This function is deprecated and should be replaced by calling px_set_parameter().

See also px_get_info() to determine the DOS code page as stored in the database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

encoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

Return Values

Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.

See Also

px_set_parameter()

Prev | Home | Next
px_set_tablename | Up | px_set_value


px_set_value

(PECL)

px_set_value -- Sets a value

Description

bool px_set_value ( resource pxdoc, string name, float value )

Sets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_set_parameter()

Prev | Home | Next
px_set_targetencoding | Up | px_timestamp2string


px_timestamp2string

(PECL)

px_timestamp2string -- Converts the timestamp into a string.

Description

string px_timestamp2string ( resource pxdoc, float value, string format )

Turns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of milliseconds since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.

Parameters

pxdoc

Resource identifier of the paradox database.

value

Value as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Turn a paradox timestamp into a human readable form

&#60;?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";

/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in milli seconds since 1.1.0000 */
$stamp = $days * 86400.0 * 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px, $stamp, "n/d/Y H:i:s")."\n";

px_delete($px);
?&#62;

The above example will output:

7/15/1917
7/15/1917 01:00:00

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

See Also

px_date2string()
jdtogregorian()

Prev | Home | Next
px_set_value | Up | px_update_record


px_update_record

(PECL)

px_update_record -- Updates record in paradox database

Description

bool px_update_record ( resource pxdoc, array data, int num )

Updates an exiting record in the database. The record starts at 0.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated array containing the field values as returned by px_retrieve_record().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

See Also

px_insert_record()

Prev | Home | Next
px_timestamp2string | Up | Parsekit Functions


radius_acct_open

(PECL)

radius_acct_open -- Creates a Radius handle for accounting

Description

resource radius_acct_open ( void )

Return Values

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Examples

Example 1. radius_acct_open() example

&#60;?php
$res = radius_acct_open ()
    or die ("Could not create handle");
print("Handle successfully created");
?&#62;

Prev | Home | Next
Radius | Up | radius_add_server


radius_add_server

(PECL)

radius_add_server -- Adds a server

Description

bool radius_add_server ( resource radius_handle, string hostname, int port, string secret, int timeout, int max_tries )

radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.

Parameters

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_add_server() example

&#60;?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
    echo 'RadiusError:' . radius_strerror($res). "\n&#60;br&#62;";
    exit;
}
?&#62;

See Also

radius_config()

Prev | Home | Next
radius_acct_open | Up | radius_auth_open


radius_auth_open

(PECL)

radius_auth_open -- Creates a Radius handle for authentication

Description

resource radius_auth_open ( void )

Return Values

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Examples

Example 1. radius_auth_open() example

&#60;?php
$radh = radius_auth_open()
    or die ("Could not create handle");
echo "Handle successfully created";
?&#62;

Prev | Home | Next
radius_add_server | Up | radius_close


radius_close

(PECL)

radius_close -- Frees all ressources

Description

bool radius_close ( resource radius_handle )

It is not needed to call this function because php frees all resources at the end of each request.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
radius_auth_open | Up | radius_config


radius_config

(PECL)

radius_config -- Causes the library to read the given configuration file

Description

bool radius_config ( resource radius_handle, string file )

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in radius.conf.

Parameters

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

radius_add_server()

Prev | Home | Next
radius_close | Up | radius_create_request


radius_create_request

(PECL)

radius_create_request -- Create accounting or authentication request

Description

bool radius_create_request ( resource radius_handle, int type )

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Note: Attention: You must call this function, before you can put any attribute!

Parameters

radius_handle

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

type

Its description

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_create_request() example

&#60;?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n&#60;br /&#62;";
    exit;
}
?&#62;

See Also

radius_send_request()

Prev | Home | Next
radius_config | Up | radius_cvt_addr


radius_cvt_addr

(PECL)

radius_cvt_addr -- Converts raw data to IP-Address

Description

string radius_cvt_addr ( string data )

Examples

Example 1. radius_cvt_addr() example

&#60;?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_IP_ADDRESS:
        $ip = radius_cvt_addr($data);
        echo "IP: $ip&#60;br&#62;\n";
        break;

    case RADIUS_FRAMED_IP_NETMASK:
        $mask = radius_cvt_addr($data);
        echo "MASK: $mask&#60;br&#62;\n";
        break;
    }
}
?&#62;

See Also

radius_cvt_int()
radius_cvt_string()

Prev | Home | Next
radius_create_request | Up | radius_cvt_int


radius_cvt_int

(PECL)

radius_cvt_int -- Converts raw data to integer

Description

int radius_cvt_int ( string data )

Examples

Example 1. radius_cvt_int() example

&#60;?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_MTU:
        $mtu = radius_cvt_int($data);
        echo "MTU: $mtu&#60;br&#62;\n";
        break;
    }
}
?&#62;

See Also

radius_cvt_addr()
radius_cvt_string()

Prev | Home | Next
radius_cvt_addr | Up | radius_cvt_string


radius_cvt_string

(PECL)

radius_cvt_string -- Converts raw data to string

Description

string radius_cvt_string ( string data )

Examples

Example 1. radius_cvt_string() example

&#60;?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FILTER_ID:
        $id = radius_cvt_string($data);
        echo "Filter ID: $id&#60;br&#62;\n";
        break;
    }
}
?&#62;

See Also

radius_cvt_addr()
radius_cvt_int()

Prev | Home | Next
radius_cvt_int | Up | radius_demangle_mppe_key


radius_demangle

(PECL)

radius_demangle -- Demangles data

Description

string radius_demangle ( resource radius_handle, string mangled )

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

Return Values

Returns the demangled string, or FALSE on error.

Prev | Home | Next
radius_demangle_mppe_key | Up | radius_get_attr


radius_demangle_mppe_key

(PECL)

radius_demangle_mppe_key -- Derives mppe-keys from mangled data

Description

string radius_demangle_mppe_key ( resource radius_handle, string mangled )

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

Return Values

Returns the demangled string, or FALSE on error.

Prev | Home | Next
radius_cvt_string | Up | radius_demangle


radius_get_attr

(PECL)

radius_get_attr -- Extracts an attribute

Description

mixed radius_get_attr ( resource radius_handle )

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

Return Values

Returns an associative array containing the attribute-type and the data, or error number <= 0.

Examples

Example 1. radius_get_attr() example

&#60;?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
}
?&#62;

See Also

radius_put_attr()
radius_get_vendor_attr()
radius_put_vendor_attr()
radius_send_request()

Prev | Home | Next
radius_demangle | Up | radius_get_vendor_attr


radius_get_vendor_attr

(PECL)

radius_get_vendor_attr -- Extracts a vendor specific attribute

Description

array radius_get_vendor_attr ( string data )

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

Return Values

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

Examples

Example 1. radius_get_vendor_attr() example

&#60;?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
    if ($attr == RADIUS_VENDOR_SPECIFIC) {

        $resv = radius_get_vendor_attr($data);
        if (is_array($resv)) {
            $vendor = $resv['vendor'];
            $attrv = $resv['attr'];
            $datav = $resv['data'];
            printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));
        }

    }
}
?&#62;

See Also

radius_get_attr()
radius_put_vendor_attr()

Prev | Home | Next
radius_get_attr | Up | radius_put_addr


radius_put_addr

(PECL)

radius_put_addr -- Attaches an IP-Address attribute

Description

bool radius_put_addr ( resource radius_handle, int type, string addr )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
radius_get_vendor_attr | Up | radius_put_attr


radius_put_attr

(PECL)

radius_put_attr -- Attaches a binary attribute

Description

bool radius_put_attr ( resource radius_handle, int type, string value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_put_attr() example

&#60;?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n&#60;br /&#62;";
    exit;
}
?&#62;

See Also

radius_get_attr()
radius_get_vendor_attr()
radius_put_vendor_attr()

Prev | Home | Next
radius_put_addr | Up | radius_put_int


radius_put_int

(PECL)

radius_put_int -- Attaches an integer attribute

Description

bool radius_put_int ( resource radius_handle, int type, int value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_put_int() example

&#60;?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n&#60;br /&#62;";
   exit;
}
?&#62;

See Also

radius_put_string()
radius_put_vendor_int()
radius_put_vendor_string()

Prev | Home | Next
radius_put_attr | Up | radius_put_string


radius_put_string

(PECL)

radius_put_string -- Attaches a string attribute

Description

bool radius_put_string ( resource radius_handle, int type, string value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_put_string() example

&#60;?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n&#60;br /&#62;";
    exit;
}
?&#62;

See Also

radius_put_int()
radius_put_vendor_int()
radius_put_vendor_string()

Prev | Home | Next
radius_put_int | Up | radius_put_vendor_addr


radius_put_vendor_addr

(PECL)

radius_put_vendor_addr -- Attaches a vendor specific IP-Address attribute

Description

bool radius_put_vendor_addr ( resource radius_handle, int vendor, int type, string addr )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
radius_put_string | Up | radius_put_vendor_attr


radius_put_vendor_attr

(PECL)

radius_put_vendor_attr -- Attaches a vendor specific binary attribute

Description

bool radius_put_vendor_attr ( resource radius_handle, int vendor, int type, string value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. radius_put_vendor_attr() example

&#60;?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
    echo 'RadiusError:' . radius_strerror($res). "\n&#60;br /&#62;";
    exit;
}
?&#62;

Prev | Home | Next
radius_put_vendor_addr | Up | radius_put_vendor_int


radius_put_vendor_int

(PECL)

radius_put_vendor_int -- Attaches a vendor specific integer attribute

Description

bool radius_put_vendor_int ( resource radius_handle, int vendor, int type, int value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
radius_put_vendor_attr | Up | radius_put_vendor_string


radius_put_vendor_string

(PECL)

radius_put_vendor_string -- Attaches a vendor specific string attribute

Description

bool radius_put_vendor_string ( resource radius_handle, int vendor, int type, string value )

Warning

This function is currently not documented; only the argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
radius_put_vendor_int | Up | radius_request_authenticator


radius_request_authenticator

(PECL)

radius_request_authenticator -- Returns the request authenticator

Description

string radius_request_authenticator ( resource radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

Return Values

Returns the request authenticator as string, or FALSE on error.

See Also

radius_demangle()

Prev | Home | Next
radius_put_vendor_string | Up | radius_send_request


radius_send_request

(PECL)

radius_send_request -- Sends the request and waites for a reply

Description

int radius_send_request ( resource radius_handle )

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

Return Values

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.

See Also

radius_create_request()

Prev | Home | Next
radius_request_authenticator | Up | radius_server_secret


radius_server_secret

(PECL)

radius_server_secret -- Returns the shared secret

Description

string radius_server_secret ( resource radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

Return Values

Returns the server's shared secret as string, or FALSE on error.

Prev | Home | Next
radius_send_request | Up | radius_strerror


radius_strerror

(PECL)

radius_strerror -- Returns an error message

Description

string radius_strerror ( resource radius_handle )

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

Return Values

Returns error messages as string from failed radius functions.

Prev | Home | Next
radius_server_secret | Up | Rar Functions


rpm_close

(no version information, might be only in CVS)

rpm_close -- Closes an RPM file

Description

bool rpm_close ( resource rpmr )

rpm_close() will close an RPM file pointer.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. rpm_close() example

&#60;?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?&#62;

See Also

rpm_open()

Prev | Home | Next
RPM Header Reading Functions | Up | rpm_get_tag


rpm_get_tag

(no version information, might be only in CVS)

rpm_get_tag -- Retrieves a header tag from an RPM file

Description

mixed rpm_get_tag ( resource rpmr, int tagnum )

rpm_get_tag() will retrieve a given tag from the RPM file's header and return it.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

tagnum

The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.

Return Values

The return value can be of various types depending on the tagnum supplied to the function.

Examples

Example 1. rpm_get_tag() example

&#60;?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name&#60;br&#62;\n";

rpm_close($rpmr);

?&#62;

See Also

rpm_open()
rpm_close()

Prev | Home | Next
rpm_close | Up | rpm_is_valid


rpm_is_valid

(no version information, might be only in CVS)

rpm_is_valid -- Tests a filename for validity as an RPM file

Description

bool rpm_is_valid ( string filename )

rpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.

Parameters

filename

The filename of the RPM file you wish to check for validity.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. rpm_is_valid() example

&#60;?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.&#60;br&#62;\n";
}
else {
    echo "File is not recognized as an RPM file.&#60;br&#62;\n";
}

?&#62;

Prev | Home | Next
rpm_get_tag | Up | rpm_open


rpm_open

(no version information, might be only in CVS)

rpm_open -- Opens an RPM file

Description

resource rpm_open ( string filename )

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Parameters

filename

The filename of the RPM file you wish to open.

Return Values

If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.

Examples

Example 1. rpm_open() example

&#60;?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?&#62;

See Also

rpm_close()

Prev | Home | Next
rpm_is_valid | Up | rpm_version


rpm_version

(no version information, might be only in CVS)

rpm_version -- Returns a string representing the current version of the rpmreader extension

Description

string rpm_version ( void )

rpm_version() will return the current version of the rpmreader extension.

Return Values

rpm_version() will return a string representing the rpmreader version currently loaded in PHP.

Examples

Example 1. rpm_version() example

&#60;?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver&#60;br /&#62;\n";

?&#62;

Prev | Home | Next
rpm_open | Up | runkit Functions


runkit_class_adopt

(PECL)

runkit_class_adopt -- Convert a base class to an inherited class, add ancestral methods when appropriate

Description

bool runkit_class_adopt ( string classname, string parentname )

Parameters

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A runkit_class_adopt() example

&#60;?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?&#62;

The above example will output:

Parent Function Output

See Also

runkit_class_emancipate()

Prev | Home | Next
Runkit_Sandbox_Parent | Up | runkit_class_emancipate


runkit_class_emancipate

(PECL)

runkit_class_emancipate -- Convert an inherited class to a base class, removes any method whose scope is ancestral

Description

bool runkit_class_emancipate ( string classname )

Parameters

classname

Name of class to emancipate

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A runkit_class_emancipate() example

&#60;?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?&#62;

The above example will output:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

See Also

runkit_class_adopt()

Prev | Home | Next
runkit_class_adopt | Up | runkit_constant_add


runkit_constant_add

(PECL)

runkit_constant_add -- Similar to define(), but allows defining in class definitions as well

Description

bool runkit_constant_add ( string constname, mixed value )

Parameters

constname

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, or Resource value to store in the new constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

define()
runkit_constant_redefine()
runkit_constant_remove()

Prev | Home | Next
runkit_class_emancipate | Up | runkit_constant_redefine


runkit_constant_redefine

(PECL)

runkit_constant_redefine -- Redefine an already defined constant

Description

bool runkit_constant_redefine ( string constname, mixed newvalue )

Parameters

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

runkit_constant_add()
runkit_constant_remove()

Prev | Home | Next
runkit_constant_add | Up | runkit_constant_remove


runkit_constant_remove

(PECL)

runkit_constant_remove -- Remove/Delete an already defined constant

Description

bool runkit_constant_remove ( string constname )

Parameters

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

define()
runkit_constant_add()
runkit_constant_redefine()

Prev | Home | Next
runkit_constant_redefine | Up | runkit_function_add


runkit_function_add

(PECL)

runkit_function_add -- Add a new function, similar to create_function()

Description

bool runkit_function_add ( string funcname, string arglist, string code )

Parameters

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A runkit_function_add() example

&#60;?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?&#62;

The above example will output:

The value of a is 1
The value of b is 2

See Also

create_function()
runkit_function_redefine()
runkit_function_copy()
runkit_function_rename()
runkit_function_remove()
runkit_method_add()

Prev | Home | Next
runkit_constant_remove | Up | runkit_function_copy


runkit_function_copy

(PECL)

runkit_function_copy -- Copy a function to a new function name

Description

bool runkit_function_copy ( string funcname, string targetname )

Parameters

funcname

Name of existing function

targetname

Name of new function to copy definition to

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A runkit_function_copy() example

&#60;?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?&#62;

The above example will output:

In a function
In a function

See Also

runkit_function_add()
runkit_function_redefine()
runkit_function_rename()
runkit_function_remove()

Prev | Home | Next
runkit_function_add | Up | runkit_function_redefine


runkit_function_redefine

(PECL)

runkit_function_redefine -- Replace a function definition with a new implementation

Description

bool runkit_function_redefine ( string funcname, string arglist, string code )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in the system-wide php.ini file.

Parameters

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A runkit_function_redefine() example

&#60;?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?&#62;

The above example will output:

Original Testme Implementation
New Testme Implementation

See Also

runkit_function_add()
runkit_function_copy()
runkit_function_rename()
runkit_function_remove()

Prev | Home | Next
runkit_function_copy | Up | runkit_function_remove


runkit_function_remove

(PECL)

runkit_function_remove -- Remove a function definition

Description

bool runkit_function_remove ( string funcname )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in the system-wide php.ini file.

Parameters

funcname

Name of function to be deleted

Return Values

Returns TRUE on success or FALSE on failure.

See Also

runkit_function_add()
runkit_function_copy()
runkit_function_redefine()
runkit_function_rename()

Prev | Home | Next
runkit_function_redefine | Up | runkit_function_rename


runkit_function_rename

(PECL)

runkit_function_rename -- Change a function's name

Description

bool runkit_function_rename ( string funcname, string newname )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in the system-wide php.ini file.

Parameters

funcname

Current function name

newname

New function name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

runkit_function_add()
runkit_function_copy()
runkit_function_redefine()
runkit_function_remove()

Prev | Home | Next
runkit_function_remove | Up | runkit_import


runkit_import

(PECL)

runkit_import -- Process a PHP file importing function and class definitions, overwriting where appropriate

Description

bool runkit_import ( string filename [, int flags] )

Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags, any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.

Parameters

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
runkit_function_rename | Up | runkit_lint_file


runkit_lint

(PECL)

runkit_lint -- Check the PHP syntax of the specified php code

Description

bool runkit_lint ( string code )

The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the commandline except runkit_lint() accepts actual code rather than a filename.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

code

PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

runkit_lint_file()

Prev | Home | Next
runkit_lint_file | Up | runkit_method_add


runkit_lint_file

(PECL)

runkit_lint_file -- Check the PHP syntax of the specified file

Description

bool runkit_lint_file ( string filename )

The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

filename

File containing PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

runkit_lint()

Prev | Home | Next
runkit_import | Up | runkit_lint


runkit_method_add

(PECL)

runkit_method_add -- Dynamically adds a new method to a given class

Description

bool runkit_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 RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_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. runkit_method_add() example

&#60;?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e-&#62;add(12, 4);
?&#62;

The above example will output:

16

See Also

runkit_method_copy()
runkit_method_redefine()
runkit_method_remove()
runkit_method_rename()
runkit_function_add()

Prev | Home | Next
runkit_lint | Up | runkit_method_copy


runkit_method_copy

(PECL)

runkit_method_copy -- Copies a method from class to another

Description

bool runkit_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. runkit_method_copy() example

&#60;?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()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?&#62;

The above example will output:

foo!

See Also

runkit_method_add()
runkit_method_redefine()
runkit_method_remove()
runkit_method_rename()
runkit_function_copy()

Prev | Home | Next
runkit_method_add | Up | runkit_method_redefine


runkit_method_redefine

(PECL)

runkit_method_redefine -- Dynamically changes the code of the given method

Description

bool runkit_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 RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_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. runkit_method_redefine() example

&#60;?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e-&#62;foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e-&#62;foo();
?&#62;

The above example will output:

Before: foo!
After: bar!

See Also

runkit_method_add()
runkit_method_copy()
runkit_method_remove()
runkit_method_rename()
runkit_function_redefine()

Prev | Home | Next
runkit_method_copy | Up | runkit_method_remove


runkit_method_remove

(PECL)

runkit_method_remove -- Dynamically removes the given method

Description

bool runkit_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. runkit_method_remove() example

&#60;?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?&#62;

The above example will output:

bar

See Also

runkit_method_add()
runkit_method_copy()
runkit_method_redefine()
runkit_method_rename()
runkit_function_remove()

Prev | Home | Next
runkit_method_redefine | Up | runkit_method_rename


runkit_method_rename

(PECL)

runkit_method_rename -- Dynamically changes the name of the given method

Description

bool runkit_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. runkit_method_rename() example

&#60;?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?&#62;

The above example will output:

foo!

See Also

runkit_method_add()
runkit_method_copy()
runkit_method_redefine()
runkit_method_remove()
runkit_function_rename()

Prev | Home | Next
runkit_method_remove | Up | runkit_return_value_used


runkit_return_value_used

(no version information, might be only in CVS)

runkit_return_value_used -- Determines if the current functions return value will be used

Description

bool runkit_return_value_used ( void )

Return Values

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

Examples

Example 1. runkit_return_value_used() example

&#60;?php
function foo() {
  var_dump(runkit_return_value_used());
}

foo();
$f = foo();
?&#62;

The above example will output:

bool(false)
bool(true)

Prev | Home | Next
runkit_method_rename | Up | runkit_sandbox_output_handler


runkit_sandbox_output_handler

(PECL)

runkit_sandbox_output_handler -- Specify a function to capture and/or process output from a runkit sandbox

Description

mixed runkit_sandbox_output_handler ( object sandbox [, mixed callback] )

Ordinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Deprecated: As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.

Parameters

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.

Return Values

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Examples

Example 1. Feeding output to a variable

&#60;?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php-&#62;echo("Hello\n");
$php-&#62;eval('var_dump("Excuse me");');
$php-&#62;die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?&#62;

The above example will output:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.

Prev | Home | Next
runkit_return_value_used | Up | runkit_superglobals


runkit_superglobals

(PECL)

runkit_superglobals -- Return numerically indexed array of registered superglobals

Description

array runkit_superglobals ( void )

Return Values

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

See Also

Variable Scope

Prev | Home | Next
runkit_sandbox_output_handler | Up | SAM - Simple Asynchronous Messaging


SAMConnection->commit()

(no version information, might be only in CVS)

SAMConnection->commit() -- Commits (completes) the current unit of work.

Description

class SAMConnection {

bool commit ( void )

}

Calling the "commit" method on a Connection object commits (completes) all in-flight transactions that are part of the current unit of work.

Return Values

This method returns FALSE if an error occurs.

Examples

Example 1. Committing the current unit of work

&#60;?php
  if (!$conn-&#62;commit()) {
    // The commit failed!
    echo "Commit failed ($conn-&#62;errno) $conn-&#62;error";
  }
?&#62;

See Also

SAMConnection->rollback()

Prev | Home | Next
SAM - Simple Asynchronous Messaging | Up | SAMConnection->connect()


SAMConnection->connect()

(no version information, might be only in CVS)

SAMConnection->connect() -- Establishes a connection to a Messaging Server

Description

class SAMConnection {

bool connect ( string protocol [, array properties] )

}

Calling the "connect" method on a SAMConnection object connects the PHP script to a messaging server. No messages can be sent or received until a connection is made.

Parameters

protocol

A structured string identifying the protocol to be used when attempting to connect to the messaging server. The supported protocols are represented by constants which are normally used but if required the string may be composed dynamically by the script. The string is made up of 2 parts, the first being the protocol identifier and the second a protocol option. The two parts are seperated by a colon (:) character. Acceptable values are described by the following table:

Protocol string | Constant | Usage
mqtt | SAM_MQTT | Use the MQTT (MQ Telemetry Transport) protocol connecting as a client to a server.
wmq | SAM_WMQ | Use the IBM MQSeries protocol connecting as a client to a remote messaging server. This is equivalent to "wmq:client" (SAM_WMQ_CLIENT). At least a broker name (SAM_BROKER) must be specified in the options array.
wmq:client | SAM_WMQ_CLIENT | Use the IBM MQSeries protocol connecting as a client to a remote messaging server. At least a broker name (SAM_BROKER) must be specified in the options array.
wmq:bindings | SAM_WMQ_BINDINGS | Use the IBM MQSeries protocol connecting to a local messaging server and communicating via shared memory. At least a broker name (SAM_BROKER) must be specified in the options array.
wpm | SAM_WPM | Use the IBM WebSphere Platform Messaging protocol to connect to the messaging infrastructure of a WebSphere Application server or cluster. A bus name must be specified in the options array (SAM_BUS) and endpoint and target chain may also be specified.
rtt | SAM_RTT | Use the IBM Realtime transport protocol to connect to the messaging infrastructure.

properties

An optional associative array of properties to describe the details of the connection required. The following table lists the available property names and accepted values:

Property name | default | Usage
SAM_BROKER none The name of the broker or queue manager running on the messaging server.

This property must be set if using one of the variants of the WebSphere MQSeries protocol (SAM_WMQ, SAM_WMQ_CLIENT, SAM_WMQ_BINDINGS).

SAM_HOST | localhost | The hostname of the machine on which the messaging server is running.
SAM_PORT | 1414 for SAM_WMQ, 1506 for SAM_WPM, or 1883 for SAM_MQTT | The port number on which to attempt communication with the messaging server.
SAM_EXPIRE_AFTER 0 Time in milliseconds after which a message is deemed to have expired and can be deleted from queues. The default value is 0 indicating the message never expires.

Warning: Not yet implemented!

SAM_MESSAGE_PERSISTENCE none Selects whether messages are made persistent during delivery. The value may be SAM_PERSISTENT or SAM_NON_PERSISTENT. The default is dependant on the connection type and capabilities of the Messaging Server to which the connection is made.

Warning: Not yet implemented!

SAM_MQTT_CLEANSTART | FALSE | Optional connect option to indicate to an MQTT server that all previous connection data for this client should be removed and that subscriptions should be deleted when the client disconnects explicitly or unexpectedly. Setting the value to TRUE causes SAM to discard any subscription already in place for the client when it connects and also to discard subscription when the client disconnects. Setting the option to FALSE, or using the default, allows subscriptions to be durable and survive across client disconnects.
SAM_PASSWORD | none | The password to be used when the Messaging Server to which the connection is being made requires authentication.
SAM_TRANSACTIONS | SAM_AUTO | Indicates how transactions are handled on this connection. The value may be SAM_AUTO (the default) to allow automatic handling on a per operation basis or SAM_MANUAL to allow the PHP script to control the transaction boundaries. If SAM_MANUAL is used any in-flight transactions will be rolled back if the script is terminated or the connection is closed without a commit being executed.
SAM_USERID | none | The user id to be used when the Messaging Server to which the connection is being made requires authentication.
SAM_WPM_DUR_SUB_HOME | none | The name of the messaging engine where durable subscriptions are managed. (WPM ONLY).

Return Values

This method returns FALSE if an error occurs.

Examples

Example 1. Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)

&#60;?php

$conn-&#62;connect(SAM_WMQ, array(SAM_HOST =&#62; 'Myhost.myco.com', SAM_PORT =&#62; 1506, SAM_BROKER =&#62; 'MyBroker'));

?&#62;

Example 2. Creating a connection with application transaction control and default host and port values

&#60;?php

$conn-&#62;connect(SAM_WMQ, array(SAM_BROKER =&#62; 'MyBroker', SAM_TRANSACTIONS =&#62; SAM_MANUAL));

?&#62;

Example 3. Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)

&#60;?php

$conn-&#62;connect(SAM_WPM, array(SAM_ENDPOINTS =&#62; 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS =&#62; 'Bus1', SAM_TARGETCHAIN =&#62; 'InboundBasicMessaging'));

?&#62;

See Also

SAMConnection->isConnected()
SAMConnection->disconnect()

Prev | Home | Next
SAMConnection->commit() | Up | SAMConnection->__construct()


SAMConnection->__construct()

(no version information, might be only in CVS)

SAMConnection->__construct() -- Creates a new connection to a Messaging Server

Description

class SAMConnection {

__construct ( )

}

Creates a new SAMConnection object.

Examples

Example 1. Creating a connection object and connecting to a Messaging Server

&#60;?php

$conn = new SAMConnection();
$conn-&#62;connect(SAM_WMQ, array(SAM_HOST =&#62; localhost, SAM_PORT =&#62; 1414, SAM_BROKER =&#62; 'bull'));

?&#62;

Prev | Home | Next
SAMConnection->connect() | Up | SAMConnection->disconnect()


SAMConnection->disconnect()

(no version information, might be only in CVS)

SAMConnection->disconnect() -- Disconnects from a Messaging Server

Description

class SAMConnection {

bool disconnect ( void )

}

Calling the "disconnect" method on a SAMConnection object disconnects the PHP script from a messaging server. No messages can be sent or received after a connection has been disconnected.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Disconnecting from a Messaging Server

&#60;?php

$conn-&#62;disconnect();

?&#62;

See Also

SAMConnection->isConnected()
SAMConnection->connect()

Prev | Home | Next
SAMConnection->__construct() | Up | SAMConnection->errno


SAMConnection->errno

(no version information, might be only in CVS)

SAMConnection->errno -- Contains the unique numeric error code of the last executed SAM operation.

Description

class SAMConnection {

int errno

}

Contains the numeric error code of the last executed SAM operation on this connection. If the last operation completed successfully this property contains 0.

Return Values

An integer greater than zero indicates the last error type encountered on the connection. Zero indicates that the last operation on this connection completed successfully.

Examples

Example 1. Using the error number and description properties

&#60;?php
$conn = new SAMConnection();
$conn-&#62;connect(SAM_WMQ, array(SAM_HOST =&#62; 'localhost', SAM_PORT =&#62; 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn-&#62;send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

See Also

SAMConnection->error

Prev | Home | Next
SAMConnection->disconnect() | Up | SAMConnection->error


SAMConnection->error

(no version information, might be only in CVS)

SAMConnection->error -- Contains the text description of the last failed SAM operation.

Description

class SAMConnection {

string error

}

Contains the text description of the last failed SAM operation on this connection. If the last operation completed successfully this property contains an empty string.

Return Values

A string containing the text description of the last error type encountered on the connection. An empty string indicates that the last operation on this connection completed successfully.

Examples

Example 1. Using the error number and description properties

&#60;?php
$conn = new SAMConnection();
$conn-&#62;connect(SAM_WMQ, array(SAM_HOST =&#62; 'localhost', SAM_PORT =&#62; 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn-&#62;send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

See Also

SAMConnection->errno

Prev | Home | Next
SAMConnection->errno | Up | SAMConnection->isConnected()


SAMConnection->isConnected()

(no version information, might be only in CVS)

SAMConnection->isConnected() -- Queries whether a connection is established to a Messaging Server

Description

class SAMConnection {

bool isConnected ( void )

}

Calling the "isConnected" method on a Connection object will check whether the PHP script is connected to a messaging server. No messages can be sent or received unless a connection has been established with a Messaging server.

Return Values

This method returns TRUE if the SAMConnection object is successfully connected to a Messaging server or FALSE otherwise.

Examples

Example 1. Checking whether there us a connection to a Messaging Server

&#60;?php

if ($conn-&#62;isConnected()) {
  echo 'Connection is active.'
} else {
  echo 'No active connection!'
}

?&#62;

See Also

SAMConnection->disconnect()
SAMConnection->connect()

Prev | Home | Next
SAMConnection->error | Up | SAMConnection->peek()


SAMConnection->peek()

(no version information, might be only in CVS)

SAMConnection->peek() -- Read a message from a queue without removing it from the queue.

Description

class SAMConnection {

SAMMessage peek ( string target [, array properties] )

}

Parameters

target

The identity of the queue from which to peek the message.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be peeked.

Return Values

This method returns a SAMMessage object or FALSE if an error occurs.

Examples

Example 1. Retrieve the next message from a queue without removing it

&#60;?php
$msg = $conn-&#62;peek('queue://receive/test');

if (!$msg) {
  // The peek failed!
  echo "Peek failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Example 2. Retrieve a specific message from a queue without removing it from the queue

&#60;?php

$msg = $conn-&#62;peek('queue://receive/test', array(SAM_MESSAGEID =&#62; $messageId));

?&#62;

See Also

SAMConnection->peekAll()

Prev | Home | Next
SAMConnection->isConnected() | Up | SAMConnection->peekAll()


SAMConnection->peekAll()

(no version information, might be only in CVS)

SAMConnection->peekAll() -- Read one or more messages from a queue without removing it from the queue.

Description

class SAMConnection {

array peekAll ( string target [, array properties] )

}

Parameters

target

The identity of the queue from which messages should be peeked.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of messages to be peeked. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of a message which is to be peeked.

Return Values

This method returns an array of SAMMessage objects or FALSE if an error occurs.

Examples

Example 1. Retrieve all messages in a queue without removing them

&#60;?php
$msgArray = $conn-&#62;peekAll('queue://receive/test');
if ($msgArray) {
   foreach ( $msgArray as $key =&#62; $msg) {
       echo "Message $key: body = $msg-&#62;body\n";
   }
} else {
   echo "PeekAll failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Example 2. Retrieve all messages from a queue with a matching correlation id

&#60;?php

   $msgArray = $conn-&#62;peekAll('queue://receive/test', array(SAM_CORRELID =&#62; $correlId ));
   if ($msgArray) {

      foreach ( $msgArray as $key =&#62; $msg) {
            echo "Message $key: body = $msg-&#62;body\n";
         }
      }
   else
      echo "PeekAll failed ($conn-&#62;errno) $conn-&#62;error";
   }

?&#62;

See Also

SAMConnection->peek()

Prev | Home | Next
SAMConnection->peek() | Up | SAMConnection->receive()


SAMConnection->receive()

(no version information, might be only in CVS)

SAMConnection->receive() -- Receive a message from a queue or subscription.

Description

class SAMConnection {

SAMMessage receive ( string target [, array properties] )

}

Parameters

target

The identity of the queue, topic or subscription from which to receive the message.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_CORRELID | Used to request selection of the message to receive based upon the correlation id string of the message.
SAM_MESSAGEID | Used to request selection of the message to receive based upon the message id string of the message.
SAM_WAIT | Timeout value in milliseconds to control how long the request should block waiting to receive a message before returning with a failure if no message is available on the queue or topic. The default value is 0 meaning wait indefinitely and should be used with caution as the request may wait until the overall PHP script processing time limit has expired if no message becomes available.

Return Values

This method returns a SAMMessage object or FALSE if an error occurs.

Examples

Example 1. Receiving a message from a queue

&#60;?php
$msg = $conn-&#62;receive('queue://receive/test');

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Example 2. Receiving a message from a queue with options

In this example the SAM_CORRELID option is used to specify a correlation id string to be used to identify the message to receive. A wait timeout of 10 seconds is also specified.

&#60;?php

$msg = $conn-&#62;receive('queue://receive/test', array(SAM_CORRELID =&#62; $token, SAM_WAIT =&#62; 10000));

?&#62;

Example 3. Receiving a message from a subscription

In this example we show how to receive a message from a subscription id.

&#60;?php
$msg = $conn-&#62;receive($subscriptionName);

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Please note that $subscriptionName is a subscription id returned from an earlier subscribe call.

See Also

SAMConnection->send()

Prev | Home | Next
SAMConnection->peekAll() | Up | SAMConnection->remove()


SAMConnection->remove()

(no version information, might be only in CVS)

SAMConnection->remove() -- Remove a message from a queue.

Description

class SAMConnection {

SAMMessage remove ( string target [, array properties] )

}

Removes a message from a queue.

Parameters

target

The identity of the queue from which to remove the message.

properties

An optional associative array of properties describing other parameters to control the remove operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be removed.

Return Values

This method returns FALSE if an error occurs.

Examples

Example 1. Removing a message from a queue by message id

&#60;?php
if (!$conn-&#62;remove('queue://receive/test', array(SAM_MESSAGEID =&#62; $messageId))) {
  // The remove failed!
  echo "Remove failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Prev | Home | Next
SAMConnection->receive() | Up | SAMConnection->rollback()


SAMConnection->rollback()

(no version information, might be only in CVS)

SAMConnection->rollback() -- Cancels (rolls back) an in-flight unit of work.

Description

class SAMConnection {

bool rollback ( void )

}

Rolls back an in-flight unit of work.

Return Values

This method returns FALSE if an error occurs.

Examples

Example 1. Cancelling an in-flight unit of work

&#60;?php
if (!$conn-&#62;rollback()) {
  // The rollback failed!
  echo "Rollback failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

See Also

SAMConnection->commit()

Prev | Home | Next
SAMConnection->remove() | Up | SAMConnection->send()


SAMConnection->send()

(no version information, might be only in CVS)

SAMConnection->send() -- Send a message to a queue or publish an item to a topic.

Description

class SAMConnection {

string send ( string target, SAMMessage msg [, array properties] )

}

The "send" method is used to send a message to a specific queue or to publish to a specific topic. The method returns a correlation id that can be used as a selector to identify reply or response messages when these are requested.

Parameters

target

If sending a message, the identity of the queue (queue://queuename) or if publishing to a topic the identity of the topic (topic://topicname) to which the message is to be delivered.

msg

The message to be sent or published.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_DELIVERYMODE | Indicates whether the messaging server should enusre delivery or whether it is acceptable for messages to be lost in the case of system failures. The value of this property may be set to either SAM_PERSISTENT, to indicate that message loss is not acceptable, or SAM_NON_PERSISTENT, if message loss is acceptable. The resulting behaviour of the send will vary depending on the capabilities of the messaging server the PHP script is currently connected to. If the server does not support persistent messages and SAM_PERSISTENT is specified the send request will fail with an error indication showing the capability is not available.
SAM_PRIORITY | A numeric value between 0 and 9 indicating the desired message delivery priority. A priority value of 0 indicates the lowest priority while 9 indicates highest priority. If no priority is specified a default will be assigned which is dependent on the messaging server being used.
SAM_CORRELID | A string to be assigned as a correlation id for this message. If no value is given the messaging server may assign a value automatically.
SAM_TIMETOLIVE | A time in milliseconds indicating how long the messaging server should retain the message on a queue before discarding it. The default value is 0 indicating the message should be retained indefinitely.
SAM_WMQ_TARGET_CLIENT | This property is only valid when using WebSphere MQ and indicates whether or not an RFH2 header should be included with the message. This option may be set to either 'jms' or 'mq'. The default is 'jms' which means that an RFH2 header is included. If the value 'mq' is specified then no RFH2 is included with the message.

Return Values

A correlation id string that can be used in a subsequent receive call as a selector to obtain any reply or response that has been requested or FALSE if an error occurred.

Note: A correlation id will only be returned for a successful send to a queue destination (queue://xxxx) in which case it will reflect the message identitiy of the message on the queue. In the case of a send being used to publish data to a topic the return value will be TRUE as no correlation id is availabe for return.

Examples

Example 1. Send a message to a queue

&#60;?php
$msg = new SAMMessage('This is a simple text message');
$correlId = $conn-&#62;send('queue://send/test', $msg);
if (!$correlId) {
    // The send failed!
    echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
}

?&#62;

Example 2. Publish a message to a topic

&#60;?php
$msg = new SAMMessage('This is a simple text item');
if (!$conn-&#62;send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

Example 3. Send a request and receive a response

&#60;?php
$msg = new SAMMessage('This is a simple text message');
$msg-&#62;header-&#62;SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn-&#62;send('queue://send/test', $msg);

if (!$correlid) {
    // The Send failed!
    echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
} else {
    $resp = $conn-&#62;receive('queue://receive/test', array(SAM_CORRELID =&#62; $correlid));
}
?&#62;

See Also

SAMConnection->receive()

Prev | Home | Next
SAMConnection->rollback() | Up | SAMConnection::setDebug()


SAMConnection::setDebug()

(no version information, might be only in CVS)

SAMConnection::setDebug() -- Turn on or off additional debugging output.

Description

The "setdebug" method is used to turn on or off additional debugging output. The SAM framework will provide method/function entry and exit trace data plus additional information. Protocol specific implementations also provide extra output.

class SAMConnection {

void send ( bool switch )

}

Parameters

switch

If this parameter is set to TRUE additional debugging output will be provided. If the value is set to FALSE output of additional information will be stopped.

Examples

Example 1. Turn on debugging output

&#60;?php
$conn-&#62;setdebug(TRUE);
?&#62;

Example 2. Turn off debugging output

&#60;?php
$conn-&#62;setdebug(FALSE);
?&#62;

Prev | Home | Next
SAMConnection->send() | Up | SAMConnection->subscribe()


SAMConnection->subscribe()

(no version information, might be only in CVS)

SAMConnection->subscribe() -- Create a subscription to a specified topic.

Description

class SAMConnection {

string subscribe ( string targetTopic )

}

The "subscribe" method is used to create a new subscription to a specified topic.

Parameters

targetTopic

The identity of the topic (topic://topicname) to subscribe to.

Return Values

A subscription identifier that can be used in a subsequent receive call as a selector to obtain any topic data or FALSE if an error occurred. The subscription identifier should be used in the receive call in place of the simple topic name.

Examples

Example 1. Subscribe to a topic

&#60;?php
$subid = $conn-&#62;subscribe('topic://A');
if (!$subid) {
  // The subscribe failed!
  echo "Subscribe failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

See Also

SAMConnection->unsubscribe()

Prev | Home | Next
SAMConnection::setDebug() | Up | SAMConnection->unsubscribe()


SAMConnection->unsubscribe()

(no version information, might be only in CVS)

SAMConnection->unsubscribe() -- Cancel a subscription to a specified topic.

Description

class SAMConnection {

bool unsubscribe ( string subscriptionId [, string targetTopic] )

}

The "unsubscribe" method is used to delete an existing subscription to a specified topic.

Parameters

subscriptionId

The identifier of an existing subscription as returned by a call to the subscribe method.

Return Values

This method returns FALSE if an error occurs.

Examples

Example 1. Delete a subscription

&#60;?php
if (!$conn-&#62;unsubscribe($subid)) {
    // The unsubscribe failed!
    echo "Unsubscribe failed ($conn-&#62;errno) $conn-&#62;error";
}
?&#62;

See Also

SAMConnection->subscribe()

Prev | Home | Next
SAMConnection->subscribe() | Up | SAMMessage->body


SAMMessage->body

(no version information, might be only in CVS)

SAMMessage->body -- The body of the message.

Description

class SAMMessage {

string nody

}

The "body" property contains the actual body of the message. It may not always be set.

Examples

Example 1. Setting a text string into the body of a message

&#60;?php
$msg = new SAMMessage();
$msg-&#62;body = 'This is a simple message';

?&#62;

See Also

SAMMessage->header

Prev | Home | Next
SAMConnection->unsubscribe() | Up | SAMMessage->__construct()


SAMMessage->__construct()

(no version information, might be only in CVS)

SAMMessage->__construct() -- Creates a new Message object

Description

class SAMMessage {

__construct ( [mixed body] )

}

Creates a new SAMMessage object optionally specifying a message body.

Parameters

body

The optional body for the message.

Examples

Example 1. Creating a message

&#60;?php

$msg = new SAMMessage();

?&#62;

Example 2. Creating a message with a simple text payload

&#60;?php

$msg = new SAMMessage('This is a simple text message');

?&#62;

Prev | Home | Next
SAMMessage->body | Up | SAMMessage->header


SAMMessage->header

(no version information, might be only in CVS)

SAMMessage->header -- The header properties of the message.

Description

class SAMMessage {

object header

}

The header property is a container for any system or user properties that area associated with the message.

Properties may be assigned by the sender of a message to control the way the messaging systems handles it or may be assigned by the messaging system itself to tell the recipient extra information about the message or the way in which it has been handled.

Some properties are understood by SAM in which case constants have been defined for them. The majority of properties however are ignored by the SAM implementation and simply passed through to the underlying messaging systems allowing the application to use messaging specific property names or to define its own "user" properties.

The SAM defined properties are as follows:

Property name | Possible values
SAM_MESSAGEID | When a message is received this field contains the unique identifier of the message as allocated by the underlying messaging system. When sending a message this field is ignored.
SAM_REPLY_TO | A string providing the identity of the queue on to which responses to this message should be posted.
SAM_TYPE

An indication of the type of message to be sent. The value may be SAM_TEXT indicating the contents of the message body is a text string, or SAM_BYTES indicating the contents of the message body are some application defined format.

The way in which this property is used may depend on the underlying messaging server. For instance a messaging server that supports the JMS (Java Message Service) specification may interpret this value and send messages of type "jms_text" and "jms_bytes". In addition, if the SAM_TYPE property is set to SAM_TEXT the data provided for the message body is expected to be a UTF8 encoded string.

When setting the values of properties it is often useful to give a hint as to the format in which the property should be delivered to the messaging system. By default property values are delivered as text and the following simple syntax may be used to set a value:

Example 1. Setting a text format property using the default syntax

&#60;?php
$msg = new SAMMessage();

$msg-&#62;header-&#62;myPropertyName = 'textData';
?&#62;

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Example 2. Setting a text format property using a type hint

&#60;?php
$msg = new SAMMessage();

$msg-&#62;header-&#62;myPropertyName = array('textData', SAM_STRING);
?&#62;

When passing a type hint the type entry should be one of the SAM defined constant values as defined by the following table:

Constant | Type description
SAM_BOOLEAN | Any value passed will be interpreted as logical true or false. If the value cannot be interpreted as a PHP boolean value the value passed to the messaging system is undefined.
SAM_BYTE | An 8-bit signed integer value. SAM will attempt to convert the property value specified into a single byte value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 8-bit signed binary value data may be lost in the conversion.
SAM_DOUBLE | A long floating point value. SAM will attempt to convert the property value specified into a floating point value with 15 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 15 digit floating point value data may be lost in the conversion.
SAM_FLOAT | A short floating point value. SAM will attempt to convert the property value specified into a floating point value with 7 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 7 digit floating point value data may be lost in the conversion.
SAM_INT | An 32-bit signed integer value. SAM will attempt to convert the property value specified into a 32-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 32-bit signed binary value data may be lost in the conversion.
SAM_LONG | An 64-bit signed integer value. SAM will attempt to convert the property value specified into a 64-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 64-bit signed binary value data may be lost in the conversion.
SAM_STRING | SAM will interpret the property value specified as a string and pass it to the messaging system accordingly.

Examples

Example 3. Setting properties as the sender of a message

&#60;?php
$msg = new SAMMessage('This is a test message');

// defining SAM specific properties...
$msg-&#62;header-&#62;SAM_REPLY_TO = 'queue://test/replyQueue';

// defining arbitrary properties...
//
// a default string property
$msg-&#62;header-&#62;myStringProp1 = 'a string property';
// a string property with a type hint
$msg-&#62;header-&#62;myStringProp2 = array('another string property', SAM_STRING);

// a boolean property
$msg-&#62;header-&#62;myBoolProp = array(FALSE, SAM_BOOL);

// numeric format properties
$msg-&#62;header-&#62;myIntProp = array(32768, SAM_INT);
$msg-&#62;header-&#62;myLongProp = array(9876543, SAM_LONG);
$msg-&#62;header-&#62;myByteProp1 = array(123, SAM_BYTE);
$msg-&#62;header-&#62;myByteProp2 = array('12', SAM_BYTE);
$msg-&#62;header-&#62;myFloatProp = array(3.141592, SAM_FLOAT);
$msg-&#62;header-&#62;myDoubleProp = array(3.14159265358979, SAM_DOUBLE);
?&#62;

Example 4. Retreiving property values from a message

&#60;?php

// accessing an application specific property
$intProp = $msg-&#62;header-&#62;'MyIntProp';

// accessing a messaging system specific property
$encoding = $msg-&#62;header-&#62;'JMS_IBM_Msgtype';

?&#62;

See Also

SAMMessage->body

Prev | Home | Next
SAMMessage->__construct() | Up | Satellite CORBA client extension [deprecated]


satellite_caught_exception

(4.0.3 - 4.1.2 only, PECL)

satellite_caught_exception -- See if an exception was caught from the previous function

Description

bool satellite_caught_exception ( void )

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

This function returns TRUE if an exception has been caught, FALSE otherwise.

Examples

Example 1. Sample IDL file

/* ++?????++ Out of Cheese Error. Redo From Start. */
exception OutOfCheeseError {
    int parameter;
}

interface AnotherInterface {
    void AskWhy() raises (OutOfCheeseError);
}

Example 2. PHP code for handling CORBA exceptions

&#60;?php
$obj = new OrbitObject ($ior);

$obj-&#62;AskWhy();

if (satellite_caught_exception()) {
    if ("IDL:OutOfCheeseError:1.0" == satellite_exception_id()) {
        $exception = satellite_exception_value();
        echo $exception-&#62;parameter;
    }
}
?&#62;

Prev | Home | Next
OrbitStruct | Up | satellite_exception_id


satellite_exception_id

(4.0.3 - 4.1.2 only, PECL)

satellite_exception_id -- Get the repository id for the latest exception.

Description

string satellite_exception_id ( void )

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.

For example usage see satellite_caught_exception().

Return Values

Return a repository id string. (E.g. "IDL:MyException:1.0".)

Prev | Home | Next
satellite_caught_exception | Up | satellite_exception_value


satellite_exception_value

(4.0.3 - 4.1.2 only, PECL)

satellite_exception_value -- Get the exception struct for the latest exception

Description

OrbitStruct satellite_exception_value ( void )

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 an exception struct. For example usage see satellite_caught_exception().

Prev | Home | Next
satellite_exception_id | Up | satellite_get_repository_id


satellite_get_repository_id

(4.0.3 - 4.1.2 only, PECL)

satellite_get_repository_id -- NOT IMPLEMENTED

Description

int satellite_get_repository_id ( object obj )

Not implemented.

Prev | Home | Next
satellite_exception_value | Up | satellite_load_idl


satellite_load_idl

(4.0.3 - 4.1.2 only, PECL)

satellite_load_idl -- Instruct the type manager to load an IDL file

Description

bool satellite_load_idl ( string file )

Load an IDL file into Satellite.

Prev | Home | Next
satellite_get_repository_id | Up | satellite_object_to_string


satellite_object_to_string

(4.1.0 - 4.1.2 only, PECL)

satellite_object_to_string -- Convert an object to its string representation

Description

string satellite_object_to_string ( object obj )

Convert an object to its string representation (IOR).

Prev | Home | Next
satellite_load_idl | Up | SCA Functions


SCA::createDataObject

(no version information, might be only in CVS)

SCA::createDataObject -- create an SDO

Description

SDO_DataObject SCA::createDataObject ( string type_namespace_uri, string type_name )

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.

This method is used inside an SCA component that needs to create an SDO to return. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in one of the schema files which are specfied on the @types annotation within the component.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations.

Prev | Home | Next
SCA_SoapProxy::createDataObject | Up | SCA::getService


SCA::getService

(no version information, might be only in CVS)

SCA::getService -- Obtain a proxy for a service

Description

mixed SCA::getService ( string target )

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.

Examine the target and initialise and return a proxy of the appropriate sort. If the target is for a local PHP component the returned proxy will be an SCA_LocalProxy. If the target is for a WSDL file, the returned proxy will be a SCA_SoapProxy.

Parameters

target

An absolute or relative path to the PHP component, or to the WSDL file. A relative path, if specified, is resolved relative to the location of the script issuing the getService call, and not against the include_path or current working directory.

Return Values

The SCA_LocalProxy or SCA_SoapProxy.

Prev | Home | Next
SCA::createDataObject | Up | SDO Functions


SCA_LocalProxy::createDataObject

(no version information, might be only in CVS)

SCA_LocalProxy::createDataObject -- create an SDO

Description

SDO_DataObject SCA_LocalProxy::createDataObject ( string type_namespace_uri, string type_name )

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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a local service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined in one of the schema files which are specfied on the @types annotation within the component for which the SCA_LocalProxy object is a proxy.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations within the component for which the SCA_LocalProxy object is a proxy..

Prev | Home | Next
SCA Functions | Up | SCA_SoapProxy::createDataObject


SCA_SoapProxy::createDataObject

(no version information, might be only in CVS)

SCA_SoapProxy::createDataObject -- create an SDO

Description

SDO_DataObject SCA_SoapProxy::createDataObject ( string type_namespace_uri, string type_name )

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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a web service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined within the WSDL for the web service. If the web service is also an SCA component then the types will have been defined within one of the schema files which are specfied on the @types annotation within the component for which the SCA_SoapProxy object is a proxy.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type found in the WSDL that was used to initialise this SCA_SoapProxy.

Prev | Home | Next
SCA_LocalProxy::createDataObject | Up | SCA::createDataObject


SDO_DAS_ChangeSummary::beginLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::beginLogging -- Begin change logging

Description

void SDO_DAS_ChangeSummary::beginLogging ( void )

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.

Begin logging changes made to the SDO_DataObject.

Parameters

None.

Return Values

None.

Prev | Home | Next
SDO Functions | Up | SDO_DAS_ChangeSummary::endLogging


SDO_DAS_ChangeSummary::endLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::endLogging -- End change logging

Description

void SDO_DAS_ChangeSummary::endLogging ( void )

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.

End logging changes made to an SDO_DataObject.

Parameters

None.

Return Values

None.

Prev | Home | Next
SDO_DAS_ChangeSummary::beginLogging | Up | SDO_DAS_ChangeSummary::getChangeType


SDO_DAS_ChangeSummary::getChangedDataObjects

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getChangedDataObjects -- Get the changed data objects from a change summary

Description

SDO_List SDO_DAS_ChangeSummary::getChangedDataObjects ( void )

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.

Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.

Parameters

None.

Return Values

Returns an SDO_List of SDO_DataObjects.

Prev | Home | Next
SDO_DAS_ChangeSummary::getChangeType | Up | SDO_DAS_ChangeSummary::getOldContainer


SDO_DAS_ChangeSummary::getChangeType

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getChangeType -- Get the type of change made to an SDO_DataObject

Description

int SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject dataObject )

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.

Get the type of change which has been made to the supplied SDO_DataObject.

Parameters

dataObject

The SDO_DataObject which has been changed.

Return Values

The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:

  • SDO_DAS_ChangeSummary::NONE

  • SDO_DAS_ChangeSummary::MODIFICATION

  • SDO_DAS_ChangeSummary::ADDITION

  • SDO_DAS_ChangeSummary::DELETION

Prev | Home | Next
SDO_DAS_ChangeSummary::endLogging | Up | SDO_DAS_ChangeSummary::getChangedDataObjects


SDO_DAS_ChangeSummary::getOldContainer

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getOldContainer -- Get the old container for a deleted SDO_DataObject

Description

SDO_DataObject SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject data_object )

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.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Parameters

data_object

The SDO_DataObject which has been deleted and whose container we wish to identify.

Return Values

The old containing data object of the deleted SDO_DataObject.

Prev | Home | Next
SDO_DAS_ChangeSummary::getChangedDataObjects | Up | SDO_DAS_ChangeSummary::getOldValues


SDO_DAS_ChangeSummary::getOldValues

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getOldValues -- Get the old values for a given changed SDO_DataObject

Description

SDO_List SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject data_object )

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.

Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.

Parameters

data_object

The data object which has been changed.

Return Values

A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject. If the change type is SDO_DAS_ChangeSummary::ADDITION, this list is empty.

Prev | Home | Next
SDO_DAS_ChangeSummary::getOldContainer | Up | SDO_DAS_ChangeSummary::isLogging


SDO_DAS_ChangeSummary::isLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::isLogging -- Test to see whether change logging is switched on

Description

bool SDO_DAS_ChangeSummary::isLogging ( void )

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.

Test to see whether change logging is switched on.

Parameters

None.

Return Values

Returns TRUE if change logging is on, otherwise returns FALSE.

Prev | Home | Next
SDO_DAS_ChangeSummary::getOldValues | Up | SDO_DAS_DataFactory::addPropertyToType


SDO_DAS_DataFactory::addPropertyToType

(no version information, might be only in CVS)

SDO_DAS_DataFactory::addPropertyToType -- Adds a property to a type

Description

void SDO_DAS_DataFactory::addPropertyToType ( string parent_type_namespace_uri, string parent_type_name, string property_name, string type_namespace_uri, string type_name [, array options] )

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.

Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.

Parameters

parent_type_namespace_uri

The namespace URI for the parent type.

parent_type_name

The type name for the parent type.

property_name

The name by which the property will be known in the parent type.

type_namespace_uri

The namespace URI for the type of the property.

type_name

The type name for the type of the property

options

This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:

many

A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').

readOnly

A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').

containment

A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.

default

A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).

Return Values

None.

ChangeLog

Version | Description
0.5.2 | Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Examples

Example 1. A SDO_DAS_DataFactory::addPropertyToType() example

The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.

&#60;?php
  $df-&#62;addPropertyToType('PersonNS', 'PersonType',
    'addressline', 'commonj.sdo', 'String', array('many'=&#62;true));
?&#62;

Prev | Home | Next
SDO_DAS_ChangeSummary::isLogging | Up | SDO_DAS_DataFactory::addType


SDO_DAS_DataFactory::addType

(no version information, might be only in CVS)

SDO_DAS_DataFactory::addType -- Add a new type to a model

Description

void SDO_DAS_DataFactory::addType ( string type_namespace_uri, string type_name [, array options] )

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.

Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

options

This array holds one or more key=>value pairs to set attribute values for the type. The optional keywords are:

open

A flag to say whether the type is open. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content such as that described by an <xsd:any> element. The default value is 'false'.

sequenced

A flag to say whether the type is sequenced. Sequenced types can have the ordering across properties preserved and can contain unstructured text. The default value is 'false'. For more information on sequenced types see the section on Working with Sequenced Data Objects.

basetype

If specified, an array of namespace URI and type name strings for the type from which this type is derived. An example of the use of base types is when a type derived in an XML schema inherits from another type by using <extension base="...">.

Return Values

None.

Examples

Example 1. A SDO_DAS_DataFactory::addType() example

The following adds a new data object type of 'CompanyType' where that type belongs to the namespace 'CompanyNS'.

&#60;?php
  $df-&#62;addType('CompanyNS', 'CompanyType');
?&#62;

Prev | Home | Next
SDO_DAS_DataFactory::addPropertyToType | Up | SDO_DAS_DataFactory::getDataFactory


SDO_DAS_DataFactory::getDataFactory

(no version information, might be only in CVS)

SDO_DAS_DataFactory::getDataFactory -- Get a data factory instance

Description

SDO_DAS_DataFactory SDO_DAS_DataFactory::getDataFactory ( void )

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.

Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.

Parameters

None.

Return Values

Returns an SDO_DAS_DataFactory.

Prev | Home | Next
SDO_DAS_DataFactory::addType | Up | SDO_DAS_DataObject::getChangeSummary


SDO_DAS_DataObject::getChangeSummary

(no version information, might be only in CVS)

SDO_DAS_DataObject::getChangeSummary -- Get a data object's change summary

Description

SDO_DAS_ChangeSummary SDO_DAS_DataObject::getChangeSummary ( void )

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.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Parameters

None.

Return Values

Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Prev | Home | Next
SDO_DAS_DataFactory::getDataFactory | Up | SDO_DAS_Setting::getListIndex


SDO_DAS_Relational::applyChanges

(no version information, might be only in CVS)

SDO_DAS_Relational::applyChanges -- Applies the changes made to a data graph back to the database.

Description

void SDO_DAS_Relational::applyChanges ( PDO database_handle, SDODataObject root_data_object )

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.

Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

root_data_object

The special root object which is at the top of every SDO data graph.

Return Values

None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.

Errors/Exceptions

SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.

The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.

The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.

Prev | Home | Next
SDO Relational Data Access Service Functions | Up | SDO_DAS_Relational::__construct


SDO_DAS_Relational::__construct

(no version information, might be only in CVS)

SDO_DAS_Relational::__construct -- Creates an instance of a Relational Data Access Service

Description

SDO_DAS_Relational SDO_DAS_Relational::__construct ( array database_metadata [, string application_root_type [, array SDO_containment_references_metadata]] )

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.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Parameters

database_metadata

An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

application_root_type

The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.

SDO_containment_references_metadata

An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Return Values

Returns an SDO_DAS_Relational object on success.

Errors/Exceptions

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Examples

For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Prev | Home | Next
SDO_DAS_Relational::applyChanges | Up | SDO_DAS_Relational::createRootDataObject


SDO_DAS_Relational::createRootDataObject

(no version information, might be only in CVS)

SDO_DAS_Relational::createRootDataObject -- Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

Description

SDODataObject SDO_DAS_Relational::createRootDataObject ( void )

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.

Returns the special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.

The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.

Parameters

None.

Return Values

The root object.

Errors/Exceptions

None.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

Prev | Home | Next
SDO_DAS_Relational::__construct | Up | SDO_DAS_Relational::executePreparedQuery


SDO_DAS_Relational::executePreparedQuery

(no version information, might be only in CVS)

SDO_DAS_Relational::executePreparedQuery -- Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

Description

SDODataObject SDO_DAS_Relational::executePreparedQuery ( PDO database_handle, PDOStatement prepared_statement, array value_list [, array column_specifier] )

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.

Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the the metadata to interpret the result set and returns a data graph.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

prepared_statement

A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.

value_list

An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Return Values

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Errors/Exceptions

SDO_DAS_Relational::executePreparedQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Example 1. Retrieving a data object using executePreparedQuery()

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios .

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 * Use a prepared query with a placeholder.
 ***************************************************************/
$name = 'Acme';
$pdo_stmt = $dbh-&#62;prepare('select name, id from company where name=?');
$root = $das-&#62;executePreparedQuery(
    $dbh,
    $pdo_stmt,
    array($name),
    array('company.name', 'company.id'));

/**************************************************************
 * Echo name and id
 ***************************************************************/
foreach ($root['company'] as $company) {
    echo "Company obtained from the database has name = " .
    $company['name'] . " and id " . $company['id'] . "\n";
}
?&#62;

Prev | Home | Next
SDO_DAS_Relational::createRootDataObject | Up | SDO_DAS_Relational::executeQuery


SDO_DAS_Relational::executeQuery

(no version information, might be only in CVS)

SDO_DAS_Relational::executeQuery -- Executes a given SQL query against a relational database and returns the results as a normalised data graph.

Description

SDODataObject SDO_DAS_Relational::executeQuery ( PDO database_handle, string SQL_statement [, array column_specifier] )

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.

Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the the metadata to interpret the result set. Returns a data graph.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

SQL_statement

The SQL statement to be executed against the database.

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Return Values

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Errors/Exceptions

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

Prev | Home | Next
SDO_DAS_Relational::executePreparedQuery | Up | Semaphore, Shared Memory and IPC Functions


SDO_DAS_Setting::getListIndex

(no version information, might be only in CVS)

SDO_DAS_Setting::getListIndex -- Get the list index for a changed many-valued property

Description

int SDO_DAS_Setting::getListIndex ( void )

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.

Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).

Parameters

None.

Return Values

The list index for the element of the many-valued property which has been changed.

Prev | Home | Next
SDO_DAS_DataObject::getChangeSummary | Up | SDO_DAS_Setting::getPropertyIndex


SDO_DAS_Setting::getPropertyIndex

(no version information, might be only in CVS)

SDO_DAS_Setting::getPropertyIndex -- Get the property index for a changed property

Description

int SDO_DAS_Setting::getPropertyIndex ( void )

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.

Returns the property index for the changed property. This index identifies the property which was modified in data object.

Parameters

None.

Return Values

The property index for a changed property.

Prev | Home | Next
SDO_DAS_Setting::getListIndex | Up | SDO_DAS_Setting::getPropertyName


SDO_DAS_Setting::getPropertyName

(no version information, might be only in CVS)

SDO_DAS_Setting::getPropertyName -- Get the property name for a changed property

Description

string SDO_DAS_Setting::getPropertyName ( void )

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.

Returns the property name for the changed property. This name identifies the property which was modified in data object.

Parameters

None.

Return Values

The property name for a changed property.

Prev | Home | Next
SDO_DAS_Setting::getPropertyIndex | Up | SDO_DAS_Setting::getValue


SDO_DAS_Setting::getValue

(no version information, might be only in CVS)

SDO_DAS_Setting::getValue -- Get the old value for the changed property

Description

mixed SDO_DAS_Setting::getValue ( void )

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.

Returns the old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.

Parameters

None.

Return Values

Returns the old value of the changed property.

Prev | Home | Next
SDO_DAS_Setting::getPropertyName | Up | SDO_DAS_Setting::isSet


SDO_DAS_Setting::isSet

(no version information, might be only in CVS)

SDO_DAS_Setting::isSet -- Test whether a property was set prior to being modified

Description

bool SDO_DAS_Setting::isSet ( void )

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.

Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.

Parameters

None.

Return Values

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.

Prev | Home | Next
SDO_DAS_Setting::getValue | Up | SDO_DataFactory::create


SDO_DAS_XML::addTypes

(no version information, might be only in CVS)

SDO_DAS_XML::addTypes -- To load a second or subsequent schema file to a SDO_DAS_XML object

Description

void SDO_DAS_XML::addTypes ( string xsd_file )

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.

Load a second or subsequent schema file to an XML DAS that has already been created with the static method create(). Although the file may be any valid schema file, a likely reason for using this method is to add a schema file containing definitions of extra complex types, hence the name. See Example 4 of the parent document for an example.

Parameters

xsd_file

Path to XSD Schema file.

Return Values

None if successful, otherwise throws an exception as described below.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

Prev | Home | Next
SDO_DAS_XML_Document::setXMLVersion | Up | SDO_DAS_XML::create


SDO_DAS_XML::create

(no version information, might be only in CVS)

SDO_DAS_XML::create -- To create SDO_DAS_XML object for a given schema file

Description

SDO_DAS_XML SDO_DAS_XML::create ( [string xsd_file] )

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.

This is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.

Parameters

xsd_file

Path to XSD Schema file. This is optional. If omitted a DAS will be created that only has the SDO base types defined. Schema files can then be loaded with the addTypes() method.

Return Values

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

Prev | Home | Next
SDO_DAS_XML::addTypes | Up | SDO_DAS_XML::createDataObject


SDO_DAS_XML::createDataObject

(no version information, might be only in CVS)

SDO_DAS_XML::createDataObject -- Creates SDO_DataObject for a given namespace URI and type name

Description

SDO_DataObject SDO_DAS_XML::createDataObject ( string namespace_uri, string type_name )

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.

Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.

Parameters

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Return Values

Returns SDO_DataObject on success.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

Prev | Home | Next
SDO_DAS_XML::create | Up | SDO_DAS_XML::createDocument


SDO_DAS_XML::createDocument

(no version information, might be only in CVS)

SDO_DAS_XML::createDocument -- Creates an XML Document object from scratch, without the need to load a document from a file or string.

Description

SDO_DAS_XML_Document SDO_DAS_XML::createDocument ( [string document_element_name] )

SDO_DAS_XML_Document SDO_DAS_XML::createDocument ( string document_element_namespace_URI, string document_element_name )

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.

Creates an XML Document object. This will contain just one empty root element on which none of the properties will have been set. The purpose of this call is to allow an application to create an XML document from scratch without the need to load a document from a file or string. The document that is created will be as if a document had been loaded that contained just a single empty document element with no attributes set or elements within it.

createDocument() may need to be told what the document element is. This will not be necessary in simple cases. When there is no ambiguity then no parameter need be passed to the method. However it is possible to load more than one schema file into the same XML DAS and in this case there may be more than one possible document element defined: furthermore it is even possible that there are two possible document elements that differ only in the namespace. To cope with these cases it is possible to specify either the document element name, or both the document element name and namespace to the method.

Parameters

document_element_name

The name of the document element. Only needed if there is more than one possibility.

document_element_namespace_URI

The namespace part of the document element name. Only needed if there is more than one possible document element with the same name.

Return Values

Returns an SDO_XML_DAS_Document object on success.

Errors/Exceptions

SDO_UnsupportedOperationException

Thrown if an element name or element name and namespace URI is passed, but not found in the underlying model.

Prev | Home | Next
SDO_DAS_XML::createDataObject | Up | SDO_DAS_XML::loadFile


SDO_DAS_XML_Document::getRootDataObject

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootDataObject -- Returns the root SDO_DataObject

Description

SDO_DataObject SDO_DAS_XML_Document::getRootDataObject ( void )

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.

Returns the root SDO_DataObject.

Parameters

Return Values

Returns the root SDO_DataObject.

Prev | Home | Next
SDO XML Data Access Service Functions | Up | SDO_DAS_XML_Document::getRootElementName


SDO_DAS_XML_Document::getRootElementName

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootElementName -- Returns root element's name

Description

string SDO_DAS_XML_Document::getRootElementName ( void )

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.

Returns root element's name.

Parameters

Return Values

Returns root element's name.

Prev | Home | Next
SDO_DAS_XML_Document::getRootDataObject | Up | SDO_DAS_XML_Document::getRootElementURI


SDO_DAS_XML_Document::getRootElementURI

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootElementURI -- Returns root element's URI string

Description

string SDO_DAS_XML_Document::getRootElementURI ( void )

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.

Returns root element's URI string.

Parameters

Return Values

Returns root element's URI string.

Prev | Home | Next
SDO_DAS_XML_Document::getRootElementName | Up | SDO_DAS_XML_Document::setEncoding


SDO_DAS_XML_Document::setEncoding

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setEncoding -- Sets the given string as encoding

Description

void SDO_DAS_XML_Document::setEncoding ( string encoding )

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.

Sets the given string as encoding.

Parameters

encoding

Encoding string.

Return Values

None.

Prev | Home | Next
SDO_DAS_XML_Document::getRootElementURI | Up | SDO_DAS_XML_Document::setXMLDeclaration


SDO_DAS_XML_Document::setXMLDeclaration

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setXMLDeclaration -- Sets the xml declaration

Description

void SDO_DAS_XML_Document::setXMLDeclaration ( bool xmlDeclatation )

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.

Controls whether an XML declaration will be generated at the start of the XML document. Set to true to generate the XML declaration, or false to suppress it.

Parameters

xmlDeclatation

Boolean value to set the XML declaration.

Return Values

None.

Prev | Home | Next
SDO_DAS_XML_Document::setEncoding | Up | SDO_DAS_XML_Document::setXMLVersion


SDO_DAS_XML_Document::setXMLVersion

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setXMLVersion -- Sets the given string as xml version

Description

void SDO_DAS_XML_Document::setXMLVersion ( string xmlVersion )

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.

Sets the given string as xml version.

Parameters

xmlVersion

xml version string.

Return Values

None.

Prev | Home | Next
SDO_DAS_XML_Document::setXMLDeclaration | Up | SDO_DAS_XML::addTypes


SDO_DAS_XML::loadFile

(no version information, might be only in CVS)

SDO_DAS_XML::loadFile -- Returns SDO_DAS_XML_Document object for a given path to xml instance document

Description

SDO_XMLDocument SDO_DAS_XML::loadFile ( string xml_file )

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.

Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parameters

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Return Values

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

Prev | Home | Next
SDO_DAS_XML::createDocument | Up | SDO_DAS_XML::loadString


SDO_DAS_XML::loadString

(no version information, might be only in CVS)

SDO_DAS_XML::loadString -- Returns SDO_DAS_XML_Document for a given xml instance string

Description

SDO_DAS_XML_Document SDO_DAS_XML::loadString ( string xml_string )

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.

Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parameters

xml_string

xml string.

Return Values

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

Prev | Home | Next
SDO_DAS_XML::loadFile | Up | SDO_DAS_XML::saveFile


SDO_DAS_XML::saveFile

(no version information, might be only in CVS)

SDO_DAS_XML::saveFile -- Saves the SDO_DAS_XML_Document object to a file

Description

void SDO_DAS_XML::saveFile ( SDO_XMLDocument xdoc, string xml_file [, int indent] )

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.

Saves the SDO_DAS_XML_Document object to a file.

Parameters

xdoc

SDO_DAS_XML_Document object.

xml_file

xml file.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Return Values

None.

Errors/Exceptions

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

Prev | Home | Next
SDO_DAS_XML::loadString | Up | SDO_DAS_XML::saveString


SDO_DAS_XML::saveString

(no version information, might be only in CVS)

SDO_DAS_XML::saveString -- Saves the SDO_DAS_XML_Document object to a string

Description

string SDO_DAS_XML::saveString ( SDO_XMLDocument xdoc [, int indent] )

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.

Saves the SDO_DAS_XML_Document object to string.

Parameters

xdoc

SDO_DAS_XML_Document object.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Return Values

xml string.

Prev | Home | Next
SDO_DAS_XML::saveFile | Up | SDO Relational Data Access Service Functions


SDO_DataFactory::create

(no version information, might be only in CVS)

SDO_DataFactory::create -- Create an SDO_DataObject

Description

void SDO_DataFactory::create ( string type_namespace_uri, string type_name )

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.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.

Prev | Home | Next
SDO_DAS_Setting::isSet | Up | SDO_DataObject::clear


SDO_DataObject::clear

(no version information, might be only in CVS)

SDO_DataObject::clear -- Clear an SDO_DataObject's properties

Description

void SDO_DataObject::clear ( void )

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.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Parameters

None.

Return Values

No return values.

Prev | Home | Next
SDO_DataFactory::create | Up | SDO_DataObject::createDataObject


SDO_DataObject::createDataObject

(no version information, might be only in CVS)

SDO_DataObject::createDataObject -- Create a child SDO_DataObject

Description

SDO_DataObject SDO_DataObject::createDataObject ( mixed 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.

Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.

Parameters

identifier

Identifies the property for the data object type to be created. Can be either a property name (string), a property index (int), or an SDO_Model_Property.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.

Prev | Home | Next
SDO_DataObject::clear | Up | SDO_DataObject::getContainer


SDO_DataObject::getContainer

(no version information, might be only in CVS)

SDO_DataObject::getContainer -- Get a data object's container

Description

SDO_DataObject SDO_DataObject::getContainer ( void )

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.

Get the data object which contains this data object.

Parameters

None.

Return Values

Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).

Prev | Home | Next
SDO_DataObject::createDataObject | Up | SDO_DataObject::getSequence


SDO_DataObject::getSequence

(no version information, might be only in CVS)

SDO_DataObject::getSequence -- Get the sequence for a data object

Description

SDO_Sequence SDO_DataObject::getSequence ( void )

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 the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.

Parameters

None.

Return Values

The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.

Prev | Home | Next
SDO_DataObject::getContainer | Up | SDO_DataObject::getTypeName


SDO_DataObject::getTypeName

(no version information, might be only in CVS)

SDO_DataObject::getTypeName -- Return the name of the type for a data object.

Description

string SDO_DataObject::getTypeName ( void )

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 the name of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getName().

Parameters

None.

Return Values

The name of the type for the data object.

Prev | Home | Next
SDO_DataObject::getSequence | Up | SDO_DataObject::getTypeNamespaceURI


SDO_DataObject::getTypeNamespaceURI

(no version information, might be only in CVS)

SDO_DataObject::getTypeNamespaceURI -- Return the namespace URI of the type for a data object.

Description

string SDO_DataObject::getTypeNamespaceURI ( void )

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 the namespace URI of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getNamespaceURI().

Parameters

None.

Return Values

The namespace URI of the type for the data object.

Prev | Home | Next
SDO_DataObject::getTypeName | Up | SDO_Exception::getCause


SDO_Exception::getCause

(no version information, might be only in CVS)

SDO_Exception::getCause -- Get the cause of the exception.

Description

mixed SDO_Exception::getCause ( void )

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.

Returns the cause of this exception or NULL if the cause is nonexistent or unknown. Typically the cause will be an SDO_CPPException object, which may be used to obtain additional diagnostic information.

Parameters

None.

Return Values

Returns the cause of this exception or NULL if the cause is nonexistent or unknown.

Prev | Home | Next
SDO_DataObject::getTypeNamespaceURI | Up | SDO_List::insert


SDO_List::insert

(no version information, might be only in CVS)

SDO_List::insert -- Insert into a list

Description

void SDO_List::insert ( mixed value [, int index] )

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.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Parameters

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

index

The position at which to insert the new element. If this argument is not specified then the new value will be appended.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the list index is less than zero or greater than the size of the list.

SDO_InvalidConversionException

Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).

Prev | Home | Next
SDO_Exception::getCause | Up | SDO_Model_Property::getContainingType


SDO_Model_Property::getContainingType

(no version information, might be only in CVS)

SDO_Model_Property::getContainingType -- Get the SDO_Model_Type which contains this property

Description

SDO_Model_Type SDO_Model_Property::getContainingType ( void )

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.

Returns the SDO_Model_Type which contains this property.

Parameters

None.

Return Values

Returns the SDO_Model_Type which contains this property.

Prev | Home | Next
SDO_List::insert | Up | SDO_Model_Property::getDefault


SDO_Model_Property::getDefault

(no version information, might be only in CVS)

SDO_Model_Property::getDefault -- Get the default value for the property

Description

mixed SDO_Model_Property::getDefault ( void )

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.

Returns the default value for the property. Only primitive data type properties can have default values.

Parameters

None.

Return Values

Returns the default value for the property.

Prev | Home | Next
SDO_Model_Property::getContainingType | Up | SDO_Model_Property::getName


SDO_Model_Property::getName

(no version information, might be only in CVS)

SDO_Model_Property::getName -- Get the name of the SDO_Model_Property

Description

string SDO_Model_Property::getName ( void )

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.

Returns the name of the SDO_Model_Property.

Parameters

None.

Return Values

Returns the name of the SDO_Model_Property.

Prev | Home | Next
SDO_Model_Property::getDefault | Up | SDO_Model_Property::getType


SDO_Model_Property::getType

(no version information, might be only in CVS)

SDO_Model_Property::getType -- Get the SDO_Model_Type of the property

Description

SDO_Model_Type SDO_Model_Property::getType ( void )

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.

Get the SDO_Model_Type of the property. The SDO_Model_Type describes the type information for the property, such as its type name, namespace URI, whether it is a primitive data type, and so on.

Parameters

None.

Return Values

Returns the SDO_Model_Type describing the property's type information.

Prev | Home | Next
SDO_Model_Property::getName | Up | SDO_Model_Property::isContainment


SDO_Model_Property::isContainment

(no version information, might be only in CVS)

SDO_Model_Property::isContainment -- Test to see if the property defines a containment relationship

Description

bool SDO_Model_Property::isContainment ( void )

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.

Test to see if the property corresponds to a containment relationship. Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

Parameters

None.

Return Values

Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

Prev | Home | Next
SDO_Model_Property::getType | Up | SDO_Model_Property::isMany


SDO_Model_Property::isMany

(no version information, might be only in CVS)

SDO_Model_Property::isMany -- Test to see if the property is many-valued

Description

bool SDO_Model_Property::isMany ( void )

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.

Test to see if the property is many-valued. Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Parameters

None.

Return Values

Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Prev | Home | Next
SDO_Model_Property::isContainment | Up | SDO_Model_ReflectionDataObject::__construct


SDO_Model_ReflectionDataObject::__construct

(no version information, might be only in CVS)

SDO_Model_ReflectionDataObject::__construct -- Construct an SDO_Model_ReflectionDataObject

Description

SDO_Model_ReflectionDataObject SDO_Model_ReflectionDataObject::__construct ( SDO_DataObject data_object )

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.

Construct an SDO_Model_ReflectionDataObject to reflect on an SDO_DataObject. Reflecting on an SDO_DataObject gives access to information about its model. The model contains information such as the data object's type, and whether that type is sequenced (preserves ordering across properties) or open (each instance can have its model extended). The model also holds information about the data object's properties, any default values they may have, and so on.

Parameters

data_object

The SDO_DataObject being reflected upon.

Return Values

None.

Prev | Home | Next
SDO_Model_Property::isMany | Up | SDO_Model_ReflectionDataObject::export


SDO_Model_ReflectionDataObject::export

(no version information, might be only in CVS)

SDO_Model_ReflectionDataObject::export -- Get a string describing the SDO_DataObject.

Description

mixed SDO_Model_ReflectionDataObject::export ( SDO_Model_ReflectionDataObject rdo [, bool return] )

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.

Get a string describing the SDO_DataObject. The default behaviour is to print the output, but if TRUE is specified for return, it is returned as a string.

Parameters

rdo

An SDO_Model_ReflectionDataObject.

return

If TRUE, return the output as a string, otherwise print it.

Return Values

Returns the output if TRUE is specified for return, otherwise NULL.

Prev | Home | Next
SDO_Model_ReflectionDataObject::__construct | Up | SDO_Model_ReflectionDataObject::getContainmentProperty


SDO_Model_ReflectionDataObject::getContainmentProperty

(no version information, might be only in CVS)

SDO_Model_ReflectionDataObject::getContainmentProperty -- Get the property which defines the containment relationship to the data object

Description

SDO_Model_Property SDO_Model_ReflectionDataObject::getContainmentProperty ( void )

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.

Get the SDO_Model_Property that contains the SDO_DataObject. This method is used to navigate up to the parent's property which contains the data object which has been reflected upon.

Parameters

None.

Return Values

Returns the container's SDO_Model_Property which references the SDO_DataObject, or NULL if it is a root SDO_DataObject.

Prev | Home | Next
SDO_Model_ReflectionDataObject::export | Up | SDO_Model_ReflectionDataObject::getInstanceProperties


SDO_Model_ReflectionDataObject::getInstanceProperties

(no version information, might be only in CVS)

SDO_Model_ReflectionDataObject::getInstanceProperties -- Get the instance properties of the SDO_DataObject

Description

array SDO_Model_ReflectionDataObject::getInstanceProperties ( void )

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.

Get the instance properties for the SDO_DataObject. The instance properties consist of all the properties defined on the data object's type, plus any instance properties from open content (if the data object is an open type).

Parameters

None.

Return Values

An array of SDO_Model_Property objects.

Prev | Home | Next
SDO_Model_ReflectionDataObject::getContainmentProperty | Up | SDO_Model_ReflectionDataObject::getType


SDO_Model_ReflectionDataObject::getType

(no version information, might be only in CVS)

SDO_Model_ReflectionDataObject::getType -- Get the SDO_Model_Type for the SDO_DataObject

Description

SDO_Model_Type SDO_Model_ReflectionDataObject::getType ( void )

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.

Returns the SDO_Model_Type for the SDO_DataObject. The SDO_Model_Type holds all the information about the data object's type, such as namespace URI, type name, whether it is a primitive data type, and so on.

Parameters

None.

Return Values

Returns the SDO_Model_Type for the SDO_DataObject.

Prev | Home | Next
SDO_Model_ReflectionDataObject::getInstanceProperties | Up | SDO_Model_Type::getBaseType


SDO_Model_Type::getBaseType

(no version information, might be only in CVS)

SDO_Model_Type::getBaseType -- Get the base type for this type

Description

SDO_Model_Type SDO_Model_Type::getBaseType ( void )

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.

Get the base type for this type. Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL. An example of when base types occur is when a type defined in XML schema inherits from another type by using <extension base="..."> .

Parameters

None.

Return Values

Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL.

Prev | Home | Next
SDO_Model_ReflectionDataObject::getType | Up | SDO_Model_Type::getName


SDO_Model_Type::getName

(no version information, might be only in CVS)

SDO_Model_Type::getName -- Get the name of the type

Description

string SDO_Model_Type::getName ( void )

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.

Returns the name of the type. The combination of type name and namespace URI is used to uniquely identify the type.

Parameters

None.

Return Values

Returns the name of the type.

Prev | Home | Next
SDO_Model_Type::getBaseType | Up | SDO_Model_Type::getNamespaceURI


SDO_Model_Type::getNamespaceURI

(no version information, might be only in CVS)

SDO_Model_Type::getNamespaceURI -- Get the namespace URI of the type

Description

string SDO_Model_Type::getNamespaceURI ( void )

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.

Returns the namespace URI of the type. The combination of namespace URI and type name is used to uniquely identify the type.

Parameters

None.

Return Values

Returns the namespace URI of the type.

Prev | Home | Next
SDO_Model_Type::getName | Up | SDO_Model_Type::getProperties


SDO_Model_Type::getProperties

(no version information, might be only in CVS)

SDO_Model_Type::getProperties -- Get the SDO_Model_Property objects defined for the type

Description

array SDO_Model_Type::getProperties ( void )

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.

Get an array of SDO_Model_Property objects describing the properties defined for the SDO_Model_Type. Each SDO_Model_Property holds information such as the property name, default value, and so on.

Parameters

None.

Return Values

Returns an array of SDO_Model_Property objects.

Prev | Home | Next
SDO_Model_Type::getNamespaceURI | Up | SDO_Model_Type::getProperty


SDO_Model_Type::getProperty

(no version information, might be only in CVS)

SDO_Model_Type::getProperty -- Get an SDO_Model_Property of the type

Description

SDO_Model_Property SDO_Model_Type::getProperty ( mixed 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.

Get an SDO_Model_Property of the type, identified by its property index or property name.

Parameters

identifier

The property index or property name.

Return Values

Returns the SDO_Model_Property.

Prev | Home | Next
SDO_Model_Type::getProperties | Up | SDO_Model_Type::isAbstractType


SDO_Model_Type::isAbstractType

(no version information, might be only in CVS)

SDO_Model_Type::isAbstractType -- Test to see if this SDO_Model_Type is an abstract data type

Description

bool SDO_Model_Type::isAbstractType ( void )

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.

Test to see if this SDO_Model_Type is an abstract data type. Returns TRUE if this type is abstract, that is, no SDO_DataObject of this type can be instantiated, though other types may inherit from it.

Parameters

None.

Return Values

Returns TRUE if this type is an abstract data type, otherwise returns FALSE.

Prev | Home | Next
SDO_Model_Type::getProperty | Up | SDO_Model_Type::isDataType


SDO_Model_Type::isDataType

(no version information, might be only in CVS)

SDO_Model_Type::isDataType -- Test to see if this SDO_Model_Type is a primitive data type

Description

bool SDO_Model_Type::isDataType ( void )

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.

Test to see if this SDO_Model_Type is a primitive data type. Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

Parameters

None.

Return Values

Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

Prev | Home | Next
SDO_Model_Type::isAbstractType | Up | SDO_Model_Type::isInstance


SDO_Model_Type::isInstance

(no version information, might be only in CVS)

SDO_Model_Type::isInstance -- Test for an SDO_DataObject being an instance of this SDO_Model_Type

Description

bool SDO_Model_Type::isInstance ( SDO_DataObject data_object )

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.

Test for an SDO_DataObject being an instance of this SDO_Model_Type. Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

Parameters

data_object

The SDO_DataObject to be tested.

Return Values

Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

Prev | Home | Next
SDO_Model_Type::isDataType | Up | SDO_Model_Type::isOpenType


SDO_Model_Type::isOpenType

(no version information, might be only in CVS)

SDO_Model_Type::isOpenType -- Test to see if this type is an open type

Description

bool SDO_Model_Type::isOpenType ( void )

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.

Test to see if this type is open. Returns TRUE if this type is open, otherwise returns FALSE. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content, such as that defined by an <xsd:any> element.

Parameters

None.

Return Values

Returns TRUE if this type is open, otherwise returns FALSE.

Prev | Home | Next
SDO_Model_Type::isInstance | Up | SDO_Model_Type::isSequencedType


SDO_Model_Type::isSequencedType

(no version information, might be only in CVS)

SDO_Model_Type::isSequencedType -- Test to see if this is a sequenced type

Description

bool SDO_Model_Type::isSequencedType ( void )

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.

Test to see if this is a sequenced type. Returns TRUE if this type is sequence, otherwise returns FALSE. Sequenced types can have the ordering across properties preserved and can contain unstructured text. For more information on sequenced types see the section on Working with Sequenced Data Objects.

Parameters

None.

Return Values

Returns TRUE if this type is sequence, otherwise return FALSE.

Prev | Home | Next
SDO_Model_Type::isOpenType | Up | SDO_Sequence::getProperty


SDO_Sequence::getProperty

(no version information, might be only in CVS)

SDO_Sequence::getProperty -- Return the property for the specified sequence index.

Description

SDO_Model_Property SDO_Sequence::getProperty ( int sequence_index )

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 the property for the specified sequence index.

Parameters

sequence_index

The position of the element in the sequence.

Return Values

An SDO_Model_Property. A return value of NULL means the sequence element does not belong to a property and must therefore be unstructured text.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

Prev | Home | Next
SDO_Model_Type::isSequencedType | Up | SDO_Sequence::insert


SDO_Sequence::insert

(no version information, might be only in CVS)

SDO_Sequence::insert -- Insert into a sequence

Description

void SDO_Sequence::insert ( mixed value [, int sequenceIndex [, mixed propertyIdentifier]] )

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.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Parameters

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

sequenceIndex

The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.

propertyIdentifier

Either a property index, a property name, or an SDO_Model_Property, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_InvalidConversionException

Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.

Prev | Home | Next
SDO_Sequence::getProperty | Up | SDO_Sequence::move


SDO_Sequence::move

(no version information, might be only in CVS)

SDO_Sequence::move -- Move an item to another sequence position

Description

void SDO_Sequence::move ( int toIndex, int fromIndex )

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.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Parameters

toIndex

The destination sequence index. If this index is less than zero or greater than the size of the sequence then the value is appended.

fromIndex

The source sequence index.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the fromIndex sequence index is less than zero or greater than the size of the sequence.

Prev | Home | Next
SDO_Sequence::insert | Up | SDO XML Data Access Service Functions


session_pgsql_add_error

(PECL)

session_pgsql_add_error -- Increments error counts and sets last error message

Description

bool session_pgsql_add_error ( int error_level [, string error_message] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

error_level

error_message

Return Values

Returns TRUE on success or FALSE on failure.

See Also

session_pgsql_get_error()

Prev | Home | Next
PostgreSQL Session Save Handler | Up | session_pgsql_get_error


session_pgsql_get_error

(PECL)

session_pgsql_get_error -- Returns number of errors and last error message

Description

array session_pgsql_get_error ( [bool with_error_message] )

Get the number of errors and optional the error messages.

Parameters

with_error_message

Set to TRUE the literal error message for each error is also returned.

Return Values

The number of errors are returned as array.

See Also

session_pgsql_add_error()

Prev | Home | Next
session_pgsql_add_error | Up | session_pgsql_get_field


session_pgsql_get_field

(PECL)

session_pgsql_get_field -- Get custom field value

Description

string session_pgsql_get_field ( void )

Warning

This function is currently not documented; only the argument list is available.

See Also

session_pgsql_set_field()

Prev | Home | Next
session_pgsql_get_error | Up | session_pgsql_reset


session_pgsql_reset

(PECL)

session_pgsql_reset -- Reset connection to session database servers

Description

bool session_pgsql_reset ( void )

Reset the connection to the session database servers.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
session_pgsql_get_field | Up | session_pgsql_set_field


session_pgsql_set_field

(PECL)

session_pgsql_set_field -- Set custom field value

Description

bool session_pgsql_set_field ( string value )

Warning

This function is currently not documented; only the argument list is available.

Parameters

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

session_pgsql_get_field()

Prev | Home | Next
session_pgsql_reset | Up | session_pgsql_status


session_pgsql_status

(PECL)

session_pgsql_status -- Get current save handler status

Description

array session_pgsql_status ( void )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
session_pgsql_set_field | Up | Session Handling Functions


SimpleXMLElement->addAttribute()

(no version information, might be only in CVS)

SimpleXMLElement->addAttribute() -- Adds an attribute to the SimpleXML element

Description

class SimpleXMLElement {

void addAttribute ( string name, string value [, string namespace] )

}

Adds an attribute to the SimpleXML element.

Parameters

name

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

Return Values

No value is returned.

Examples

Example 1. Add attributes and children to a SimpleXML element

&#60;?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe-&#62;addAttribute('type', 'documentary');

$movie = $sxe-&#62;addChild('movie');
$movie-&#62;addChild('title', 'PHP2: More Parser Stories');
$movie-&#62;addChild('plot', 'This is all about the people who make it work.');

$characters = $movie-&#62;addChild('characters');
$character  = $characters-&#62;addChild('character');
$character-&#62;addChild('name', 'Mr. Parser');
$character-&#62;addChild('actor', 'John Doe');

$rating = $movie-&#62;addChild('rating', '5');
$rating-&#62;addAttribute('type', 'stars');

echo $sxe-&#62;asXML();

?&#62;

See Also

SimpleXMLElement->addChild()

Prev | Home | Next
SimpleXML functions | Up | SimpleXMLElement->addChild()


SimpleXMLElement->addChild()

(no version information, might be only in CVS)

SimpleXMLElement->addChild() -- Adds a child element to the XML node

Description

class SimpleXMLElement {

SimpleXMLElement addChild ( string name [, string value [, string namespace]] )

}

Adds a child element to the node and returns a SimpleXMLElement of the child.

Parameters

name

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

Return Values

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

Examples

Example 1. Add attributes and children to a SimpleXML element

&#60;?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe-&#62;addAttribute('type', 'documentary');

$movie = $sxe-&#62;addChild('movie');
$movie-&#62;addChild('title', 'PHP2: More Parser Stories');
$movie-&#62;addChild('plot', 'This is all about the people who make it work.');

$characters = $movie-&#62;addChild('characters');
$character  = $characters-&#62;addChild('character');
$character-&#62;addChild('name', 'Mr. Parser');
$character-&#62;addChild('actor', 'John Doe');

$rating = $movie-&#62;addChild('rating', '5');
$rating-&#62;addAttribute('type', 'stars');

echo $sxe-&#62;asXML();

?&#62;

See Also

SimpleXMLElement->addAttribute()

Prev | Home | Next
SimpleXMLElement->addAttribute() | Up | SimpleXMLElement->asXML()


SimpleXMLElement->__construct()

(no version information, might be only in CVS)

SimpleXMLElement->__construct() -- Creates a new SimpleXMLElement object

Description

class SimpleXMLElement {

__construct ( string data [, int options [, bool data_is_url [, string ns [, bool is_prefix]]]] )

}

Creates a new SimpleXMLElement object.

Parameters

data

A well-formed XML string or the path or URL to an XML document if data_is_url is TRUE.

options

Optionally used to specify additional Libxml parameters.

data_is_url

By default, data_is_url is FALSE. Use TRUE to specify that data is a path or URL to an XML document instead of string data.

ns

is_prefix

Return Values

Returns a SimpleXMLElement object representing data.

Errors/Exceptions

Produces an E_WARNING error message for each error found in the XML data and throws an exception if errors were detected.

Examples

Example 1. Create a SimpleXMLElement object

&#60;?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe-&#62;movie[0]-&#62;title;

?&#62;

Example 2. Create a SimpleXMLElement object from a URL

&#60;?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe-&#62;asXML();

?&#62;

See Also

simplexml_load_string
simplexml_load_file

Prev | Home | Next
SimpleXMLElement->children() | Up | SimpleXMLElement->getDocNamespaces()


SimpleXMLElement->getDocNamespaces()

(no version information, might be only in CVS)

SimpleXMLElement->getDocNamespaces() -- Returns namespaces declared in document

Description

class SimpleXMLElement {

array getDocNamespaces ( [bool recursive] )

}

Returns namespaces declared in document

Parameters

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

Return Values

The getDocNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example 1. Get document namespaces

&#60;?php

$xml = &#60;&#60;&#60;XML
&#60;?xml version="1.0" standalone="yes"?&#62;
&#60;people xmlns:p="http://example.org/ns"&#62;
    &#60;p:person id="1"&#62;John Doe&#60;/p:person&#62;
    &#60;p:person id="2"&#62;Susie Q. Public&#60;/p:person&#62;
&#60;/people&#62;
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe-&#62;getDocNamespaces();
var_dump($namespaces);

?&#62;

Example 2. Working with multiple namespaces

&#60;?php

$xml = &#60;&#60;&#60;XML
&#60;?xml version="1.0" standalone="yes"?&#62;
&#60;people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test"&#62;
    &#60;p:person t:id="1"&#62;John Doe&#60;/p:person&#62;
    &#60;p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr"&#62;
        Susie Q. Public
    &#60;/p:person&#62;
&#60;/people&#62;
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe-&#62;getDocNamespaces(TRUE);
var_dump($namespaces);

?&#62;

See Also

SimpleXMLElement->getNamespaces()
SimpleXMLElement->registerXPathNamespace()

Prev | Home | Next
SimpleXMLElement->__construct() | Up | SimpleXMLElement->getName()


SimpleXMLElement->getName()

(no version information, might be only in CVS)

SimpleXMLElement->getName() -- Gets the name of the XML element

Description

class SimpleXMLElement {

string getName ( void )

}

Gets the name of the XML element.

Return Values

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

Examples

Example 1. Get XML element names

&#60;?php

$sxe = new SimpleXMLElement($xmlstr);

echo $sxe-&#62;getName() . "\n";

foreach ($sxe-&#62;children() as $child)
{
    echo $child-&#62;getName() . "\n";
}

?&#62;

Prev | Home | Next
SimpleXMLElement->getDocNamespaces() | Up | SimpleXMLElement->getNamespaces()


SimpleXMLElement->getNamespaces()

(no version information, might be only in CVS)

SimpleXMLElement->getNamespaces() -- Returns namespaces used in document

Description

class SimpleXMLElement {

array getNamespaces ( [bool recursive] )

}

Returns namespaces used in document

Parameters

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Return Values

The getNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example 1. Get document namespaces in use

&#60;?php

$xml = &#60;&#60;&#60;XML
&#60;?xml version="1.0" standalone="yes"?&#62;
&#60;people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test"&#62;
    &#60;p:person id="1"&#62;John Doe&#60;/p:person&#62;
    &#60;p:person id="2"&#62;Susie Q. Public&#60;/p:person&#62;
&#60;/people&#62;
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe-&#62;getNamespaces(true);
var_dump($namespaces);

?&#62;

The above example will output:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

See Also

SimpleXMLElement->getDocNamespaces()
SimpleXMLElement->registerXPathNamespace()

Prev | Home | Next
SimpleXMLElement->getName() | Up | SimpleXMLElement->registerXPathNamespace()


SimpleXMLElement->registerXPathNamespace()

(no version information, might be only in CVS)

SimpleXMLElement->registerXPathNamespace() -- Creates a prefix/ns context for the next XPath query

Description

class SimpleXMLElement {

bool registerXPathNamespace ( string prefix, string ns )

}

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

Parameters

prefix

The namespace prefix to use in the XPath query for the namespace given in ns.

ns

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Setting a namespace prefix to use in an XPath query

&#60;?php

$xml = &#60;&#60;&#60;EOD
&#60;book xmlns:chap="http://example.org/chapter-title"&#62;
    &#60;title&#62;My Book&#60;/title&#62;
    &#60;chapter id="1"&#62;
        &#60;chap:title&#62;Chapter 1&#60;/chap:title&#62;
        &#60;para&#62;Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
            In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
            Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
            ultricies id, mauris.&#60;/para&#62;
    &#60;/chapter&#62;
    &#60;chapter id="2"&#62;
        &#60;chap:title&#62;Chapter 2&#60;/chap:title&#62;
        &#60;para&#62;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
            gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
            vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
            tellus, pharetra id, faucibus eu, dapibus dictum, odio.&#60;/para&#62;
    &#60;/chapter&#62;
&#60;/book&#62;
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe-&#62;registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe-&#62;xpath('//c:title');

foreach ($result as $title) {
  echo $title . "\n";
}

?&#62;

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

See Also

SimpleXMLElement->getDocNamespaces()
SimpleXMLElement->getNamespaces()

Prev | Home | Next
SimpleXMLElement->getNamespaces() | Up | SimpleXMLElement->xpath()


snmp_set_oid_output_format

(no version information, might be only in CVS)

snmp_set_oid_output_format -- Set the OID output format

Description

void snmp_set_oid_output_format ( int oid_format )

snmp_set_oid_output_format() sets the output format to be full or numeric.

Parameters

oid_format

Set it to SNMP_OID_OUTPUT_FULL if you want a full output, SNMP_OID_OUTPUT_NUMERIC otherwise.

Return Values

No value is returned.

Notes

Note: snmp_set_oid_output_format() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

Prev | Home | Next
snmp_set_oid_numeric_print | Up | snmp_set_quick_print


spl_autoload

(PHP 5 >= 5.1.0RC1)

spl_autoload -- Default implementation for __autoload()

Description

void spl_autoload ( string class_name [, string file_extensions] )

This function is intended to be used as a default implementation for __autoload(). If nothing else is specified and autoload_register() is called without any parameters then this functions will be used for any later call to __autoload(). By default it checks all include paths to contain failnames built up by the lowercase class name appended by the filename extensions .inc and .php.

Prev | Home | Next
spl_autoload_unregister | Up | spl_classes


spl_autoload_call

(PHP 5 >= 5.1.0RC1)

spl_autoload_call -- Try all registered __autoload() function to load the requested class

Description

void spl_autoload-call ( string class_name )

This function can be used to manually search for a class or interface using the registered __autoload functions.

Prev | Home | Next
iterator_to_array | Up | spl_autoload_extensions


spl_autoload_extensions

(PHP 5 >= 5.1.0RC1)

spl_autoload_extensions -- Register and return default file extensions for spl_autoload

Description

string spl_autoload_extensions ( [string file_extensions] )

This function allows to modify and check the file extensions the built in __autoload fallback function spl_autoload will be using. When calling without an argument it simply returns the current list of extensions each separated by comma. To modify the list of file extensions simply invoke the functions with the new list of file extensions to use in a single string with each extensions separated by comma.

Prev | Home | Next
spl_autoload_call | Up | spl_autoload_functions


spl_autoload_functions

(PHP 5 >= 5.1.0RC1)

spl_autoload_functions -- Return all registered __autoload() functions

Description

array spl_autoload_functions ( void )

This function returns an array of all registered __autoload functions. If the autoload stack is not activated then the return value is false. If no function is registered the return value will be an empty array.

Prev | Home | Next
spl_autoload_extensions | Up | spl_autoload_register


spl_autoload_register

(PHP 5 >= 5.1.0RC1)

spl_autoload_register -- Register given function as __autoload() implementation

Description

bool spl_autoload_register ( [mixed autoload_function] )

Register a function with the spl provided __autoload stack. If the stack is not yet activated it will be activated. If no parameter is provided the default implementation spl_autoload will be registered. When registering is successful the return value is true and upon failure false is being returned.

If your code has an existing __autoload function then this function must explicitly registered on the __autoload stack. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload function by either spl_autoload() or spl_autoload_call().

Prev | Home | Next
spl_autoload_functions | Up | spl_autoload_unregister


spl_autoload_unregister

(PHP 5 >= 5.1.0RC1)

spl_autoload_unregister -- Unregister given function as __autoload() implementation

Description

bool spl_autoload_unregister ( mixed autoload_function )

Unregister a function from the spl provided __autoload stack. If the stack is activated and empty after unregistering the given function then it will be deactivated. When unregistering is successful the return value is true and upon failure false is being returned.

When this function results in the autoload stack being activated an existing __autoload function will not be reactivated.

Prev | Home | Next
spl_autoload_register | Up | spl_autoload


spl_object_hash

(PHP 5 >= 5.2.0)

spl_object_hash -- Return hash id for given object

Description

string spl_object_hash ( object obj )

This function returns an unique identifier for the object. This id can be used as a hash key for storing objects or for identifying an object.

Parameters

class

Any object.

Return Values

Returns string that is unique for each object and is always the same for the same object.

Examples

Example 1. A spl_object_hash() example

&#60;?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?&#62;

Prev | Home | Next
spl_classes | Up | SQLite Functions


ssh2_publickey_add

(PECL)

ssh2_publickey_add -- Add an authorized publickey

Description

bool ssh2_publickey_add ( resource pkey, string algoname, string blob [, bool overwrite [, array attributes]] )

Note: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Parameters

pkey

Publickey Subsystem resource created by ssh2_publickey_init().

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

overwrite

If the specified key already exists, should it be overwritten?

attributes

Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, precede its name with an asterisk. If the server is unable to support an attribute marked mandatory, it will abort the add process.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Adding a publickey with ssh2_publickey_add()

&#60;?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($ssh2, 'ssh-rsa', $keyblob, false, array('comment'=&#62;"John's Key"));
?&#62;

See Also

ssh2_publickey_init()
ssh2_publickey_remove()
ssh2_publickey_list()

Prev | Home | Next
ssh2_methods_negotiated | Up | ssh2_publickey_init


ssh2_publickey_init

(PECL)

ssh2_publickey_init -- Initialize Publickey subsystem

Description

resource ssh2_publickey_init ( resource session )

Request the Publickey subsystem from an already connected SSH2 server.

The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return FALSE.

Note: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Return Values

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods.

See Also

ssh2_publickey_add()
ssh2_publickey_remove()
ssh2_publickey_list()

Prev | Home | Next
ssh2_publickey_add | Up | ssh2_publickey_list


ssh2_publickey_list

(PECL)

ssh2_publickey_list -- List currently authorized publickeys

Description

array ssh2_publickey_list ( resource pkey )

Note: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Parameters

pkey

Publickey Subsystem resource

Return Values

Returns a numerically indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.

Table 1. Publickey elements

Array Key | Meaning
name | Name of algorithm used by this publickey, for example: ssh-dss or ssh-rsa.
blob | Publickey blob as raw binary data.
attrs | Attributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string.

Examples

Example 1. Listing authorized keys with ssh2_publickey_list()

&#60;?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'secret');
$pkey = ssh2_publickey_init($ssh2);

$list = ssh2_publickey_list($pkey);

foreach($list as $key) {
  echo "Key: {$key['name']}\n";
  echo "Blob: " . chunk_split(base64_encode($key['blob']), 40, "\n") . "\n";
  echo "Comment: {$key['attrs']['comment']}\n\n";
}
?&#62;

The above example will output:

Key: ssh-rsa
Blob: AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5P
TrLRdjNONxXH1tVFGn0Bd26BF0aCP9qyJRlvdJ3j
4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xjza
Lpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VE
HYckxQ16CjSTibI5X69GmnYC9PNqEYq/1TP+HF10
Comment: John's Key

Key: ssh-rsa
Blob: AAAAB3NzaHVt6VqSGd5C1yc2EAAAABIwA232dnJA
AIEA5HVt6VqSGd5PTrLRdjNONxX/1TP+HF1HVt6V
qSGd50H1tVFGn0BB3NzaC1yc2EAd26BF0aCP9qyJ
RlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26HVt6Vq
SGd5sDHwfL351xjzaLpipu\BGB3NzaC1yc2EA/1T
Comment: Alice's Key

See Also

ssh2_publickey_init()
ssh2_publickey_add()
ssh2_publickey_remove()

Prev | Home | Next
ssh2_publickey_init | Up | ssh2_publickey_remove


ssh2_publickey_remove

(PECL)

ssh2_publickey_remove -- Remove an authorized publickey

Description

bool ssh2_publickey_remove ( resource pkey, string algoname, string blob )

Note: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Parameters

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

Return Values

Returns TRUE on success or FALSE on failure.

See Also

ssh2_publickey_init()
ssh2_publickey_add()
ssh2_publickey_list()

Prev | Home | Next
ssh2_publickey_list | Up | ssh2_scp_recv


stats_absolute_deviation

(PECL)

stats_absolute_deviation -- Returns the absolute deviation of an array of values

Description

float stats_absolute_deviation ( array a )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
Statistics Functions | Up | stats_cdf_beta


stats_cdf_beta

(PECL)

stats_cdf_beta -- CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

Description

float stats_cdf_beta ( float par1, float par2, float par3, int which )

Method Cumulative distribution function (P) is calculated directly by code associated with the following reference. DiDinato, A. R. and Morris, A. H. Algorithm 708: Significant Digit Computation of the Incomplete Beta Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373. Computation of other parameters involve a search for a value that produces the desired value of P. The search relies on the monotinicity of P with the other parameter. Note The beta density is proportional to t^(A-1) * (1-t)^(B-1) Arguments P -- The integral from 0 to X of the chi-square distribution. Input range: [0, 1]. Q -- 1-P. Input range: [0, 1]. P + Q = 1.0. X -- Upper limit of integration of beta density. Input range: [0,1]. Search range: [0,1] Y -- 1-X. Input range: [0,1]. Search range: [0,1] X + Y = 1.0. A -- The first parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] B -- The second parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1 BOUND -- Undefined if STATUS is 0 Bound exceeded by parameter number I if STATUS is negative. Lower search bound if STATUS is 1. Upper search bound if STATUS is 2.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Integer indicating which of the next four argument values is to be calculated from the others. Legal range: 1..4 iwhich = 1 : Calculate P and Q from X,Y,A and B iwhich = 2 : Calculate X and Y from P,Q,A and B iwhich = 3 : Calculate A from P,Q,X,Y and B iwhich = 4 : Calculate B from P,Q,X,Y and A

Return Values

STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1

Prev | Home | Next
stats_absolute_deviation | Up | stats_cdf_binomial


stats_cdf_binomial

(PECL)

stats_cdf_binomial -- Calculates any one parameter of the binomial distribution given values for the others.

Description

float stats_cdf_binomial ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_beta | Up | stats_cdf_cauchy


stats_cdf_cauchy

(PECL)

stats_cdf_cauchy -- Not documented

Description

float stats_cdf_cauchy ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_binomial | Up | stats_cdf_chisquare


stats_cdf_chisquare

(PECL)

stats_cdf_chisquare -- Calculates any one parameter of the chi-square distribution given values for the others.

Description

float stats_cdf_chisquare ( float par1, float par2, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_cauchy | Up | stats_cdf_exponential


stats_cdf_exponential

(PECL)

stats_cdf_exponential -- Not documented

Description

float stats_cdf_exponential ( float par1, float par2, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_chisquare | Up | stats_cdf_f


stats_cdf_f

(PECL)

stats_cdf_f -- Calculates any one parameter of the F distribution given values for the others.

Description

float stats_cdf_f ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_exponential | Up | stats_cdf_gamma


stats_cdf_gamma

(PECL)

stats_cdf_gamma -- Calculates any one parameter of the gamma distribution given values for the others.

Description

float stats_cdf_gamma ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_f | Up | stats_cdf_laplace


stats_cdf_laplace

(PECL)

stats_cdf_laplace -- Not documented

Description

float stats_cdf_laplace ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_gamma | Up | stats_cdf_logistic


stats_cdf_logistic

(PECL)

stats_cdf_logistic -- Not documented

Description

float stats_cdf_logistic ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_laplace | Up | stats_cdf_negative_binomial


stats_cdf_negative_binomial

(PECL)

stats_cdf_negative_binomial -- Calculates any one parameter of the negative binomial distribution given values for the others.

Description

float stats_cdf_negative_binomial ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_logistic | Up | stats_cdf_noncentral_chisquare


stats_cdf_noncentral_chisquare

(PECL)

stats_cdf_noncentral_chisquare -- Calculates any one parameter of the non-central chi-square distribution given values for the others.

Description

float stats_cdf_noncentral_chisquare ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_negative_binomial | Up | stats_cdf_noncentral_f


stats_cdf_noncentral_f

(PECL)

stats_cdf_noncentral_f -- Calculates any one parameter of the Non-central F distribution given values for the others.

Description

float stats_cdf_noncentral_f ( float par1, float par2, float par3, float par4, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

par4

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_noncentral_chisquare | Up | stats_cdf_poisson


stats_cdf_poisson

(PECL)

stats_cdf_poisson -- Calculates any one parameter of the Poisson distribution given values for the others.

Description

float stats_cdf_poisson ( float par1, float par2, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_noncentral_f | Up | stats_cdf_t


stats_cdf_t

(PECL)

stats_cdf_t -- Calculates any one parameter of the T distribution given values for the others.

Description

float stats_cdf_t ( float par1, float par2, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_poisson | Up | stats_cdf_uniform


stats_cdf_uniform

(PECL)

stats_cdf_uniform -- Not documented

Description

float stats_cdf_uniform ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_t | Up | stats_cdf_weibull


stats_cdf_weibull

(PECL)

stats_cdf_weibull -- Not documented

Description

float stats_cdf_weibull ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_uniform | Up | stats_covariance


stats_covariance

(PECL)

stats_covariance -- Computes the covariance of two data sets

Description

float stats_covariance ( array a, array b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

b

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_cdf_weibull | Up | stats_den_uniform


stats_den_uniform

(no version information, might be only in CVS)

stats_den_uniform -- Not documented

Description

float stats_den_uniform ( float x, float a, float b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

a

Its description

b

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_covariance | Up | stats_dens_beta


stats_dens_beta

(PECL)

stats_dens_beta -- Not documented

Description

float stats_dens_beta ( float x, float a, float b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

a

Its description

b

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_den_uniform | Up | stats_dens_cauchy


stats_dens_cauchy

(PECL)

stats_dens_cauchy -- Not documented

Description

float stats_dens_cauchy ( float x, float ave, float stdev )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

ave

Its description

stdev

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_beta | Up | stats_dens_chisquare


stats_dens_chisquare

(PECL)

stats_dens_chisquare -- Not documented

Description

float stats_dens_chisquare ( float x, float dfr )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

dfr

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_cauchy | Up | stats_dens_exponential


stats_dens_exponential

(PECL)

stats_dens_exponential -- Not documented

Description

float stats_dens_exponential ( float x, float scale )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

scale

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_chisquare | Up | stats_dens_f


stats_dens_f

(PECL)

stats_dens_f --

Description

float stats_dens_f ( float x, float dfr1, float dfr2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

dfr1

Its description

dfr2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_exponential | Up | stats_dens_gamma


stats_dens_gamma

(PECL)

stats_dens_gamma -- Not documented

Description

float stats_dens_gamma ( float x, float shape, float scale )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

shape

Its description

scale

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_f | Up | stats_dens_laplace


stats_dens_laplace

(PECL)

stats_dens_laplace -- Not documented

Description

float stats_dens_laplace ( float x, float ave, float stdev )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

ave

Its description

stdev

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_gamma | Up | stats_dens_logistic


stats_dens_logistic

(PECL)

stats_dens_logistic -- Not documented

Description

float stats_dens_logistic ( float x, float ave, float stdev )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

ave

Its description

stdev

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_laplace | Up | stats_dens_negative_binomial


stats_dens_negative_binomial

(no version information, might be only in CVS)

stats_dens_negative_binomial -- Not documented

Description

float stats_dens_negative_binomial ( float x, float n, float pi )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

n

Its description

pi

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_logistic | Up | stats_dens_normal


stats_dens_normal

(PECL)

stats_dens_normal -- Not documented

Description

float stats_dens_normal ( float x, float ave, float stdev )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

ave

Its description

stdev

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_negative_binomial | Up | stats_dens_pmf_binomial


stats_dens_pmf_binomial

(PECL)

stats_dens_pmf_binomial -- Not documented

Description

float stats_dens_pmf_binomial ( float x, float n, float pi )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

n

Its description

pi

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_normal | Up | stats_dens_pmf_hypergeometric


stats_dens_pmf_hypergeometric

(PECL)

stats_dens_pmf_hypergeometric --

Description

float stats_dens_pmf_hypergeometric ( float n1, float n2, float N1, float N2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

n1

Its description

n2

Its description

N1

Its description

N2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_pmf_binomial | Up | stats_dens_pmf_poisson


stats_dens_pmf_poisson

(PECL)

stats_dens_pmf_poisson -- Not documented

Description

float stats_dens_pmf_poisson ( float x, float lb )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

lb

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_pmf_hypergeometric | Up | stats_dens_t


stats_dens_t

(PECL)

stats_dens_t -- Not documented

Description

float stats_dens_t ( float x, float dfr )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

dfr

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_pmf_poisson | Up | stats_dens_weibull


stats_dens_weibull

(PECL)

stats_dens_weibull -- Not documented

Description

float stats_dens_weibull ( float x, float a, float b )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

a

Its description

b

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_t | Up | stats_harmonic_mean


stats_harmonic_mean

(PECL)

stats_harmonic_mean -- Returns the harmonic mean of an array of values

Description

number stats_harmonic_mean ( array a )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_dens_weibull | Up | stats_kurtosis


stats_kurtosis

(PECL)

stats_kurtosis -- Computes the kurtosis of the data in the array

Description

float stats_kurtosis ( array a )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_harmonic_mean | Up | stats_rand_gen_beta


stats_rand_gen_beta

(PECL)

stats_rand_gen_beta -- Generates beta random deviate

Description

float stats_rand_gen_beta ( float a, float b )

Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng.

Parameters

a

Its description

b

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_kurtosis | Up | stats_rand_gen_chisquare


stats_rand_gen_chisquare

(PECL)

stats_rand_gen_chisquare -- Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

Description

float stats_rand_gen_chisquare ( float df )

Warning

This function is currently not documented; only the argument list is available.

Parameters

df

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_beta | Up | stats_rand_gen_exponential


stats_rand_gen_exponential

(PECL)

stats_rand_gen_exponential -- Generates a single random deviate from an exponential distribution with mean "av"

Description

float stats_rand_gen_exponential ( float av )

Warning

This function is currently not documented; only the argument list is available.

Parameters

av

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_chisquare | Up | stats_rand_gen_f


stats_rand_gen_f

(PECL)

stats_rand_gen_f -- Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates

Description

float stats_rand_gen_f ( float dfn, float dfd )

Warning

This function is currently not documented; only the argument list is available.

Parameters

dfn

Its description

dfd

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_exponential | Up | stats_rand_gen_funiform


stats_rand_gen_funiform

(PECL)

stats_rand_gen_funiform -- Generates uniform float between low (exclusive) and high (exclusive)

Description

float stats_rand_gen_funiform ( float low, float high )

Warning

This function is currently not documented; only the argument list is available.

Parameters

low

Its description

high

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_f | Up | stats_rand_gen_gamma


stats_rand_gen_gamma

(PECL)

stats_rand_gen_gamma -- Generates random deviates from a gamma distribution

Description

float stats_rand_gen_gamma ( float a, float r )

Generates random deviates from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X).

Parameters

a

location parameter of Gamma distribution (a > 0).

r

shape parameter of Gamma distribution (r > 0).

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_funiform | Up | stats_rand_gen_ibinomial_negative


stats_rand_gen_ibinomial

(no version information, might be only in CVS)

stats_rand_gen_ibinomial -- Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE

Description

int stats_rand_gen_ibinomial ( int n, float pp )

Warning

This function is currently not documented; only the argument list is available.

Parameters

n

Its description

pp

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_ibinomial_negative | Up | stats_rand_gen_int


stats_rand_gen_ibinomial_negative

(no version information, might be only in CVS)

stats_rand_gen_ibinomial_negative -- Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).

Description

int stats_rand_gen_ibinomial_negative ( int n, float p )

Warning

This function is currently not documented; only the argument list is available.

Parameters

n

Its description

p

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_gamma | Up | stats_rand_gen_ibinomial


stats_rand_gen_int

(no version information, might be only in CVS)

stats_rand_gen_int -- Generates random integer between 1 and 2147483562

Description

int stats_rand_gen_int ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_ibinomial | Up | stats_rand_gen_ipoisson


stats_rand_gen_ipoisson

(PECL)

stats_rand_gen_ipoisson -- Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

Description

int stats_rand_gen_ipoisson ( float mu )

Warning

This function is currently not documented; only the argument list is available.

Parameters

mu

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_int | Up | stats_rand_gen_iuniform


stats_rand_gen_iuniform

(PECL)

stats_rand_gen_iuniform -- Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

Description

int stats_rand_gen_iuniform ( int low, int high )

Warning

This function is currently not documented; only the argument list is available.

Parameters

low

Its description

high

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_ipoisson | Up | stats_rand_gen_noncenral_chisquare


stats_rand_gen_noncenral_chisquare

(no version information, might be only in CVS)

stats_rand_gen_noncenral_chisquare -- Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0

Description

float stats_rand_gen_noncenral_chisquare ( float df, float xnonc )

Warning

This function is currently not documented; only the argument list is available.

Parameters

df

Its description

xnonc

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_iuniform | Up | stats_rand_gen_noncentral_f


stats_rand_gen_noncentral_f

(no version information, might be only in CVS)

stats_rand_gen_noncentral_f -- Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.

Description

float stats_rand_gen_noncentral_f ( float dfn, float dfd, float xnonc )

Warning

This function is currently not documented; only the argument list is available.

Parameters

dfn

Its description

dfd

Its description

xnonc

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_noncenral_chisquare | Up | stats_rand_gen_noncentral_t


stats_rand_gen_noncentral_t

(PECL)

stats_rand_gen_noncentral_t -- Generates a single random deviate from a noncentral T distribution

Description

float stats_rand_gen_noncentral_t ( float df, float xnonc )

Warning

This function is currently not documented; only the argument list is available.

Parameters

df

Its description

xnonc

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_noncentral_f | Up | stats_rand_gen_normal


stats_rand_gen_normal

(PECL)

stats_rand_gen_normal -- Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.

Description

float stats_rand_gen_normal ( float av, float sd )

Warning

This function is currently not documented; only the argument list is available.

Parameters

av

Its description

sd

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_noncentral_t | Up | stats_rand_gen_t


stats_rand_gen_t

(PECL)

stats_rand_gen_t -- Generates a single random deviate from a T distribution

Description

float stats_rand_gen_t ( float df )

Warning

This function is currently not documented; only the argument list is available.

Parameters

df

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_normal | Up | stats_rand_get_seeds


stats_rand_get_seeds

(no version information, might be only in CVS)

stats_rand_get_seeds -- Not documented

Description

array stats_rand_get_seeds ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_gen_t | Up | stats_rand_phrase_to_seeds


stats_rand_phrase_to_seeds

(PECL)

stats_rand_phrase_to_seeds -- generate two seeds for the RGN random number generator

Description

array stats_rand_phrase_to_seeds ( string phrase )

Warning

This function is currently not documented; only the argument list is available.

Parameters

phrase

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_get_seeds | Up | stats_rand_ranf


stats_rand_ranf

(PECL)

stats_rand_ranf -- Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator

Description

float stats_rand_ranf ( void )

Warning

This function is currently not documented; only the argument list is available.

Parameters

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_phrase_to_seeds | Up | stats_rand_setall


stats_rand_setall

(PECL)

stats_rand_setall -- Not documented

Description

void stats_rand_setall ( int iseed1, int iseed2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

iseed1

Its description

iseed2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_ranf | Up | stats_skew


stats_skew

(PECL)

stats_skew -- Computes the skewness of the data in the array

Description

float stats_skew ( array a )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_rand_setall | Up | stats_standard_deviation


stats_standard_deviation

(PECL)

stats_standard_deviation -- Returns the standard deviation

Description

float stats_standard_deviation ( array a [, bool sample] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

sample

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_skew | Up | stats_stat_binomial_coef


stats_stat_binomial_coef

(PECL)

stats_stat_binomial_coef -- Not documented

Description

float stats_stat_binomial_coef ( int x, int n )

Warning

This function is currently not documented; only the argument list is available.

Parameters

x

Its description

n

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_standard_deviation | Up | stats_stat_correlation


stats_stat_correlation

(PECL)

stats_stat_correlation -- Not documented

Description

float stats_stat_correlation ( array arr1, array arr2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

arr1

Its description

arr2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_binomial_coef | Up | stats_stat_gennch


stats_stat_gennch

(no version information, might be only in CVS)

stats_stat_gennch -- Not documented

Description

float stats_stat_gennch ( int n )

Warning

This function is currently not documented; only the argument list is available.

Parameters

n

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_correlation | Up | stats_stat_independent_t


stats_stat_independent_t

(PECL)

stats_stat_independent_t -- Not documented

Description

float stats_stat_independent_t ( array arr1, array arr2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

arr1

Its description

arr2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_gennch | Up | stats_stat_innerproduct


stats_stat_innerproduct

(PECL)

stats_stat_innerproduct --

Description

float stats_stat_innerproduct ( array arr1, array arr2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

arr1

Its description

arr2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_independent_t | Up | stats_stat_noncentral_t


stats_stat_noncentral_t

(no version information, might be only in CVS)

stats_stat_noncentral_t -- Calculates any one parameter of the noncentral t distribution give values for the others.

Description

float stats_stat_noncentral_t ( float par1, float par2, float par3, int which )

Warning

This function is currently not documented; only the argument list is available.

Parameters

par1

Its description

par2

Its description

par3

Its description

which

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_innerproduct | Up | stats_stat_paired_t


stats_stat_paired_t

(PECL)

stats_stat_paired_t -- Not documented

Description

float stats_stat_paired_t ( array arr1, array arr2 )

Warning

This function is currently not documented; only the argument list is available.

Parameters

arr1

Its description

arr2

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_noncentral_t | Up | stats_stat_percentile


stats_stat_percentile

(PECL)

stats_stat_percentile -- Not documented

Description

float stats_stat_percentile ( float df, float xnonc )

Warning

This function is currently not documented; only the argument list is available.

Parameters

df

Its description

xnonc

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_paired_t | Up | stats_stat_powersum


stats_stat_powersum

(PECL)

stats_stat_powersum -- Not documented

Description

float stats_stat_powersum ( array arr, float power )

Warning

This function is currently not documented; only the argument list is available.

Parameters

arr

Its description

power

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_percentile | Up | stats_variance


stats_variance

(PECL)

stats_variance -- Returns the population variance

Description

float stats_variance ( array a [, bool sample] )

Warning

This function is currently not documented; only the argument list is available.

Parameters

a

Its description

sample

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

Prev | Home | Next
stats_stat_powersum | Up | Stream Functions


str_getcsv

(no version information, might be only in CVS)

str_getcsv -- Parse a CSV string into an array

Description

array str_getcsv ( string input [, string delimiter [, string enclosure [, string escape]]] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
sscanf | Up | str_ireplace


stream_bucket_append

(PHP 5)

stream_bucket_append -- Append bucket to brigade

Description

void stream_bucket_append ( resource brigade, resource bucket )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
Stream Functions | Up | stream_bucket_make_writeable


stream_bucket_make_writeable

(PHP 5)

stream_bucket_make_writeable -- Return a bucket object from the brigade for operating on

Description

object stream_bucket_make_writeable ( resource brigade )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
stream_bucket_append | Up | stream_bucket_new


stream_bucket_new

(PHP 5)

stream_bucket_new -- Create a new bucket for use on the current stream

Description

object stream_bucket_new ( resource stream, string buffer )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
stream_bucket_make_writeable | Up | stream_bucket_prepend


stream_bucket_prepend

(PHP 5)

stream_bucket_prepend -- Prepend bucket to brigade

Description

void stream_bucket_prepend ( resource brigade, resource bucket )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
stream_bucket_new | Up | stream_context_create


stream_encoding

(no version information, might be only in CVS)

stream_encoding -- Set character set for stream encoding

Description

bool stream_encoding ( resource stream [, string encoding] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
stream_copy_to_stream | Up | stream_filter_append


stream_resolve_include_path

(no version information, might be only in CVS)

stream_resolve_include_path -- Determine what file will be opened by calls to fopen() with a relative path

Description

string stream_resolve_include_path ( string filename [, resource context] )

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
stream_register_wrapper | Up | stream_select


stream_socket_shutdown

(no version information, might be only in CVS)

stream_socket_shutdown -- Shutdown a full-duplex connection

Description

int stream_socket_shutdown ( resource stream, int how )

Shutdowns (partially or not) a full-duplex connection.

Parameters

stream

An open stream (opened with stream_socket_client(), for example)

how

One of the following constants: STREAM_SHUT_RD (disable further receptions), STREAM_SHUT_WR (disable further transmissions) or STREAM_SHUT_RDWR (disable further receptions and transmissions).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A stream_socket_shutdown() example

&#60;?php

$server = stream_socket_server('tcp://127.0.0.1:1337');
$client = stream_socket_client('tcp://127.0.0.1:1337');

var_dump(fputs($client, "hello"));

stream_socket_shutdown($client, STREAM_SHUT_WR);
var_dump(fputs($client, "hello")); // doesn't work now

?&#62;

The above example will output something similar to:

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

See Also

fclose()

Prev | Home | Next
stream_socket_server | Up | stream_wrapper_register


SWFAction->__construct()

(no version information, might be only in CVS)

SWFAction->__construct() -- Creates a new SWFAction

Description

class SWFAction {

SWFAction __construct ( string script )

}

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.

Creates a new SWFAction and compiles the given script in it.

Parameters

script

An ActionScript snippet to associate with the SWFAction. See SWFAction for more details.

Prev | Home | Next
SWFAction | Up | SWFBitmap


SWFBitmap->__construct()

(no version information, might be only in CVS)

SWFBitmap->__construct() -- Loads Bitmap object

Description

class SWFBitmap {

SWFBitmap __construct ( mixed file [, mixed alphafile] )

}

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.

Creates the new SWFBitmap object from the given file.

Parameters

For both parameters you can provide a file pointer returned by fopen() or the image data, as a binary string.

file

Note: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

alphafile

An MSK file to be used as an alpha mask for a JPEG image.

Examples

Example 1. Importing a DBL file

&#60;?php
$s = new SWFShape();
$f = $s-&#62;addFill(new SWFBitmap(file_get_contents("image.dbl")));
$s-&#62;setRightFill($f);

$s-&#62;drawLine(32, 0);
$s-&#62;drawLine(0, 32);
$s-&#62;drawLine(-32, 0);
$s-&#62;drawLine(0, -32);

$m = new SWFMovie();
$m-&#62;setDimension(32, 32);
$m-&#62;add($s);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Example 2. Using an alpha mask

&#60;?php

$s = new SWFShape();

// .msk file generated with "gif2mask" utility
$f = $s-&#62;addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
$s-&#62;setRightFill($f);

$s-&#62;drawLine(640, 0);
$s-&#62;drawLine(0, 480);
$s-&#62;drawLine(-640, 0);
$s-&#62;drawLine(0, -480);

$c = new SWFShape();
$c-&#62;setRightFill($c-&#62;addFill(0x99, 0x99, 0x99));
$c-&#62;drawLine(40, 0);
$c-&#62;drawLine(0, 40);
$c-&#62;drawLine(-40, 0);
$c-&#62;drawLine(0, -40);

$m = new SWFMovie();
$m-&#62;setDimension(640, 480);
$m-&#62;setBackground(0xcc, 0xcc, 0xcc);

// draw checkerboard background
for ($y=0; $y&#60;480; $y+=40) {
  for ($x=0; $x&#60;640; $x+=80) {
    $i = $m-&#62;add($c);
    $i-&#62;moveTo($x, $y);
  }

  $y+=40;

  for ($x=40; $x&#60;640; $x+=80) {
    $i = $m-&#62;add($c);
    $i-&#62;moveTo($x, $y);
  }
}

$m-&#62;add($s);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFBitmap | Up | SWFBitmap->getHeight()


SWFButton->addASound()

(no version information, might be only in CVS)

SWFButton->addASound() -- Associates a sound with a button transition

Description

class SWFButton {

SWFSoundInstance addASound ( SWFSound sound, int flags )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFButton->addAction() | Up | SWFButton->addShape()


SWFButton->__construct()

(no version information, might be only in CVS)

SWFButton->__construct() -- Creates a new Button

Description

class SWFButton {

SWFButton __construct ( void )

}

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.

Creates a new Button.

Examples

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Example 1. Usual interactions with buttons

&#60;?php

$f = new SWFFont("_serif");

$p = new SWFSprite();

function label($string)
{
  global $f;

  $t = new SWFTextField();
  $t-&#62;setFont($f);
  $t-&#62;addString($string);
  $t-&#62;setHeight(200);
  $t-&#62;setBounds(3200, 200);
  return $t;
}

function addLabel($string)
{
  global $p;

  $i = $p-&#62;add(label($string));
  $p-&#62;nextFrame();
  $p-&#62;remove($i);
}

$p-&#62;add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");

function rect($r, $g, $b)
{
  $s = new SWFShape();
  $s-&#62;setRightFill($s-&#62;addFill($r, $g, $b));
  $s-&#62;drawLine(600, 0);
  $s-&#62;drawLine(0, 600);
  $s-&#62;drawLine(-600, 0);
  $s-&#62;drawLine(0, -600);

  return $s;
}

$b = new SWFButton();
$b-&#62;addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b-&#62;addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b-&#62;addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
          SWFBUTTON_MOUSEUP);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
      SWFBUTTON_MOUSEDOWN);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
      SWFBUTTON_MOUSEOVER);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
      SWFBUTTON_MOUSEOUT);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
      SWFBUTTON_MOUSEUPOUTSIDE);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
      SWFBUTTON_DRAGOVER);

$b-&#62;addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
      SWFBUTTON_DRAGOUT);

$m = new SWFMovie();
$m-&#62;setDimension(4000, 3000);

$i = $m-&#62;add($p);
$i-&#62;setName("label");
$i-&#62;moveTo(400, 1900);

$i = $m-&#62;add($b);
$i-&#62;moveTo(400, 900);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Example 2. Drag example

&#60;?php

$s = new SWFShape();
$s-&#62;setRightFill($s-&#62;addFill(0xff, 0, 0));
$s-&#62;drawLine(1000,0);
$s-&#62;drawLine(0,1000);
$s-&#62;drawLine(-1000,0);
$s-&#62;drawLine(0,-1000);

$b = new SWFButton();
$b-&#62;addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

$b-&#62;addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
      SWFBUTTON_MOUSEDOWN);

$b-&#62;addAction(new SWFAction("stopDrag();"),
      SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

$p = new SWFSprite();
$p-&#62;add($b);
$p-&#62;nextFrame();

$m = new SWFMovie();
$i = $m-&#62;add($p);
$i-&#62;setName('test');
$i-&#62;moveTo(1000,1000);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFButton | Up | SWFButton->addAction()


SWFButton->setMenu()

(no version information, might be only in CVS)

SWFButton->setMenu() -- enable track as menu button behaviour

Description

class SWFButton {

void setMenu ( int flag )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

flag

This parameter can be used for a slight different behavior of buttons. You can set it to 0 (off) or 1 (on).

Return Values

No value is returned.

Prev | Home | Next
SWFButton->setHit() | Up | SWFButton->setOver()


SWFDisplayItem->addAction()

(no version information, might be only in CVS)

SWFDisplayItem->addAction() -- Adds this SWFAction to the given SWFSprite instance

Description

class SWFDisplayItem {

void addAction ( SWFAction action, int flags )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

action

An SWFAction, returned by SWFAction->__construct().

flags

Return Values

No value is returned.

See Also

SWFAction

Prev | Home | Next
SWFDisplayItem | Up | SWFDisplayItem->addColor()


SWFDisplayItem->endMask()

(no version information, might be only in CVS)

SWFDisplayItem->endMask() -- Another way of defining a MASK layer

Description

class SWFDisplayItem {

void endMask ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->addColor() | Up | SWFDisplayItem->getRot()


SWFDisplayItem->getRot()

(no version information, might be only in CVS)

SWFDisplayItem->getRot() --

Description

class SWFDisplayItem {

float getRot ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFDisplayItem->endMask() | Up | SWFDisplayItem->getX()


SWFDisplayItem->getX()

(no version information, might be only in CVS)

SWFDisplayItem->getX() --

Description

class SWFDisplayItem {

float getX ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getY()

Prev | Home | Next
SWFDisplayItem->getRot() | Up | SWFDisplayItem->getXScale()


SWFDisplayItem->getXScale()

(no version information, might be only in CVS)

SWFDisplayItem->getXScale() --

Description

class SWFDisplayItem {

float getXScale ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getYScale()

Prev | Home | Next
SWFDisplayItem->getX() | Up | SWFDisplayItem->getXSkew()


SWFDisplayItem->getXSkew()

(no version information, might be only in CVS)

SWFDisplayItem->getXSkew() --

Description

class SWFDisplayItem {

float getXSkew ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getYSkew()

Prev | Home | Next
SWFDisplayItem->getXScale() | Up | SWFDisplayItem->getY()


SWFDisplayItem->getY()

(no version information, might be only in CVS)

SWFDisplayItem->getY() --

Description

class SWFDisplayItem {

float getY ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getX()

Prev | Home | Next
SWFDisplayItem->getXSkew() | Up | SWFDisplayItem->getYScale()


SWFDisplayItem->getYScale()

(no version information, might be only in CVS)

SWFDisplayItem->getYScale() --

Description

class SWFDisplayItem {

float getYScale ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getXScale()

Prev | Home | Next
SWFDisplayItem->getY() | Up | SWFDisplayItem->getYSkew()


SWFDisplayItem->getYSkew()

(no version information, might be only in CVS)

SWFDisplayItem->getYSkew() --

Description

class SWFDisplayItem {

float getYSkew ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFDisplayItem->getXSkew()

Prev | Home | Next
SWFDisplayItem->getYScale() | Up | SWFDisplayItem->move()


SWFDisplayItem->setMaskLevel()

(no version information, might be only in CVS)

SWFDisplayItem->setMaskLevel() -- Defines a MASK layer at level

Description

class SWFDisplayItem {

void setMaskLevel ( int level )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->setDepth() | Up | SWFDisplayItem->setMatrix()


SWFDisplayItem->setMatrix()

(no version information, might be only in CVS)

SWFDisplayItem->setMatrix() -- Sets the item's transform matrix

Description

class SWFDisplayItem {

void setMatrix ( float a, float b, float c, float d, float x, float y )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFDisplayItem->setMaskLevel() | Up | SWFDisplayItem->setName()


SWFFont->__construct()

(no version information, might be only in CVS)

SWFFont->__construct() -- Loads a font definition

Description

class SWFFont {

SWFFont __construct ( string filename )

}

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.

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:

&#60;?php
$f = newSWFFont("_sans");
?&#62;
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

Prev | Home | Next
SWFFont | Up | SWFFont->getAscent()


SWFFont->getAscent()

(no version information, might be only in CVS)

SWFFont->getAscent() -- Returns the ascent of the font, or 0 if not available

Description

class SWFFont {

float getAscent ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFFont->getDescent()

Prev | Home | Next
SWFFont->__construct() | Up | SWFFont->getDescent()


SWFFont->getDescent()

(no version information, might be only in CVS)

SWFFont->getDescent() -- Returns the descent of the font, or 0 if not available

Description

class SWFFont {

float getDescent ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFFont->getAscent()

Prev | Home | Next
SWFFont->getAscent() | Up | SWFFont->getLeading()


SWFFont->getLeading()

(no version information, might be only in CVS)

SWFFont->getLeading() -- Returns the leading of the font, or 0 if not available

Description

class SWFFont {

float getLeading ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFFont->getDescent() | Up | SWFFont->getShape()


SWFFont->getShape()

(no version information, might be only in CVS)

SWFFont->getShape() -- Returns the glyph shape of a char as a text string

Description

class SWFFont {

string getShape ( int code )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFFont->getLeading() | Up | SWFFont->getUTF8Width()


SWFFont->getUTF8Width()

(no version information, might be only in CVS)

SWFFont->getUTF8Width() -- Calculates the width of the given string in this font at full height

Description

class SWFFont {

float getUTF8Width ( string string )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFFont->getWidth()

Prev | Home | Next
SWFFont->getShape() | Up | SWFFont->getWidth()


SWFFontChar->addChars()

(no version information, might be only in CVS)

SWFFontChar->addChars() -- Adds characters to a font for exporting font

Description

class SWFFontChar {

void addChars ( string char )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFFontChar->addUTF8Chars()

Prev | Home | Next
SWFFontChar | Up | SWFFontChar->addUTF8Chars()


SWFFontChar->addUTF8Chars()

(no version information, might be only in CVS)

SWFFontChar->addUTF8Chars() -- Adds characters to a font for exporting font

Description

class SWFFontChar {

void addUTF8Chars ( string char )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFFontChar->addChars()

Prev | Home | Next
SWFFontChar->addChars() | Up | SWFGradient


SWFGradient->__construct()

(no version information, might be only in CVS)

SWFGradient->__construct() -- Creates a gradient object

Description

class SWFGradient {

SWFGradient __construct ( void )

}

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.

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.

SWFGradient has the following methods : swfgradient->addentry().

This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.

Example 1. swfgradient() example

&#60;?php

  $m = new SWFMovie();
  $m-&#62;setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g-&#62;addEntry(0.0, 0, 0, 0);
  $g-&#62;addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s-&#62;addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f-&#62;scaleTo(0.01);
  $f-&#62;moveTo(160, 120);
  $s-&#62;setRightFill($f);
  $s-&#62;drawLine(320, 0);
  $s-&#62;drawLine(0, 240);
  $s-&#62;drawLine(-320, 0);
  $s-&#62;drawLine(0, -240);

  $m-&#62;add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g-&#62;addEntry(0.0, 0xff, 0, 0, 0xff);
  $g-&#62;addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s-&#62;addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f-&#62;scaleTo(0.005);
  $f-&#62;moveTo(160, 120);
  $s-&#62;setRightFill($f);
  $s-&#62;drawLine(320, 0);
  $s-&#62;drawLine(0, 240);
  $s-&#62;drawLine(-320, 0);
  $s-&#62;drawLine(0, -240);

  $m-&#62;add($s);

  header('Content-type: application/x-shockwave-flash');
  $m-&#62;output();
?&#62;

Prev | Home | Next
SWFGradient | Up | SWFGradient->addEntry()


SWFMorph->__construct()

(no version information, might be only in CVS)

SWFMorph->__construct() -- Creates a new SWFMorph object

Description

class SWFMorph {

SWFMorph __construct ( void )

}

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.

Creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

Examples

This simple example will morph a big red square into a smaller blue black-bordered square.

Example 1. swfmorph() example

&#60;?php
  $p = new SWFMorph();

  $s = $p-&#62;getShape1();
  $s-&#62;setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s-&#62;setLeftFill($s-&#62;addFill(0xff, 0, 0));
  $s-&#62;movePenTo(-1000,-1000);
  $s-&#62;drawLine(2000,0);
  $s-&#62;drawLine(0,2000);
  $s-&#62;drawLine(-2000,0);
  $s-&#62;drawLine(0,-2000);

  $s = $p-&#62;getShape2();
  $s-&#62;setLine(60,0,0,0);
  $s-&#62;setLeftFill($s-&#62;addFill(0, 0, 0xff));
  $s-&#62;movePenTo(0,-1000);
  $s-&#62;drawLine(1000,1000);
  $s-&#62;drawLine(-1000,1000);
  $s-&#62;drawLine(-1000,-1000);
  $s-&#62;drawLine(1000,-1000);

  $m = new SWFMovie();
  $m-&#62;setDimension(3000,2000);
  $m-&#62;setBackground(0xff, 0xff, 0xff);

  $i = $m-&#62;add($p);
  $i-&#62;moveTo(1500,1000);

  for ($r=0.0; $r&#60;=1.0; $r+=0.1) {
    $i-&#62;setRatio($r);
    $m-&#62;nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m-&#62;output();
?&#62;

Prev | Home | Next
SWFMorph | Up | SWFMorph->getShape1()


SWFMovie->addExport()

(no version information, might be only in CVS)

SWFMovie->addExport() --

Description

class SWFMovie {

void addExport ( SWFCharacter char, string name )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->add() | Up | SWFMovie->addFont()


SWFMovie->addFont()

(no version information, might be only in CVS)

SWFMovie->addFont() --

Description

class SWFFontChar {

mixed addFont ( SWFFont font )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->addExport() | Up | SWFMovie->importChar()


SWFMovie->__construct()

(no version information, might be only in CVS)

SWFMovie->__construct() -- Creates a new movie object, representing an SWF version 4 movie

Description

class SWFMovie {

SWFMovie __construct ( int version )

}

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.

Creates a new movie object, representing an SWF movie.

Parameters

version

The desired SWF version. Default is 4.

Prev | Home | Next
SWFMovie | Up | SWFMovie->add()


SWFMovie->importChar()

(no version information, might be only in CVS)

SWFMovie->importChar() --

Description

class SWFMovie {

SWFSprite importChar ( string libswf, string name )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFMovie->importFont()

Prev | Home | Next
SWFMovie->addFont() | Up | SWFMovie->importFont()


SWFMovie->importFont()

(no version information, might be only in CVS)

SWFMovie->importFont() --

Description

class SWFMovie {

SWFFontChar importFont ( string libswf, string name )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFMovie->importChar()

Prev | Home | Next
SWFMovie->importChar() | Up | SWFMovie->labelFrame()


SWFMovie->labelFrame()

(no version information, might be only in CVS)

SWFMovie->labelFrame() -- Labels a frame

Description

class SWFMovie {

void labelFrame ( string label )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->importFont() | Up | SWFMovie->nextFrame()


SWFMovie->saveToFile()

(no version information, might be only in CVS)

SWFMovie->saveToFile() --

Description

class SWFMovie {

int saveToFile ( stream x [, int compression] )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

X

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

SWFMovie->output()
SWFMovie->save()

Prev | Home | Next
SWFMovie->save() | Up | SWFMovie->setbackground()


SWFMovie->startSound()

(no version information, might be only in CVS)

SWFMovie->startSound() --

Description

class SWFMovie {

SWFSoundInstance startSound ( SWFSound sound )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFMovie->stopSound()

Prev | Home | Next
SWFMovie->setRate() | Up | SWFMovie->stopSound()


SWFMovie->stopSound()

(no version information, might be only in CVS)

SWFMovie->stopSound() --

Description

class SWFMovie {

void stopSound ( SWFSound sound )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFMovie->startSound()

Prev | Home | Next
SWFMovie->startSound() | Up | SWFMovie->streamMP3()


SWFMovie->writeExports()

(no version information, might be only in CVS)

SWFMovie->writeExports() --

Description

class SWFMovie {

void writeExports ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFMovie->streamMP3() | Up | SWFPrebuiltClip


SWFPrebuiltClip->__construct()

(no version information, might be only in CVS)

SWFPrebuiltClip->__construct() -- Returns a SWFPrebuiltClip object

Description

class SWFPrebuiltClip {

SWFPrebuiltClip __construct ( [string file] )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFPrebuiltClip | Up | SWFShape


SWFShape->__construct()

(no version information, might be only in CVS)

SWFShape->__construct() -- Creates a new shape object

Description

class SWFShape {

SWFShape __construct ( void )

}

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.

Created a new SWFShape object.

Examples

This simple example will draw a big red elliptic quadrant.

Example 1. swfshape() example

&#60;?php
$s = new SWFShape();
$s-&#62;setLine(40, 0x7f, 0, 0);
$s-&#62;setRightFill($s-&#62;addFill(0xff, 0, 0));
$s-&#62;movePenTo(200, 200);
$s-&#62;drawLineTo(6200, 200);
$s-&#62;drawLineTo(6200, 4600);
$s-&#62;drawCurveTo(200, 4600, 200, 200);

$m = new SWFMovie();
$m-&#62;setDimension(6400, 4800);
$m-&#62;setRate(12.0);
$m-&#62;add($s);
$m-&#62;nextFrame();

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFShape | Up | SWFShape->addFill()


SWFShape->drawArc()

(no version information, might be only in CVS)

SWFShape->drawArc() -- Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

Description

class SWFShape {

void drawArc ( float r, float startAngle, float endAngle )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFShape->drawCircle()

Prev | Home | Next
SWFShape->addFill() | Up | SWFShape->drawCircle()


SWFShape->drawCircle()

(no version information, might be only in CVS)

SWFShape->drawCircle() -- Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Description

class SWFShape {

void drawCircle ( float r )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFShape->drawArc() | Up | SWFShape->drawCubic()


SWFShape->drawCubic()

(no version information, might be only in CVS)

SWFShape->drawCubic() -- Draws a cubic bezier curve using the current position and the three given points as control points

Description

class SWFShape {

int drawCubic ( float bx, float by, float cx, float cy, float dx, float dy )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFShape->drawCubicTo()

Prev | Home | Next
SWFShape->drawCircle() | Up | SWFShape->drawCubicTo()


SWFShape->drawCubicTo()

(no version information, might be only in CVS)

SWFShape->drawCubicTo() -- Draws a cubic bezier curve using the current position and the three given points as control points

Description

class SWFShape {

int drawCubicTo ( float bx, float by, float cx, float cy, float dx, float dy )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFShape->drawCubic()

Prev | Home | Next
SWFShape->drawCubic() | Up | SWFShape->drawCurve()


SWFShape->drawGlyph()

(no version information, might be only in CVS)

SWFShape->drawGlyph() -- Draws the first character in the given string into the shape using the glyph definition from the given font

Description

class SWFShape {

void drawGlyph ( SWFFont font, string character [, int size] )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFShape->drawCurveTo() | Up | SWFShape->drawLine()


SWFSound

(no version information, might be only in CVS)

SWFSound -- Returns a new SWFSound object from given file

Description

class SWFSound {

SWFSound __construct ( string filename, int flags )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFSound | Up | SWFSoundInstance


SWFSoundInstance->loopCount()

(no version information, might be only in CVS)

SWFSoundInstance->loopCount() --

Description

class SWFSoundInstance {

void loopCount ( int point )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

SWFSoundInstance->loopOutPoint()

Prev | Home | Next
SWFSoundInstance | Up | SWFSoundInstance->loopInPoint()


SWFSoundInstance->loopInPoint()

(no version information, might be only in CVS)

SWFSoundInstance->loopInPoint() --

Description

class SWFSoundInstance {

void loopInPoint ( int point )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

SWFSoundInstance->loopOutPoint()

Prev | Home | Next
SWFSoundInstance->loopCount() | Up | SWFSoundInstance->loopOutPoint()


SWFSoundInstance->loopOutPoint()

(no version information, might be only in CVS)

SWFSoundInstance->loopOutPoint() --

Description

class SWFSoundInstance {

void loopOutPoint ( int point )

}

Warning

This function is currently not documented; only the argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

SWFSoundInstance->loopInPoint()

Prev | Home | Next
SWFSoundInstance->loopInPoint() | Up | SWFSoundInstance->noMultiple()


SWFSoundInstance->noMultiple()

(no version information, might be only in CVS)

SWFSoundInstance->noMultiple() --

Description

class SWFSoundInstance {

void noMultiple ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFSoundInstance->loopOutPoint() | Up | SWFSprite


SWFSprite->__construct()

(no version information, might be only in CVS)

SWFSprite->__construct() -- Creates a movie clip (a sprite)

Description

class SWFSprite {

SWFSprite __construct ( void )

}

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.

Creates a new SWFSprite object.

Prev | Home | Next
SWFSprite | Up | SWFSprite->add()


SWFSprite->labelFrame()

(no version information, might be only in CVS)

SWFSprite->labelFrame() -- Labels frame

Description

class SWFSprite {

void labelFrame ( string label )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFSprite->add() | Up | SWFSprite->nextFrame()


SWFSprite->startSound()

(no version information, might be only in CVS)

SWFSprite->startSound() --

Description

class SWFSprite {

SWFSoundInstance startSound ( SWFSound sount )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFSprite->stopSound()

Prev | Home | Next
SWFSprite->setFrames() | Up | SWFSprite->stopSound()


SWFSprite->stopSound()

(no version information, might be only in CVS)

SWFSprite->stopSound() --

Description

class SWFSprite {

void stopSound ( SWFSound sount )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFSprite->startSound()

Prev | Home | Next
SWFSprite->startSound() | Up | SWFText


SWFText->addUTF8String()

(no version information, might be only in CVS)

SWFText->addUTF8String() -- Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

Description

class SWFText {

void addUTF8String ( string text )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFText->addString()

Prev | Home | Next
SWFText->addString() | Up | SWFText->getAscent()


SWFText->__construct()

(no version information, might be only in CVS)

SWFText->__construct() -- Creates a new SWFText object

Description

class SWFText {

void __construct ( void )

}

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.

Creates a new SWFText object, fresh for manipulating.

Examples

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Example 1. swftext() example

&#60;?php
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t-&#62;setFont($f);
$t-&#62;moveTo(200, 2400);
$t-&#62;setColor(0xff, 0xff, 0);
$t-&#62;setHeight(1200);
$t-&#62;addString("PHP generates Flash with Ming!!");

$m = new SWFMovie();
$m-&#62;setDimension(5400, 3600);

$m-&#62;add($t);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFText | Up | SWFText->addString()


SWFText->getAscent()

(no version information, might be only in CVS)

SWFText->getAscent() -- Returns the ascent of the current font at its current size, or 0 if not available

Description

class SWFText {

float getAscent ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFText->getDescent()

Prev | Home | Next
SWFText->addUTF8String() | Up | SWFText->getDescent()


SWFText->getDescent()

(no version information, might be only in CVS)

SWFText->getDescent() -- Returns the descent of the current font at its current size, or 0 if not available

Description

class SWFText {

float getDescent ( void )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFText->getAscent()

Prev | Home | Next
SWFText->getAscent() | Up | SWFText->getLeading()


SWFText->getLeading()

(no version information, might be only in CVS)

SWFText->getLeading() -- Returns the leading of the current font at its current size, or 0 if not available

Description

class SWFText {

float getLeading ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFText->getDescent() | Up | SWFText->getUTF8Width()


SWFText->getUTF8Width()

(no version information, might be only in CVS)

SWFText->getUTF8Width() -- calculates the width of the given string in this text objects current font and size

Description

class SWFText {

float getUTF8Width ( string string )

}

Warning

This function is currently not documented; only the argument list is available.

See Also

SWFText->getWidth()

Prev | Home | Next
SWFText->getLeading() | Up | SWFText->getWidth()


SWFTextField->addChars()

(no version information, might be only in CVS)

SWFTextField->addChars() -- adds characters to a font that will be available within a textfield

Description

class SWFTextField {

void addChars ( string chars )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

See Also

SWFTextField->addString()

Prev | Home | Next
SWFTextField->__construct() | Up | SWFTextField->addString()


SWFTextField->__construct()

(no version information, might be only in CVS)

SWFTextField->__construct() -- Creates a text field object

Description

class SWFTextField {

SWFTextField __construct ( [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.

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield

  • SWFTEXTFIELD_HASLENGTH

  • SWFTEXTFIELD_HTML allows text markup using HTML-tags

  • SWFTEXTFIELD_MULTILINE allows multiple lines

  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable

  • SWFTEXTFIELD_NOSELECT makes the field non-selectable

  • SWFTEXTFIELD_PASSWORD obscures the data entry

  • SWFTEXTFIELD_WORDWRAP allows text to wrap

Flags are combined with the bitwise OR operation. For example,
&#60;?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?&#62;
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield->setfont(),
swftextfield->setbounds(), swftextfield->align(),
swftextfield->setheight(), swftextfield->setleftmargin(),
swftextfield->setrightmargin(), swftextfield->setmargins(),
swftextfield->setindentation(), swftextfield->setlinespacing(),
swftextfield->setcolor(), swftextfield->setname() and
swftextfield->addstring().

Prev | Home | Next
SWFTextField | Up | SWFTextField->addChars()


SWFTextField->setPadding()

(no version information, might be only in CVS)

SWFTextField->setPadding() -- Sets the padding of this textfield

Description

class SWFTextField {

void setPadding ( float padding )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFTextField->setName() | Up | SWFTextField->setRightMargin()


SWFVideoStream->__construct()

(no version information, might be only in CVS)

SWFVideoStream->__construct() -- Returns a SWFVideoStream object

Description

class SWFVideoStream {

SWFVideoStream __construct ( [string file] )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFVideoStream | Up | SWFVideoStream->getNumFrames()


SWFVideoStream->getNumFrames()

(no version information, might be only in CVS)

SWFVideoStream->getNumFrames() --

Description

class SWFVideoStream {

int getNumFrames ( void )

}

Warning

This function is currently not documented; only the argument list is available.

Prev | Home | Next
SWFVideoStream->__construct() | Up | SWFVideoStream->setDimension()


SWFVideoStream->setDimension()

(no version information, might be only in CVS)

SWFVideoStream->setDimension() --

Description

class SWFVideoStream {

void setDimension ( int x, int y )

}

Warning

This function is currently not documented; only the argument list is available.

Return Values

No value is returned.

Prev | Home | Next
SWFVideoStream->getNumFrames() | Up | ming_keypress


Swish::__construct

(no version information, might be only in CVS)

Swish::__construct -- Construct a Swish object

Description

void Swish::__construct ( string string index_names )

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

index_names

The list of index files separated by spaces.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. A Swish::__construct() example

&#60;?php

try {
    $swish = new Swish("index1 index2");
} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

foreach ($swish-&#62;indexes as $index) {
    var_dump($index["name"]);
    var_dump($index["headers"]["Total Words"]);
}

?&#62;

The above example will output something similar to:

string(6) "index1"
int(1888)
string(6) "index2"
int(2429)

Prev | Home | Next
Swish-e bindings | Up | Swish->getMetaList


Swish->getMetaList

(no version information, might be only in CVS)

Swish->getMetaList -- Get the list of meta entries for the index

Description

array Swish->getMetaList ( string index_name )

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

index_name

The name of the index file.

Return Values

Returns an array of meta entries for the given index.

Examples

Example 1. Basic Swish->getMetaList() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    var_dump($swish-&#62;getMetaList("index.swish-e"));

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

array(1) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(12) "swishdefault"
    ["Type"]=>
    int(0)
    ["ID"]=>
    int(1)
  }
}

Prev | Home | Next
Swish::__construct | Up | Swish->getPropertyList


Swish->getPropertyList

(no version information, might be only in CVS)

Swish->getPropertyList -- Get the list of properties for the index

Description

array Swish->getPropertyList ( string index_name )

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

index_name

The name of the index file.

Return Values

Returns an array of properties for the given index.

Examples

Example 1. Basic Swish->getPropertyList() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $properties = $swish-&#62;getPropertyList("index.swish-e");
    foreach ($properties as $prop) {
        echo $prop["Name"],"\n";
    }

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

swishreccount
swishrank
swishfilenum
swishdbfile
swishdocpath
swishtitle
swishdocsize
swishlastmodified

Prev | Home | Next
Swish->getMetaList | Up | Swish->prepare


Swish->prepare

(no version information, might be only in CVS)

Swish->prepare -- Prepare a search query

Description

object Swish->prepare ( [string query] )

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.

Prepare and return a search object, which you can later use for unlimited number of queries.

Parameters

query

Optional query string. The query can be also set using SwishSearch->execute() method.

Return Values

Returns SwishSearch object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic Swish->prepare() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare("search query");
    $results = $search-&#62;execute();
    echo "Found: ", $results-&#62;hits, " hits\n";

    $results = $search-&#62;execute("new search");

    echo "Found: ", $results-&#62;hits, " hits\n";
} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

Found: 2 hits
Found: 5 hits

Prev | Home | Next
Swish->getPropertyList | Up | Swish->query


Swish->query

(no version information, might be only in CVS)

Swish->query -- Execute a query and return results object

Description

object Swish->query ( string query )

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.

A quick method to execute a search with default parameters.

Parameters

query

Query string.

Return Values

Returns SwishResults object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic Swish->query() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish-&#62;query("test query");

    echo "Found: ", $results-&#62;hits, " hits\n";

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

Found: 1 hits

Prev | Home | Next
Swish->prepare | Up | SwishResult->getMetaList


SwishResult->getMetaList

(no version information, might be only in CVS)

SwishResult->getMetaList -- Get a list of meta entries

Description

array SwishResult->getMetaList ( void )

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

Returns the same array as swish->getmetalist(), but uses the index file from the result handle.

Prev | Home | Next
Swish->query | Up | SwishResult->stem


SwishResult->stem

(no version information, might be only in CVS)

SwishResult->stem -- Stems the given word

Description

array SwishResult->stem ( string word )

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.

Stems the word based on the fuzzy mode used during indexing. Each result object is linked with its index, so the results are based on this index.

Parameters

word

The word to stem.

Return Values

Returns array containing the stemmed word variants (usually just one).

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic () example

&#60;?php

try {

    $swish = new Swish("ext/swish/tests/index.swish-e");
    $results = $swish-&#62;query("testing OR others");

    if ($result = $results-&#62;nextResult()) {
        var_dump($result-&#62;stem("testing")); //the results fully depend on the stemmer used in th index
        var_dump($result-&#62;stem("others"));
    }

} catch (SwishException $e) {
    echo "Error: ", $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

array(1) {
  [0]=>
  string(4) "test"
}
array(1) {
  [0]=>
  string(5) "other"
}

Prev | Home | Next
SwishResult->getMetaList | Up | SwishResults->getParsedWords


SwishResults->getParsedWords

(no version information, might be only in CVS)

SwishResults->getParsedWords -- Get an array of parsed words

Description

array SwishResults->getParsedWords ( string index_name )

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

indexi_name

The name of the index used to initialize Swish object.

Return Values

An array of parsed words with stopwords removed. The list of parsed words may be useful for highlighting search terms in the results.

Examples

Example 1. Basic SwishResults->getParsedWords() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish-&#62;query("'some characters' and numbers");

    var_dump($results-&#62;getParsedWords("index.swish-e"));
    var_dump($results-&#62;indexes[0]['parsed_words']); //same result in a different way

} catch (SwishException $e) {
    echo "Error: ", $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}
array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}

Prev | Home | Next
SwishResult->stem | Up | SwishResults->getRemovedStopwords


SwishResults->getRemovedStopwords

(no version information, might be only in CVS)

SwishResults->getRemovedStopwords -- Get an array of stopwords removed from the query

Description

array SwishResults->getRemovedStopwords ( string index_name )

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

index_name

The name of the index used to initialize Swish object.

Return Values

Returns array of stopwords removed from the query.

Prev | Home | Next
SwishResults->getParsedWords | Up | SwishResults->nextResult


SwishResults->nextResult

(no version information, might be only in CVS)

SwishResults->nextResult -- Get the next search result

Description

object SwishResults->nextResult ( void )

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

Returns the next SwishResult object in the result set or FALSE if there are no more results available.

Examples

Example 1. Basic SwishResults->nextResult() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("lost");
    while($result = $results-&#62;nextResult()) {
        /* do something with the result object */
    }

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

Prev | Home | Next
SwishResults->getRemovedStopwords | Up | SwishResults->seekResult


SwishResults->seekResult

(no version information, might be only in CVS)

SwishResults->seekResult -- Set current seek pointer to the given position

Description

int SwishResults->seekResult ( int position )

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

position

Zero-based position number. Cannot be less than zero.

Return Values

Returns new position value on success.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic SwishResults->seekResult() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("lost");

    var_dump($results-&#62;seekResult(0)); //this will succeed
    var_dump($results-&#62;seekResult(100)); //this will fail

} catch (SwishException $e) {
    echo "Error: ", $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

int(0)
Error: No more results

Prev | Home | Next
SwishResults->nextResult | Up | SwishSearch->execute


SwishSearch->execute

(no version information, might be only in CVS)

SwishSearch->execute -- Execute the search and get the results

Description

object SwishSearch->execute ( [string query] )

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.

Searches the index file(s) based on the parameters set in the search object.

Parameters

query

The query string is an optional parameter, it can be also set using Swish->prepare() method. The query string is preserved between executions, so you can set it once, but execute the search multiple times.

Return Values

Returns SwishResults object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic SwishSearch->execute() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("query");
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $results = $search-&#62;execute("new OR query");
    echo "Second query found: ", $results-&#62;hits, " hits\n";

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 2 hits
Second query found: 12 hits

Prev | Home | Next
SwishResults->seekResult | Up | SwishSearch->resetLimit


SwishSearch->resetLimit

(no version information, might be only in CVS)

SwishSearch->resetLimit -- Reset the search limits

Description

void SwishSearch->resetLimit ( void )

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.

Reset the search limits previous set by SwishSearch->setLimit.

Examples

Example 1. Basic SwishSearch->resetLimit() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("time");
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search-&#62;execute("time");
    echo "Second query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;resetLimit();
    $results = $search-&#62;execute("time");
    echo "Third query found: ", $results-&#62;hits, " hits\n";

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 5 hits
Second query found: 2 hits
Third query found: 5 hits

Prev | Home | Next
SwishSearch->execute | Up | SwishSearch->setLimit


SwishSearch->setLimit

(no version information, might be only in CVS)

SwishSearch->setLimit -- Set the search limits

Description

void SwishSearch->setLimit ( string property, string low, string high )

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

property

Search result property name.

low

The lowest value of the property.

high

The highest value of the property.

Errors/Exceptions

Throws SwishException on error.

Examples

Example 1. Basic SwishSearch->setLimit() example

&#60;?php
try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("time");
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $i = 0;
    while($result = $results-&#62;nextResult()) {
        echo "Hit #", ++$i, " - ", $result-&#62;swishdocsize, " bytes\n";
    }

    $search-&#62;setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search-&#62;execute("time");
    echo "Second query found: ", $results-&#62;hits, " hits\n";

    $i = 0;
    while($result = $results-&#62;nextResult()) {
        echo "Hit #", ++$i, " - ", $result-&#62;swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 2 hits
Hit #1 - 4261 bytes
Hit #2 - 4768 bytes

Prev | Home | Next
SwishSearch->resetLimit | Up | SwishSearch->setPhraseDelimiter


SwishSearch->setPhraseDelimiter

(no version information, might be only in CVS)

SwishSearch->setPhraseDelimiter -- Set the phrase delimiter

Description

void SwishSearch->setPhraseDelimiter ( string delimiter )

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

delimiter

Phrase delimiter character. The default delimiter is double-quotes.

Examples

Example 1. Basic SwishSearch->setPhraseDelimiter() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute('"every time"'); //looking for "every time"
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;setPhraseDelimiter("'");
    $results = $search-&#62;execute("'every time'"); //the same query, but using different delimiter
    echo "Second query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;setPhraseDelimiter('"');
    $results = $search-&#62;execute("'every time'"); //looking for "every" and "time"
    echo "Third query found: ", $results-&#62;hits, " hits\n";

    //let's look at parsed words
    var_dump($results-&#62;getParsedWords("index.swish-e"));

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 1 hits
Second query found: 1 hits
Third query found: 2 hits
array(2) {
  [0]=>
  string(5) "every"
  [1]=>
  string(4) "time"
}

Prev | Home | Next
SwishSearch->setLimit | Up | SwishSearch->setSort


SwishSearch->setSort

(no version information, might be only in CVS)

SwishSearch->setSort -- Set the sort order

Description

void SwishSearch->setSort ( string sort )

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

sort

Sort order of the results is a string containing name of a result property combined with sort direction ("asc" or "desc"). Examples: "swishrank desc", "swishdocpath asc", "swishtitle asc", "swishdocsize desc", "swishlastmodified desc" etc.

Examples

Example 1. Basic SwishSearch->setSort() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("time");
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $i = 0;
    while($result = $results-&#62;nextResult()) {
        echo "Hit #", ++$i, " - ", $result-&#62;swishdocsize, " bytes\n";
    }

    $search-&#62;setSort("swishdocsize desc"); //sort by document size
    $results = $search-&#62;execute("time");
    echo "Second query found: ", $results-&#62;hits, " hits\n";

    $i = 0;
    while($result = $results-&#62;nextResult()) {
        echo "Hit #", ++$i, " - ", $result-&#62;swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 5 hits
Hit #1 - 37937 bytes
Hit #2 - 15427 bytes
Hit #3 - 7126 bytes
Hit #4 - 4768 bytes
Hit #5 - 4261 bytes

Prev | Home | Next
SwishSearch->setPhraseDelimiter | Up | SwishSearch->setStructure


SwishSearch->setStructure

(no version information, might be only in CVS)

SwishSearch->setStructure -- Set the structure flag in the search object

Description

void SwishSearch->setStructure ( int structure )

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

structure

The structure flag a bitmask is used to limit search to certain parts of HTML documents (like title, meta, body etc.). Its possible values are listed below. To combine several values use bitwise OR operator, see example below.

  • Swish::IN_FILE

  • Swish::IN_TITLE

  • Swish::IN_HEAD

  • Swish::IN_BODY

  • Swish::IN_COMMENTS

  • Swish::IN_HEADER

  • Swish::IN_EMPHASIZED

  • Swish::IN_META

Examples

Example 1. Basic SwishSearch->setStructure() example

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish-&#62;prepare();

    $results = $search-&#62;execute("time");
    echo "First query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;setStructure(Swish::IN_TITLE|Swish::IN_HEAD); //search in title and head
    $results = $search-&#62;execute("time");
    echo "Second query found: ", $results-&#62;hits, " hits\n";

    $search-&#62;setStructure(Swish::IN_ALL); //search in whole document, the default value
    $results = $search-&#62;execute("time");
    echo "Third query found: ", $results-&#62;hits, " hits\n";

} catch (SwishException $e) {
    echo $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

First query found: 5 hits
Second query found: 0 hits
Third query found: 5 hits

Prev | Home | Next
SwishSearch->setSort | Up | Sybase Functions


sys_get_temp_dir

(no version information, might be only in CVS)

sys_get_temp_dir -- Returns directory path used for temporary files

Description

string sys_get_temp_dir ( void )

Returns the path of the directory PHP stores temporary files in by default.

Return Values

Returns the path of the temporary directory.

See Also

tmpfile()
tempnam()

Prev | Home | Next
set_time_limit | Up | version_compare


sys_getloadavg

(no version information, might be only in CVS)

sys_getloadavg -- get average system load

Description

array sys_getloadavg ( void )

This function returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.

Note: This function is not implemented on Windows platforms.

Return Values

Returns an array with three samples (last 1, 5 and 15 minutes).

Examples

Example 1. A sys_getloadavg() example

&#60;?php
$load = sys_getloadavg();
if ($load[0] &#62; 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?&#62;

Prev | Home | Next
sleep | Up | time_nanosleep


tidy_get_opt_doc

(PHP 5 >= 5.1.0RC1)

tidy_get_opt_doc -- Returns the documentation for the given option name

Description

Procedural style:

string tidy_get_opt_doc ( tidy object, string optname )

Object oriented style:

string tidy->getOptDoc ( string optname )

tidy_get_opt_doc() returns the documentation for the given option name.

Note: You need at least libtidy from 25 April, 2005 for this function be available.

Parameters

object

A tidy object

optname

The option name

Return Values

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Examples

Example 1. Print all options along with their documentation and default value

&#60;?php

$tidy = new tidy;
$config = $tidy-&#62;getConfig();

ksort($config);

foreach ($config as $opt =&#62; $val) {

    if (!$doc = $tidy-&#62;getOptDoc($opt))
        $doc = 'no documentation available!';

    $val = ($tidy-&#62;getOpt($opt) === true)  ? 'true'  : $val;
    $val = ($tidy-&#62;getOpt($opt) === false) ? 'false' : $val;

    echo "&#60;p&#62;&#60;b&#62;$opt&#60;/b&#62; (default: '$val')&#60;br /&#62;".
         "$doc&#60;/p&#62;&#60;hr /&#62;\n";
}

?&#62;

See Also

tidy_get_config()
tidy_getopt()

Prev | Home | Next
tidy_get_html | Up | tidy_get_output


tidyNode::getParent

(no version information, might be only in CVS)

tidyNode::getParent -- returns the parent node of the current node

Description

tidyNode tidyNode::getParent ( void )

Returns the parent node of the current node.

Return Values

Returns a tidyNode if the node has a parent, or NULL otherwise.

Prev | Home | Next
tidyNode->isText | Up | Tokenizer Functions


time_sleep_until

(PHP 5 >= 5.1.0RC1)

time_sleep_until -- Make the script sleep until the specified time

Description

bool time_sleep_until ( float timestamp )

This function will make the script sleep until the specified timestamp. If the specified timestamp is in the past, time_sleep_until() will generate a E_WARNING and return FALSE.

Note: This function is not implemented on Windows platforms.

Parameters

timestamp

The timestamp when the script should wake.

Note: All signals will be delivered after the script wakes up.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A time_sleep_until() example

&#60;?php

//returns false and generates a warning
var_dump(time_sleep_until(time()-1));

// may only work on faster computers, will sleep up to 0.2 seconds
var_dump(time_sleep_until(time()+0.2));

?&#62;

See Also

sleep()
usleep()
time_nanosleep()

Prev | Home | Next
time_nanosleep | Up | uniqid


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

&#60;?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?&#62;

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
        )

)

Prev | Home | Next
time | Up | timezone_identifiers_list


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

&#60;?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i &#60; 5; $i++) {
    echo "$timezone_identifiers[$i]\n";
}
?&#62;

The above example will output something similar to:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmera

Prev | Home | Next
timezone_abbreviations_list | Up | timezone_name_from_abbr


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

&#60;?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?&#62;

The above example will output something similar to:

Europe/Berlin
Europe/Paris

See Also

timezone_abbreviations_list()

Prev | Home | Next
timezone_identifiers_list | Up | timezone_name_get


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.

Prev | Home | Next
timezone_name_from_abbr | Up | timezone_offset_get


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

&#60;?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-&#62;getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?&#62;

Prev | Home | Next
timezone_name_get | Up | timezone_open


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.

Prev | Home | Next
timezone_offset_get | Up | timezone_transitions_get


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

&#60;?php
$timezone = new DateTimeZone("CET");
print_r(reset($timezone-&#62;getTransitions()));
?&#62;

The above example will output something similar to:

Array
(
    [ts] => -1693706400
    [time] => 1916-04-30T22:00:00+0000
    [offset] => 7200
    [isdst] => 1
    [abbr] => CEST
)

Prev | Home | Next
timezone_open | Up | DB++ Functions


unicode_encode

(PHP 5 CVS only)

unicode_encode -- Set encoding of a unicode string

Description

string unicode_encode ( unicode input, string encoding, int flags )

Warning

This function is currently not documented; only the argument list is available.

Takes a unicode string and converts it to a string in the specified encoding.

Parameters

input

The unicode string that will be encoded.

encoding

The new encoding for input.

flags

Flags

Return Values

A string on success, or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if a converter cannot be created for the desired encoding.

Examples

Example 1. A unicode_encode() example

Note: The characters will be seen instead of entities in the output.

&#60;?php
header ('Content-Type: text/plain; charset=ISO-8859-2');

$encoded = unicode_encode ('\u0150\u0179', 'ISO-8859-2');

echo 'Unicode semantics: ', ini_get ('unicode_semantics'), PHP_EOL;
echo 'The string itself:', $encoded, PHP_EOL;
echo 'The length of the string: ', strlen ($encoded);
?&#62;

The above example will output something similar to:

Unicode semantics: 1
The string itself: &#336;&#377;
The length of the string: 2

See Also

unicode_symantics()

Prev | Home | Next
i18n_loc_set_default | Up | unicode_semantics


unicode_semantics

(no version information, might be only in CVS)

unicode_semantics -- Check whether unicode semantics is enabled

Description

bool unicode_semantics ( void )

unicode_semantics() checks whether unicode semantics is enabled.

Return Values

Returns TRUE or FALSE.

Prev | Home | Next
unicode_encode | Up | URL Functions


wddx_unserialize

(PHP 3 >= 3.0.7, PHP 5 CVS only)

wddx_unserialize -- Unserializes a WDDX packet

Description

mixed wddx_unserialize ( string packet )

Unserializes a WDDX packet.

Parameters

packet

A WDDX packet, as a string or stream.

Return Values

Returns the unserialized value which can be a string, a number or an array. Note that structures are unserialized into associative arrays.

Prev | Home | Next
wddx_serialize_vars | Up | win32ps Functions


win32_create_service

(PECL)

win32_create_service -- Creates a new service entry in the SCM database

Description

int win32_create_service ( array details [, string machine] )

Parameters

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run.

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Return Values

Returns TRUE on success, otherwise returns a win32 error code.

Examples

Example 1. A win32_create_service() example

Any text that describes the purpose of the example, or what goes on in the example should go here (inside the

&#60;?php
$x = win32_create_service(array(
        'service' =&#62; 'dummyphp',
        'display' =&#62; 'sample dummy PHP service',
        'params' =&#62; __FILE__ . ' run',
));
debug_zval_dump($x);
?&#62;

See Also

win32_delete_service()

Prev | Home | Next
win32service Functions | Up | win32_delete_service


win32_delete_service

(PECL)

win32_delete_service -- Deletes a service entry from the SCM database

Description

int win32_delete_service ( string servicename [, string machine] )

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Parameters

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Return Values

Returns TRUE on success, or a win32 error code on failure.

Examples

Example 1. A win32_delete_service() example

Deletes the dummyphp service.

&#60;?php
win32_delete_service('dummyphp');
?&#62;

Prev | Home | Next
win32_create_service | Up | win32_get_last_control_message


win32_get_last_control_message

(PECL)

win32_get_last_control_message -- Returns the last control message that was sent to this service

Description

int win32_get_last_control_message ( void )

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Return Values

Returns a control constant; one of WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_STOP, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_SESSIONCHANGE.

See Also

win32_start_service_ctrl_dispatcher()

Prev | Home | Next
win32_delete_service | Up | win32_query_service_status


win32_ps_list_procs

(no version information, might be only in CVS)

win32_ps_list_procs -- List running processes

Description

array win32_ps_list_procs ( void )

Retrieves statistics about all running processes.

Return Values

Returns FALSE on failure, or an array consisting of process statistics like win32_ps_stat_proc() returns for all running processes on success.

See Also

win32_ps_stat_proc()

Prev | Home | Next
win32ps Functions | Up | win32_ps_stat_mem


win32_ps_stat_mem

(no version information, might be only in CVS)

win32_ps_stat_mem -- Stat memory utilization

Description

array win32_ps_stat_mem ( void )

Retrieves statistics about the global memory utilization.

Return Values

Returns FALSE on failure, or an array consisting of the following information on success:

load

The current memory load in percent of physical memory.

unit

This is always 1024, and indicates that the following values are the count of 1024 bytes.

total_phys

The amount of total physical memory.

avail_phys

The amount of still available physical memory.

total_pagefile

The amount of total pageable memory (physical memory + paging file).

avail_pagefile

The amount of still available pageable memory (physical memory + paging file).

total_virtual

The amount of total virtual memory for a process.

avail_virtual

The amount of still available virtual memory for a process.

Prev | Home | Next
win32_ps_list_procs | Up | win32_ps_stat_proc


win32_ps_stat_proc

(no version information, might be only in CVS)

win32_ps_stat_proc -- Stat process

Description

array win32_ps_stat_proc ( [int pid] )

Retrieves statistics about the process with the process id pid.

Parameters

pid

The process id of the process to stat. If omitted, the id of the current process.

Return Values

Returns FALSE on failure, or an array consisting of the following information on success:

pid

The process id.

exe

The path to the executable image.

mem

An array containing information about the following memory utilization indicators: page_fault_count, peak_working_set_size, working_set_size, quota_peak_paged_pool_usage, quota_paged_pool_usage, quota_peak_non_paged_pool_usage, quota_non_paged_pool_usage, pagefile_usage and peak_pagefile_usage.

tms

An array containing information about the following CPU time utilization indicators: created, kernel and user.

See Also

win32_ps_list_procs()

Prev | Home | Next
win32_ps_stat_mem | Up | win32service Functions


win32_query_service_status

(PECL)

win32_query_service_status -- Queries the status of a service

Description

mixed win32_query_service_status ( string servicename [, string machine] )

Queries the current status for a service, returning an array of information.

Parameters

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Return Values

Returns FALSE on failure, otherwise returns an array consisting of the following information:

ServiceType

The dwServiceType.

CurrentState

The dwCurrentState.

ControlsAccepted

Which service controls are accepted by the service.

Win32ExitCode

If the service exited, the return code from the process.

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here.

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags.

Prev | Home | Next
win32_get_last_control_message | Up | win32_set_service_status


win32_set_service_status

(PECL)

win32_set_service_status -- Update the service status

Description

bool win32_set_service_status ( int status )

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Parameters

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

win32_start_service_ctrl_dispatcher()

Prev | Home | Next
win32_query_service_status | Up | win32_start_service_ctrl_dispatcher


win32_start_service

(PECL)

win32_start_service -- Starts a service

Description

int win32_start_service ( string servicename [, string machine] )

Attempts to start the named service. Usually requires administrative privileges.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, or some other win32 error code on failure.

See Also

win32_stop_service()

Prev | Home | Next
win32_start_service_ctrl_dispatcher | Up | win32_stop_service


win32_start_service_ctrl_dispatcher

(PECL)

win32_start_service_ctrl_dispatcher -- Registers the script with the SCM, so that it can act as the service with the given name

Description

bool win32_start_service_ctrl_dispatcher ( string name )

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Parameters

name

The short-name of the service, as registered by win32_create_service().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. A win32_start_service_ctrl_dispatcher() example

Any text that describes the purpose of the example, or what goes on in the example should go here (inside the

&#60;?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("I'm probably not running under the service control manager");
}

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # do some work here, trying not to take more than around 30 seconds
  # before coming back into the loop again
}
?&#62;

See Also

win32_get_last_control_message()

Prev | Home | Next
win32_set_service_status | Up | win32_start_service


win32_stop_service

(PECL)

win32_stop_service -- Stops a service

Description

int win32_stop_service ( string servicename [, string machine] )

Stops a named service. Requires administrative privileges.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, or a win32 error code on failure.

See Also

win32_start_service()

Prev | Home | Next
win32_start_service | Up | xattr Functions


XMLReader::close

(no version information, might be only in CVS)

XMLReader::close -- Close the XMLReader input

Description

class XMLReader {

bool close ( void )

}

Closes the input the XMLReader object is currently parsing.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::open
XMLReader::XML

Prev | Home | Next
XMLReader functions | Up | XMLReader::expand


XMLReader::expand

(no version information, might be only in CVS)

XMLReader::expand -- Returns a copy of the current node as a DOM object

Description

class XMLReader {

DOMNode expand ( void )

}

This method copies the current node and returns the appropriate DOM object.

Return Values

The resulting DOMNode or FALSE on error.

Prev | Home | Next
XMLReader::close | Up | XMLReader::getAttribute


XMLReader::getAttribute

(no version information, might be only in CVS)

XMLReader::getAttribute -- Get the value of a named attribute

Description

class XMLReader {

string getAttribute ( string name )

}

Returns the value of a named attribute or an empty string if attribute does not exist or not positioned on an element 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 or not positioned of element.

See Also

XMLReader::getAttributeNo
XMLReader::getAttributeNs

Prev | Home | Next
XMLReader::expand | Up | XMLReader::getAttributeNo


XMLReader::getAttributeNo

(no version information, might be only in CVS)

XMLReader::getAttributeNo -- Get the value of an attribute by index

Description

class XMLReader {

string getAttributeNo ( int index )

}

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Parameters

index

The position of the attribute.

Return Values

The value of the attribute, or an empty string if no attribute exists at index or not positioned of element.

See Also

XMLReader::getAttribute
XMLReader::getAttributeNs

Prev | Home | Next
XMLReader::getAttribute | Up | XMLReader::getAttributeNs


XMLReader::getAttributeNs

(no version information, might be only in CVS)

XMLReader::getAttributeNs -- Get the value of an attribute by localname and URI

Description

class XMLReader {

string getAttributeNs ( string localName, string namespaceURI )

}

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Parameters

localName

The local name.

namespaceURI

The namespace URI.

Return Values

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found or not positioned of element.

See Also

XMLReader::getAttribute
XMLReader::getAttributeNo

Prev | Home | Next
XMLReader::getAttributeNo | Up | XMLReader::getParserProperty


XMLReader::getParserProperty

(no version information, might be only in CVS)

XMLReader::getParserProperty -- Indicates if specified property has been set

Description

class XMLReader {

bool getParserProperty ( int property )

}

Indicates if specified property has been set.

Parameters

property

One of the parser option constants.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::setParserProperty

Prev | Home | Next
XMLReader::getAttributeNs | Up | XMLReader::isValid


XMLReader::isValid

(no version information, might be only in CVS)

XMLReader::isValid -- Indicates if the parsed document is valid

Description

class XMLReader {

bool isValid ( void )

}

Returns a boolean indicating if the document being parsed is currently valid.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::setParserProperty
XMLReader::setRelaxNGSchema
XMLReader::setRelaxNGSchemaSource

Prev | Home | Next
XMLReader::getParserProperty | Up | XMLReader::lookupNamespace


XMLReader::lookupNamespace

(no version information, might be only in CVS)

XMLReader::lookupNamespace -- Lookup namespace for a prefix

Description

class XMLReader {

bool lookupNamespace ( string prefix )

}

Lookup in scope namespace for a given prefix.

Parameters

prefix

String containing the prefix.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
XMLReader::isValid | Up | XMLReader::moveToAttribute


XMLReader::moveToAttribute

(no version information, might be only in CVS)

XMLReader::moveToAttribute -- Move cursor to a named attribute

Description

class XMLReader {

bool moveToAttribute ( string name )

}

Positions cursor on the named attribute.

Parameters

name

The name of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttributeNo
XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute

Prev | Home | Next
XMLReader::lookupNamespace | Up | XMLReader::moveToAttributeNo


XMLReader::moveToAttributeNo

(no version information, might be only in CVS)

XMLReader::moveToAttributeNo -- Move cursor to an attribute by index

Description

class XMLReader {

bool moveToAttributeNo ( int index )

}

Positions cursor on attribute based on its position.

Parameters

index

The position of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttribute
XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute

Prev | Home | Next
XMLReader::moveToAttribute | Up | XMLReader::moveToAttributeNs


XMLReader::moveToAttributeNs

(no version information, might be only in CVS)

XMLReader::moveToAttributeNs -- Move cursor to a named attribute

Description

class XMLReader {

bool moveToAttributeNs ( string localName, string namespaceURI )

}

Positions cursor on the named attribute in specified namespace.

Parameters

localName

The local name.

namespaceURI

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttribute
XMLReader::moveToAttributeNo
XMLReader::moveToFirstAttribute

Prev | Home | Next
XMLReader::moveToAttributeNo | Up | XMLReader::moveToElement


XMLReader::moveToElement

(no version information, might be only in CVS)

XMLReader::moveToElement -- Position cursor on the parent Element of current Attribute

Description

class XMLReader {

bool moveToElement ( void )

}

Moves cursor to the parent Element of current Attribute. Returns TRUE if successful and FALSE if it fails or not positioned on Attribute when this method is called.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToAttribute
XMLReader::moveToAttributeNo
XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute

Prev | Home | Next
XMLReader::moveToAttributeNs | Up | XMLReader::moveToFirstAttribute


XMLReader::moveToFirstAttribute

(no version information, might be only in CVS)

XMLReader::moveToFirstAttribute -- Position cursor on the first Attribute

Description

class XMLReader {

bool moveToFirstAttribute ( void )

}

Moves cursor to the first Attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttribute
XMLReader::moveToAttributeNo
XMLReader::moveToAttributeNs
XMLReader::moveToNextAttribute

Prev | Home | Next
XMLReader::moveToElement | Up | XMLReader::moveToNextAttribute


XMLReader::moveToNextAttribute

(no version information, might be only in CVS)

XMLReader::moveToNextAttribute -- Position cursor on the next Attribute

Description

class XMLReader {

bool moveToNextAttribute ( void )

}

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttribute
XMLReader::moveToAttributeNo
XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute

Prev | Home | Next
XMLReader::moveToFirstAttribute | Up | XMLReader::next


XMLReader::next

(no version information, might be only in CVS)

XMLReader::next -- Move cursor to next node skipping all subtrees

Description

class XMLReader {

bool next ( [string localname] )

}

Positions cursor on the next node skipping all subtrees.

Parameters

localname

The name of the next node to move to.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::next
XMLReader::moveToElement
XMLReader::moveToAttribute

Prev | Home | Next
XMLReader::moveToNextAttribute | Up | XMLReader::open


XMLReader::open

(no version information, might be only in CVS)

XMLReader::open -- Set the URI containing the XML to parse

Description

class XMLReader {

bool open ( string URI [, string encoding [, int options]] )

}

Set the URI containing the XML document to be parsed.

Parameters

URI

URI pointing to the document.

encoding

The document encoding or NULL.

options

A bitmask of the XMLReader Options constants.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
5.2.0 | encoding and options were added.

See Also

XMLReader::XML
XMLReader::close

Prev | Home | Next
XMLReader::next | Up | XMLReader::read


XMLReader::read

(no version information, might be only in CVS)

XMLReader::read -- Move to next node in document

Description

class XMLReader {

bool read ( void )

}

Moves cursor to the next node in the document.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::moveToElement
XMLReader::moveToAttribute
XMLReader::next

Prev | Home | Next
XMLReader::open | Up | XMLReader::setParserProperty


XMLReader::setParserProperty

(no version information, might be only in CVS)

XMLReader::setParserProperty -- Set or Unset parser options

Description

class XMLReader {

bool setParserProperty ( int property, bool value )

}

Set or Unset parser option for the parser. The options must be set
after xmlreader-open() or
xmlreader-xml() are called and before
the first xmlreader-read() call.

Parameters

property

One of the parser option constants.

value

If set to TRUE the option will be enabled otherwise will be disabled.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
XMLReader::read | Up | XMLReader::setRelaxNGSchema


XMLReader::setRelaxNGSchema

(no version information, might be only in CVS)

XMLReader::setRelaxNGSchema -- Set the filename or URI for a RelaxNG Schema

Description

class XMLReader {

bool setRelaxNGSchema ( string filename )

}

Set the filename or URI for the RelaxNG Schema to use for validation.

Parameters

filename

filename or URI pointing to a RelaxNG Schema.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::setRelaxNGSchemaSource

Prev | Home | Next
XMLReader::setParserProperty | Up | XMLReader::setRelaxNGSchemaSource


XMLReader::setRelaxNGSchemaSource

(no version information, might be only in CVS)

XMLReader::setRelaxNGSchemaSource -- Set the data containing a RelaxNG Schema

Description

class XMLReader {

bool setRelaxNGSchemaSource ( string source )

}

Set the data containing a RelaxNG Schema to use for validation.

Parameters

source

String containing the RelaxNG Schema.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLReader::setRelaxNGSchema

Prev | Home | Next
XMLReader::setRelaxNGSchema | Up | XMLReader::XML


XMLReader::XML

(no version information, might be only in CVS)

XMLReader::XML -- Set the data containing the XML to parse

Description

class XMLReader {

bool open ( string source [, string encoding [, int options]] )

}

Set the data containing the XML to parse.

Parameters

source

String containing the XML to be parsed.

encoding

The document encoding or NULL.

options

A bitmask of the XMLReader Options constants.

Return Values

Returns TRUE on success or FALSE on failure.

ChangeLog

Version | Description
5.2.0 | encoding and options were added.

See Also

XMLReader::open
XMLReader::close

Prev | Home | Next
XMLReader::setRelaxNGSchemaSource | Up | XMLWriter Functions


XMLWriter::endAttribute

(no version information, might be only in CVS)

XMLWriter::endAttribute -- End attribute

Description

Object oriented style:

class XMLWriter {

bool endAttribute ( void )

}

Procedural style:

bool xmlwriter_end_attribute ( resource xmlwriter )

Ends the current attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startAttribute
XMLWriter::startAttributeNS
XMLWriter::writeAttribute
XMLWriter::writeAttributeNS

Prev | Home | Next
XMLWriter Functions | Up | XMLWriter::endCData


XMLWriter::endCData

(no version information, might be only in CVS)

XMLWriter::endCData -- End current CDATA

Description

Object oriented style:

class XMLWriter {

bool endCData ( void )

}

Procedural style:

bool xmlwriter_end_cdata ( resource xmlwriter )

Ends the current CDATA section.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startCData
XMLWriter::writeCData

Prev | Home | Next
XMLWriter::endAttribute | Up | XMLWriter::endComment


XMLWriter::endComment

(no version information, might be only in CVS)

XMLWriter::endComment -- Create end comment

Description

Object oriented style:

class XMLWriter {

bool endComment ( void )

}

Procedural style:

bool xmlwriter_end_comment ( resource xmlwriter )

Ends the current comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startComment
XMLWriter::writeComment

Prev | Home | Next
XMLWriter::endCData | Up | XMLWriter::endDocument


XMLWriter::endDocument

(no version information, might be only in CVS)

XMLWriter::endDocument -- End current document

Description

Object oriented style:

class XMLWriter {

bool endDocument ( void )

}

Procedural style:

bool xmlwriter_end_document ( resource xmlwriter )

Ends the current document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDocument

Prev | Home | Next
XMLWriter::endComment | Up | XMLWriter::endDTDAttlist


XMLWriter::endDTD

(no version information, might be only in CVS)

XMLWriter::endDTD -- End current DTD

Description

Object oriented style:

class XMLWriter {

bool endDTD ( void )

}

Procedural style:

bool xmlwriter_end_dtd ( resource xmlwriter )

Ends the DTD of the document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTD
XMLWriter::writeDTD

Prev | Home | Next
XMLWriter::endDTDEntity | Up | XMLWriter::endElement


XMLWriter::endDTDAttlist

(no version information, might be only in CVS)

XMLWriter::endDTDAttlist -- End current DTD AttList

Description

Object oriented style:

class XMLWriter {

bool endDTDAttlist ( void )

}

Procedural style:

bool xmlwriter_end_dtd_attlist ( resource xmlwriter )

Ends the current DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDAttlist
XMLWriter::writeDTDAttlist

Prev | Home | Next
XMLWriter::endDocument | Up | XMLWriter::endDTDElement


XMLWriter::endDTDElement

(no version information, might be only in CVS)

XMLWriter::endDTDElement -- End current DTD element

Description

Object oriented style:

class XMLWriter {

bool endDTDElement ( void )

}

Procedural style:

bool xmlwriter_end_dtd_element ( resource xmlwriter )

Ends the current DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDElement
XMLWriter::writeDTDElement

Prev | Home | Next
XMLWriter::endDTDAttlist | Up | XMLWriter::endDTDEntity


XMLWriter::endDTDEntity

(no version information, might be only in CVS)

XMLWriter::endDTDEntity -- End current DTD Entity

Description

Object oriented style:

class XMLWriter {

bool endDTDEntity ( void )

}

Procedural style:

bool xmlwriter_end_dtd_entity ( resource xmlwriter )

Ends the current DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDEntity
XMLWriter::writeDTDEntity

Prev | Home | Next
XMLWriter::endDTDElement | Up | XMLWriter::endDTD


XMLWriter::endElement

(no version information, might be only in CVS)

XMLWriter::endElement -- End current element

Description

Object oriented style:

class XMLWriter {

bool endElement ( void )

}

Procedural style:

bool xmlwriter_end_element ( resource xmlwriter )

Ends the current element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startElement
XMLWriter::writeElement

Prev | Home | Next
XMLWriter::endDTD | Up | XMLWriter::endPI


XMLWriter::endPI

(no version information, might be only in CVS)

XMLWriter::endPI -- End current PI

Description

Object oriented style:

class XMLWriter {

bool endPI ( void )

}

Procedural style:

bool xmlwriter_end_pi ( resource xmlwriter )

Ends the current processing instruction.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startPI
XMLWriter::writePI

Prev | Home | Next
XMLWriter::endElement | Up | XMLWriter::flush


XMLWriter::flush

(no version information, might be only in CVS)

XMLWriter::flush -- Flush current buffer

Description

Object oriented style:

class XMLWriter {

mixed flush ( [bool empty] )

}

Procedural style:

mixed xmlwriter_flush ( resource xmlwriter [, bool empty] )

Flushes the current buffer.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

empty

Whether to empty the buffer or no. Default is TRUE.

Return Values

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

Prev | Home | Next
XMLWriter::endPI | Up | XMLWriter::fullEndElement


XMLWriter::fullEndElement

(no version information, might be only in CVS)

XMLWriter::fullEndElement -- End current element

Description

Object oriented style:

class XMLWriter {

bool fullEndElement ( void )

}

Procedural style:

bool xmlwriter_full_end_element ( resource xmlwriter )

End the current xml element. Writes an end tag even if the element is empty.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endElement

Prev | Home | Next
XMLWriter::flush | Up | XMLWriter::openMemory


XMLWriter::openMemory

(no version information, might be only in CVS)

XMLWriter::openMemory -- Create new xmlwriter using memory for string output

Description

Object oriented style:

class XMLWriter {

bool openMemory ( void )

}

Procedural style:

resource xmlwriter_open_memory ( void )

Creates a new XMLWriter using memory for string output.

Parameters

Return Values

Object oriented style: Returns TRUE on success or FALSE on failure..

Procedural style: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

See Also

XMLWriter::openURI

Prev | Home | Next
XMLWriter::fullEndElement | Up | XMLWriter::openURI


XMLWriter::openURI

(no version information, might be only in CVS)

XMLWriter::openURI -- Create new xmlwriter using source uri for output

Description

Object oriented style:

class XMLWriter {

bool openURI ( string uri )

}

Procedural style:

resource xmlwriter_open_uri ( string uri )

Creates a new XMLWriter using uri for the output.

Parameters

uri

The URI of the resource for the output.

Return Values

Object oriented style: Returns TRUE on success or FALSE on failure..

Procedural style: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

See Also

XMLWriter::openMemory

Prev | Home | Next
XMLWriter::openMemory | Up | XMLWriter::outputMemory


XMLWriter::outputMemory

(no version information, might be only in CVS)

XMLWriter::outputMemory -- Returns current buffer

Description

Object oriented style:

class XMLWriter {

bool outputMemory ( [bool flush] )

}

Procedural style:

string xmlwriter_output_memory ( resource xmlwriter [, bool flush] )

Returns the current buffer.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

flush

Whether to flush the output buffer or no. Default is TRUE.

Return Values

Returns the current buffer as a string.

See Also

XMLWriter::flush

Prev | Home | Next
XMLWriter::openURI | Up | XMLWriter::setIndentString


XMLWriter::setIndent

(no version information, might be only in CVS)

XMLWriter::setIndent -- Toggle indentation on/off

Description

Object oriented style:

class XMLWriter {

bool setIndent ( bool indent )

}

Procedural style:

bool xmlwriter_set_indent ( resource xmlwriter, bool indent )

Toggles indentation on or off.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

indent

Whether indentation is enabled. Defaults to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::setIndentString

Prev | Home | Next
XMLWriter::setIndentString | Up | XMLWriter::startAttributeNS


XMLWriter::setIndentString

(no version information, might be only in CVS)

XMLWriter::setIndentString -- Set string used for indenting

Description

Object oriented style:

class XMLWriter {

bool setIndentString ( string indentString )

}

Procedural style:

bool xmlwriter_set_indent_string ( resource xmlwriter, string indentString )

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

indentString

The indentation string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::setIndent

Prev | Home | Next
XMLWriter::outputMemory | Up | XMLWriter::setIndent


XMLWriter::startAttribute

(no version information, might be only in CVS)

XMLWriter::startAttribute -- Create start attribute

Description

Object oriented style:

class XMLWriter {

bool startAttribute ( string name )

}

Procedural style:

bool xmlwriter_start_attribute ( resource xmlwriter, string name )

Starts an attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startAttributeNS
XMLWriter::endAttribute
XMLWriter::writeAttribute
XMLWriter::writeAttributeNS

Prev | Home | Next
XMLWriter::startAttributeNS | Up | XMLWriter::startCData


XMLWriter::startAttributeNS

(no version information, might be only in CVS)

XMLWriter::startAttributeNS -- Create start namespaced attribute

Description

Object oriented style:

class XMLWriter {

bool startAttributeNS ( string prefix, string name, string uri )

}

Procedural style:

bool xmlwriter_start_attribute_ns ( resource xmlwriter, string prefix, string name, string uri )

Starts a namespaced attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startAttribute
XMLWriter::endAttribute
XMLWriter::writeAttribute
XMLWriter::writeAttributeNS

Prev | Home | Next
XMLWriter::setIndent | Up | XMLWriter::startAttribute


XMLWriter::startCData

(no version information, might be only in CVS)

XMLWriter::startCData -- Create start CDATA tag

Description

Object oriented style:

class XMLWriter {

bool startCData ( void )

}

Procedural style:

bool xmlwriter_start_cdata ( resource xmlwriter )

Starts a CDATA.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endCData
XMLWriter::writeCData

Prev | Home | Next
XMLWriter::startAttribute | Up | XMLWriter::startComment


XMLWriter::startComment

(no version information, might be only in CVS)

XMLWriter::startComment -- Create start comment

Description

Object oriented style:

class XMLWriter {

bool startComment ( void )

}

Procedural style:

bool xmlwriter_start_comment ( resource xmlwriter )

Starts a comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endComment
XMLWriter::writeComment

Prev | Home | Next
XMLWriter::startCData | Up | XMLWriter::startDocument


XMLWriter::startDocument

(no version information, might be only in CVS)

XMLWriter::startDocument -- Create document tag

Description

Object oriented style:

class XMLWriter {

bool startDocument ( [string version [, string encoding [, string standalone]]] )

}

Procedural style:

bool xmlwriter_start_document ( resource xmlwriter [, string version [, string encoding [, string standalone]]] )

Starts a document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

version

The version number of the document as part of the XML declaration. Defaults to 1.0.

encoding

The encoding of the document as part of the XML declaration. NULL by default.

standalone

yes or no. NULL by default.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endDocument

Prev | Home | Next
XMLWriter::startComment | Up | XMLWriter::startDTDAttlist


XMLWriter::startDTD

(no version information, might be only in CVS)

XMLWriter::startDTD -- Create start DTD tag

Description

Object oriented style:

class XMLWriter {

bool startDTD ( string qualifiedName [, string publicId [, string systemId]] )

}

Procedural style:

bool xmlwriter_start_dtd ( resource xmlwriter, string qualifiedName [, string publicId [, string systemId]] )

Starts a DTD.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endDTD
XMLWriter::writeDTD

Prev | Home | Next
XMLWriter::startDTDEntity | Up | XMLWriter::startElementNS


XMLWriter::startDTDAttlist

(no version information, might be only in CVS)

XMLWriter::startDTDAttlist -- Create start DTD AttList

Description

Object oriented style:

class XMLWriter {

bool startDTDAttlist ( string name )

}

Procedural style:

bool xmlwriter_start_dtd_attlist ( resource xmlwriter, string name )

Starts a DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute list name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endDTDAttlist
XMLWriter::writeDTDAttlist

Prev | Home | Next
XMLWriter::startDocument | Up | XMLWriter::startDTDElement


XMLWriter::startDTDElement

(no version information, might be only in CVS)

XMLWriter::startDTDElement -- Create start DTD element

Description

Object oriented style:

class XMLWriter {

bool startDTDElement ( string qualifiedName )

}

Procedural style:

bool xmlwriter_start_dtd_element ( resource xmlwriter, string qualifiedName )

Starts a DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endDTDElement
XMLWriter::writeDTDElement

Prev | Home | Next
XMLWriter::startDTDAttlist | Up | XMLWriter::startDTDEntity


XMLWriter::startDTDEntity

(no version information, might be only in CVS)

XMLWriter::startDTDEntity -- Create start DTD Entity

Description

Object oriented style:

class XMLWriter {

bool startDTDEntity ( string name, bool isparam )

}

Procedural style:

bool xmlwriter_start_dtd_entity ( resource xmlwriter, string name, bool isparam )

Starts a DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

isparam

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endDTDEntity
XMLWriter::writeDTDEntity

Prev | Home | Next
XMLWriter::startDTDElement | Up | XMLWriter::startDTD


XMLWriter::startElement

(no version information, might be only in CVS)

XMLWriter::startElement -- Create start element tag

Description

Object oriented style:

class XMLWriter {

bool startElement ( string name )

}

Procedural style:

bool xmlwriter_start_element ( resource xmlwriter, string name )

Starts an element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endElement
XMLWriter::writeElement

Prev | Home | Next
XMLWriter::startElementNS | Up | XMLWriter::startPI


XMLWriter::startElementNS

(no version information, might be only in CVS)

XMLWriter::startElementNS -- Create start namespaced element tag

Description

Object oriented style:

class XMLWriter {

bool startElementNS ( string prefix, string name, string uri )

}

Procedural style:

bool xmlwriter_start_element_ns ( resource xmlwriter, string prefix, string name, string uri )

Starts a namespaced element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endElement
XMLWriter::writeElementNS

Prev | Home | Next
XMLWriter::startDTD | Up | XMLWriter::startElement


XMLWriter::startPI

(no version information, might be only in CVS)

XMLWriter::startPI -- Create start PI tag

Description

Object oriented style:

class XMLWriter {

bool startPI ( string target )

}

Procedural style:

bool xmlwriter_start_pi ( resource xmlwriter, string target )

Starts a processing instruction tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::endPI
XMLWriter::writePI

Prev | Home | Next
XMLWriter::startElement | Up | XMLWriter::text


XMLWriter::text

(no version information, might be only in CVS)

XMLWriter::text -- Write text

Description

Object oriented style:

class XMLWriter {

bool text ( string content )

}

Procedural style:

bool xmlwriter_text ( resource xmlwriter, string content )

Writes a text.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the text.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
XMLWriter::startPI | Up | XMLWriter::writeAttributeNS


XMLWriter::writeAttribute

(no version information, might be only in CVS)

XMLWriter::writeAttribute -- Write full attribute

Description

Object oriented style:

class XMLWriter {

bool writeAttribute ( string name, string value )

}

Procedural style:

bool xmlwriter_write_attribute ( resource xmlwriter, string name, string value )

Writes a full attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::writeAttributeNS
XMLWriter::startAttribute
XMLWriter::startAttributeNS
XMLWriter::endAttribute

Prev | Home | Next
XMLWriter::writeAttributeNS | Up | XMLWriter::writeCData


XMLWriter::writeAttributeNS

(no version information, might be only in CVS)

XMLWriter::writeAttributeNS -- Write full namespaced attribute

Description

Object oriented style:

class XMLWriter {

bool writeAttributeNS ( string prefix, string name, string uri, string content )

}

Procedural style:

bool xmlwriter_write_attribute_ns ( resource xmlwriter, string prefix, string name, string uri, string content )

Writes a full namespaced attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

content

The attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::writeAttribute
XMLWriter::startAttribute
XMLWriter::startAttributeNS
XMLWriter::endAttribute

Prev | Home | Next
XMLWriter::text | Up | XMLWriter::writeAttribute


XMLWriter::writeCData

(no version information, might be only in CVS)

XMLWriter::writeCData -- Write full CDATA tag

Description

Object oriented style:

class XMLWriter {

bool writeCData ( string content )

}

Procedural style:

bool xmlwriter_write_cdata ( resource xmlwriter, string content )

Writes a full CDATA.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the CDATA.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startCData
XMLWriter::endCData

Prev | Home | Next
XMLWriter::writeAttribute | Up | XMLWriter::writeComment


XMLWriter::writeComment

(no version information, might be only in CVS)

XMLWriter::writeComment -- Write full comment tag

Description

Object oriented style:

class XMLWriter {

bool writeComment ( string content )

}

Procedural style:

bool xmlwriter_write_comment ( resource xmlwriter, string content )

Writes a full comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startComment
XMLWriter::endComment

Prev | Home | Next
XMLWriter::writeCData | Up | XMLWriter::writeDTDAttlist


XMLWriter::writeDTD

(no version information, might be only in CVS)

XMLWriter::writeDTD -- Write full DTD tag

Description

Object oriented style:

class XMLWriter {

bool writeDTD ( string name [, string publicId [, string systemId [, string subset]]] )

}

Procedural style:

bool xmlwriter_write_dtd ( resource xmlwriter, string name [, string publicId [, string systemId [, string subset]]] )

Writes a full DTD.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

subset

The content of the DTD.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTD
XMLWriter::endDTD

Prev | Home | Next
XMLWriter::writeDTDEntity | Up | XMLWriter::writeElementNS


XMLWriter::writeDTDAttlist

(no version information, might be only in CVS)

XMLWriter::writeDTDAttlist -- Write full DTD AttList tag

Description

Object oriented style:

class XMLWriter {

bool writeDTDAttlist ( string name, string content )

}

Procedural style:

bool xmlwriter_write_dtd_attlist ( resource xmlwriter, string name, string content )

Writes a DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDAttlist
XMLWriter::endDTDAttlist

Prev | Home | Next
XMLWriter::writeComment | Up | XMLWriter::writeDTDElement


XMLWriter::writeDTDElement

(no version information, might be only in CVS)

XMLWriter::writeDTDElement -- Write full DTD element tag

Description

Object oriented style:

class XMLWriter {

bool writeDTDElement ( string name, string content )

}

Procedural style:

bool xmlwriter_write_dtd_element ( resource xmlwriter, string name, string content )

Writes a full DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDElement
XMLWriter::endDTDElement

Prev | Home | Next
XMLWriter::writeDTDAttlist | Up | XMLWriter::writeDTDEntity


XMLWriter::writeDTDEntity

(no version information, might be only in CVS)

XMLWriter::writeDTDEntity -- Write full DTD Entity tag

Description

Object oriented style:

class XMLWriter {

bool writeDTDEntity ( string name, string content )

}

Procedural style:

bool xmlwriter_write_dtd_entity ( resource xmlwriter, string name, string content )

Writes a full DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startDTDEntity
XMLWriter::endDTDEntity

Prev | Home | Next
XMLWriter::writeDTDElement | Up | XMLWriter::writeDTD


XMLWriter::writeElement

(no version information, might be only in CVS)

XMLWriter::writeElement -- Write full element tag

Description

Object oriented style:

class XMLWriter {

bool writeElement ( string name, string content )

}

Procedural style:

bool xmlwriter_write_element ( resource xmlwriter, string name, string content )

Writes a full element tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

content

The element contents.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startElement
XMLWriter::endElement
XMLWriter::writeElementNS

Prev | Home | Next
XMLWriter::writeElementNS | Up | XMLWriter::writePI


XMLWriter::writeElementNS

(no version information, might be only in CVS)

XMLWriter::writeElementNS -- Write full namesapced element tag

Description

Object oriented style:

class XMLWriter {

bool writeElementNS ( string prefix, string name, string uri, string content )

}

Procedural style:

bool xmlwriter_write_element_ns ( resource xmlwriter, string prefix, string name, string uri, string content )

Writes a full namesapced element tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

content

The element contents.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startElementNS
XMLWriter::endElement
XMLWriter::writeElement

Prev | Home | Next
XMLWriter::writeDTD | Up | XMLWriter::writeElement


XMLWriter::writePI

(no version information, might be only in CVS)

XMLWriter::writePI -- Writes a PI

Description

Object oriented style:

class XMLWriter {

bool writePI ( string target, string content )

}

Procedural style:

bool xmlwriter_write_pi ( resource xmlwriter, string target, string content )

Writes a processing instruction.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::startPI
XMLWriter::endPI

Prev | Home | Next
XMLWriter::writeElement | Up | XMLWriter::writeRaw


XMLWriter::writeRaw

(no version information, might be only in CVS)

XMLWriter::writeRaw -- Write a raw XML text

Description

Object oriented style:

class XMLWriter {

bool writeRaw ( string content )

}

Procedural style:

bool xmlwriter_write_raw ( resource xmlwriter, string content )

Writes a raw xml text.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The text string to write.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

XMLWriter::text

Prev | Home | Next
XMLWriter::writePI | Up | XSL functions


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.

See Also

xpath_register_ns_auto()

Prev | Home | Next
xpath_register_ns_auto | Up | xptr_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.

See Also

xpath_register_ns()

Prev | Home | Next
xpath_new_context | Up | xpath_register_ns


yaz_es

(PECL)

yaz_es -- Prepares for an Extended Service Request

Description

void yaz_es ( resource id, string type, array args )

This function prepares for an Extended Service Request. Extended Services is family of various Z39.50 facilities, such as Record Update, Item Order, Database administration etc.

Note: Many Z39.50 Servers do not support Extended Services.

The yaz_es() creates an Extended Service Request packages and puts it into a queue of operations. Use yaz_wait() to send the request(s) to the server. After completion of yaz_wait() the result of the Extended Service operation should be expected with a call to yaz_es_result().

Parameters

id

The connection resource returned by yaz_connect().

type

A string which represents the type of the Extended Service: itemorder (Item Order), create (Create Database), drop (Drop Database), commit (Commit Operation), update (Update Record), xmlupdate (XML Update). Each type is specified in the following section.

args

An array with extended service options plus package specific options. The options are identical to those offered in the C API of ZOOM C. Refer to the ZOOM Extended Services.

Return Values

No value is returned.

Examples

Example 1. Record Update

&#60;?php
$con = yaz_connect("myhost/database");
$args = array (
    "record" =&#62; "&#60;gils&#62;&#60;title&#62;some title&#60;/title&#62;&#60;/gils&#62;",
    "syntax" =&#62; "xml",
    "action" =&#62; "specialUpdate"
);
yaz_es($con, "update", $args);
yaz_wait();
$result = yaz_es_result($id);
?&#62;

See Also

yaz_es_result()

Prev | Home | Next
yaz_es_result | Up | yaz_get_option


ZipArchive::addFile

(no version information, might be only in CVS)

ZipArchive::addFile -- Adds a file to a ZIP archive from the given path

Description

bool ZipArchive::addFile ( string filename [, string localname] )

Adds a file to a ZIP archive from a given path

Parameters

filename

The path to the file to add.

localname

local name inside ZIP archive.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Example 1. Open and extract

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test.zip') === TRUE) {
    $zip-&#62;addFile('/path/to/index.txt', 'newname.txt');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
zip_read | Up | ZipArchive::addFromString


ZipArchive::addFromString

(no version information, might be only in CVS)

ZipArchive::addFromString -- Add a file to a ZIP archive using its contents

Description

bool ZipArchive::addFromString ( string localname, string contents )

Add a file to a ZIP archive using its contents.

Parameters

localname

The name of the entry to create.

contents

The contents to use to create the entry. It is used in a binary safe mode.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Add an entry to a new archive

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip-&#62;addFromString('test.txt', 'file content goes here');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Example 2. Add file to a directory inside an archive

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test.zip') === TRUE) {
    $zip-&#62;addFromString('dir/test.txt', 'file content goes here');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::addFile | Up | ZipArchive::close


ZipArchive::close

(no version information, might be only in CVS)

ZipArchive::close -- Close the active archive (opened or newly created)

Description

bool ZipArchive::close ( void )

Close opened or created archive and save changes. This method is automatically called at the end of the script.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ZipArchive::addFromString | Up | ZipArchive::deleteIndex


ZipArchive::deleteIndex

(no version information, might be only in CVS)

ZipArchive::deleteIndex -- delete an entry in the archive using its index

Description

bool ZipArchive::deleteIndex ( int index )

Delete an entry in the archive using its index.

Parameters

index

Index of the entry to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Delete file from archive using its index

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test.zip') === TRUE) {
    $zip-&#62;deleteIndex(2);
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::close | Up | ZipArchive::deleteName


ZipArchive::deleteName

(no version information, might be only in CVS)

ZipArchive::deleteName -- delete an entry in the archive using its name

Description

bool ZipArchive::deleteName ( string name )

Delete an entry in the archive using its name.

Parameters

name

Name of the entry to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Delete file from archive using its name

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test1.zip') === TRUE) {
    $zip-&#62;deleteName('testfromfile.php');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::deleteIndex | Up | ZipArchive::extractTo


ZipArchive::extractTo

(no version information, might be only in CVS)

ZipArchive::extractTo -- Extract the archive contents

Description

mixed ZipArchive::extractTo ( string destination [, mixed entries] )

Extract the complete archive or the given files to the specified destination.

Parameters

destination

Location where to extract the files.

entries

The entries to extract. It accepts either a single entry name or an array of names.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example 1. Extract all entries

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test.zip') === TRUE) {
    $zip-&#62;extractTo('/my/destination/dir/');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Example 2. Extract only two entries

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test_im.zip');
if ($res === TRUE) {
    $zip-&#62;extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::deleteName | Up | ZipArchive::getArchiveComment


ZipArchive::getArchiveComment

(no version information, might be only in CVS)

ZipArchive::getArchiveComment -- Returns the Zip archive comment

Description

string ZipArchive::getArchiveComment ( void )

Returns the Zip archive comment.

Return Values

Returns the Zip archive comment or FALSE on failure.

Examples

Example 1. Dump an archive comment

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test_with_comment.zip')
if ($res === TRUE) {
    var_dump($zip-&#62;getArchiveComment());
    /* Or using the archive property */
    var_dump($zip-&#62;comment);
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Prev | Home | Next
ZipArchive::extractTo | Up | ZipArchive::getCommentIndex


ZipArchive::getCommentIndex

(no version information, might be only in CVS)

ZipArchive::getCommentIndex -- Returns the comment of an entry using the entry index

Description

string ZipArchive::getCommentIndex ( int index [, int flags] )

Returns the comment of an entry using the entry index.

Parameters

index

Index of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Return Values

Returns the comment on success or FALSE on failure.

Examples

Example 1. Dump an entry comment

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test1.zip')
if ($res === TRUE) {
    var_dump($zip-&#62;getCommentIndex(1));
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Prev | Home | Next
ZipArchive::getArchiveComment | Up | ZipArchive::getCommentName


ZipArchive::getCommentName

(no version information, might be only in CVS)

ZipArchive::getCommentName -- Returns the comment of an entry using the entry name

Description

string ZipArchive::getCommentName ( string name [, int flags] )

Returns the comment of an entry using the entry name.

Parameters

name

Name of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Return Values

Returns the comment on success or FALSE on failure.

Examples

Example 1. Dump an entry comment

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test1.zip')
if ($res === TRUE) {
    var_dump($zip-&#62;getCommentName('test/entry1.txt'));
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Prev | Home | Next
ZipArchive::getCommentIndex | Up | ZipArchive::getFromIndex


ZipArchive::getFromIndex

(no version information, might be only in CVS)

ZipArchive::getFromIndex -- Returns the entry contents using its index.

Description

mixed ZipArchive::getFromIndex ( int index [, int flags] )

Returns the entry contents using its index.

Parameters

index

Index of the entry

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example 1. Get the file contents

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test.zip') === TRUE) {
    echo $zip-&#62;getFromIndex(2);
    $zip-&#62;close();
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::getCommentName | Up | ZipArchive::getFromName


ZipArchive::getFromName

(no version information, might be only in CVS)

ZipArchive::getFromName -- Returns the entry contents using its name.

Description

mixed ZipArchive::getFromName ( string name [, int flags] )

Returns the entry contents using its name.

Parameters

name

Name of the entry

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example 1. Get the file contents

&#60;?php
$zip = new ZipArchive;
if ($zip-&#62;open('test1.zip') === TRUE) {
    echo $zip-&#62;getFromName('testfromfile.php');
    $zip-&#62;close();
} else {
    echo 'failed';
}
?&#62;

Example 2. Convert an image from a zip entry

&#60;?php
$z = new ZipArchive();
if ($z-&#62;open(dirname(__FILE__) . '/test_im.zip')) {
    $im_string = $z-&#62;getFromName("pear_item.gif");
    $im = imagecreatefromstring($im_string);
    imagepng($im, 'b.png');
}
?&#62;

Prev | Home | Next
ZipArchive::getFromIndex | Up | ZipArchive::getNameIndex


ZipArchive::getNameIndex

(no version information, might be only in CVS)

ZipArchive::getNameIndex -- Returns the name of an entry using its index

Description

string ZipArchive::getNameIndex ( int index )

Returns the name of an entry using its index.

Parameters

index

Index of the entry.

Return Values

Returns the name on success or FALSE on failure.

Prev | Home | Next
ZipArchive::getFromName | Up | ZipArchive::getStream


ZipArchive::getStream

(no version information, might be only in CVS)

ZipArchive::getStream -- Get a file handler to the entry defined by its name (read only).

Description

resource ZipArchive::getStream ( string name )

Get a file handler to the entry defined by its name. For now it only supports read operations.

Parameters

name

The name of the entry to use.

Return Values

Returns a file pointer (resource) on success or FALSE on failure.

Examples

Example 1. Get the entry contents with fread and store it.

&#60;?php
$content = '';
$z = new ZipArchive();
if ($z-&#62;open('test.zip')) {
    $fp = $z-&#62;getStream('test');
    if(!$fp) exit("failed\n");

    while (!feof($fp)) {
        $contents .= fread($fp, 2);
    }

    fclose($fp);
    file_put_contents('t',$contents);
    echo "done.\n";
}
?&#62;

Example 2. Same as the previous example but with fopen and the zip stream wrapper

&#60;?php
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
    exit("cannot open\n");
}
while (!feof($fp)) {
    $contents .= fread($fp, 2);
    echo "$contents\n";
}
fclose($fp);
echo "done.\n";
?&#62;

Example 3. Stream wrapper and image, can be used with the xml function as well

&#60;?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?&#62;

Prev | Home | Next
ZipArchive::getNameIndex | Up | ZipArchive::locateName


ZipArchive::locateName

(no version information, might be only in CVS)

ZipArchive::locateName -- Returns the index of the entry in the archive

Description

mixed ZipArchive::locateName ( string name [, int flags] )

Locates an entry using its name.

Parameters

name

The name of the entry to look up

flags

The function returns the index of the file named fname in archive. The flags are specified by ORing the following values, or 0 for none of them.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

Return Values

Returns the index of the entry on success or FALSE on failure.

Examples

Example 1. Create an archive and then use it with locateName

&#60;?php
$file = 'testlocate.zip';

$zip = new ZipArchive;
if ($zip-&#62;open($file, ZIPARCHIVE::CREATE) !== TRUE) {
    exit('failed');
}

$zip-&#62;addFromString('entry1.txt', 'entry #1');
$zip-&#62;addFromString('entry2.txt', 'entry #2');
$zip-&#62;addFromString('dir/entry2d.txt', 'entry #2');

if (!$zip-&#62;status == ZIPARCHIVE::ER_OK) {
    echo "failed to write zip\n";
}
$zip-&#62;close();

if ($zip-&#62;open($file) === TRUE) {
    exit('failed');
}

echo $zip-&#62;locateName('entry1.txt') . "\n";
echo $zip-&#62;locateName('eNtry2.txt') . "\n";
echo $zip-&#62;locateName('eNtry2.txt', ZIPARCHIVE::FL_NOCASE) . "\n";
echo $zip-&#62;locateName('enTRy2d.txt', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR) . "\n";
$zip-&#62;close();

?&#62;

Prev | Home | Next
ZipArchive::getStream | Up | ZipArchive::open


ZipArchive::open

(no version information, might be only in CVS)

ZipArchive::open -- Open a ZIP file archive

Description

mixed ZipArchive::open ( string filename [, int flags] )

Opens a new zip archive for reading, writing or modifying.

Parameters

filename

The file name of the ZIP archive to open.

flags

The mode to use to open the archive.

  • ZIPARCHIVE::OVERWRITE

  • ZIPARCHIVE::CREATE

  • ZIPARCHIVE::EXCL

  • ZIPARCHIVE::CHECKCONS

Return Values

Error codes

Returns TRUE on success or the error code.

  • ZIPARCHIVE::ER_EXISTS

  • ZIPARCHIVE::ER_INCONS

  • ZIPARCHIVE::ER_INVAL

  • ZIPARCHIVE::ER_MEMORY

  • ZIPARCHIVE::ER_NOENT

  • ZIPARCHIVE::ER_NOZIP

  • ZIPARCHIVE::ER_OPEN

  • ZIPARCHIVE::ER_READ

  • ZIPARCHIVE::ER_SEEK

Examples

This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example 1. Open and extract

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip')
if ($res === TRUE) {
    echo 'ok';
    $zip-&#62;extractTo('test');
    $zip-&#62;close();
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Example 2. Create an archive

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip-&#62;addFromString('test.txt', 'file content goes here');
    $zip-&#62;addFile('data.txt', 'entryname.txt');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::locateName | Up | ZipArchive::renameIndex


ZipArchive::renameIndex

(no version information, might be only in CVS)

ZipArchive::renameIndex -- Renames an entry defined by its index

Description

bool ZipArchive::renameIndex ( int index, string newname )

Renames an entry defined by its index.

Parameters

index

Index of the entry to rename.

newname

New name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Rename one entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip')
if ($res === TRUE) {
    $zip-&#62;renameIndex(2,'newname.txt');
    $zip-&#62;close();
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Prev | Home | Next
ZipArchive::open | Up | ZipArchive::renameName


ZipArchive::renameName

(no version information, might be only in CVS)

ZipArchive::renameName -- Renames an entry defined by its name

Description

bool ZipArchive::renameName ( string name, string newname )

Renames an entry defined by its index.

Parameters

name

Name of the entry to rename.

newname

New name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Rename one entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip');
if ($res === TRUE) {
    $zip-&#62;renameName('currentname.txt','newname.txt');
    $zip-&#62;close();
} else {
    echo 'failed, code:' . $res;
}
?&#62;

Prev | Home | Next
ZipArchive::renameIndex | Up | ZipArchive::setArchiveComment


ZipArchive::setArchiveComment

(no version information, might be only in CVS)

ZipArchive::setArchiveComment -- Set the comment of a ZIP archive

Description

mixed ZipArchive::setArchiveComment ( string comment )

Set the comment of a ZIP archive.

Parameters

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Create an archive and set a comment

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip-&#62;addFromString('test.txt', 'file content goes here');
    $z-&#62;setArchiveComment('new archive comment');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::renameName | Up | ZipArchive::setCommentIndex


ZipArchive::setCommentIndex

(no version information, might be only in CVS)

ZipArchive::setCommentIndex -- Set the comment of an entry defined by its index

Description

mixed ZipArchive::setCommentIndex ( int index, string comment )

Set the comment of an entry defined by its index.

Parameters

index

Index of the entry.

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Open an archive and set a comment for an entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip');
if ($res === TRUE) {
    $z-&#62;setCommentIndex(2, 'new entry comment');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::setArchiveComment | Up | ZipArchive::setCommentName


ZipArchive::setCommentName

(no version information, might be only in CVS)

ZipArchive::setCommentName -- Set the comment of an entry defined by its name

Description

mixed ZipArchive::setCommentIndex ( string name, string comment )

Set the comment of an entry defined by its name.

Parameters

name

Name of the entry.

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 1. Open an archive and set a comment for an entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip');
if ($res === TRUE) {
    $z-&#62;setCommentName('entry1.txt', 'new entry comment');
    $zip-&#62;close();
    echo 'ok';
} else {
    echo 'failed';
}
?&#62;

Prev | Home | Next
ZipArchive::setCommentIndex | Up | ZipArchive::statIndex


ZipArchive::statIndex

(no version information, might be only in CVS)

ZipArchive::statIndex -- Get the details of an entry defined by its index.

Description

mixed ZipArchive::statIndex ( int index [, int flags] )

The function obtains information about the entry defined by its index.

Parameters

index

Index of the entry

flags

ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example 1. Dump the stat info of an entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip')
if ($res === TRUE) {
    print_r($zip-&#62;statIndex(3));
    $zip-&#62;close();
} else {
    echo 'failed, code:' . $res;
}
?&#62;

The above example will output something similar to:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)

Prev | Home | Next
ZipArchive::setCommentName | Up | ZipArchive::statName


ZipArchive::statName

(no version information, might be only in CVS)

ZipArchive::statName -- Get the details of an entry defined by its name.

Description

mixed ZipArchive::statName ( name name [, int flags] )

The function obtains information about the entry defined by its name.

Parameters

name

Name of the entry

flags

The flags argument specifies how the name lookup should be done. Also, ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

  • ZIPARCHIVE::FL_UNCHANGED

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example 1. Dump the stat info of an entry

&#60;?php
$zip = new ZipArchive;
$res = $zip-&#62;open('test.zip')
if ($res === TRUE) {
    print_r($zip-&#62;statName('foobar/baz'));
    $zip-&#62;close();
} else {
    echo 'failed, code:' . $res;
}
?&#62;

The above example will output something similar to:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)

Prev | Home | Next
ZipArchive::statIndex | Up | ZipArchive::unchangeAll


ZipArchive::unchangeAll

(no version information, might be only in CVS)

ZipArchive::unchangeAll -- Undo all changes done in the archive.

Description

mixed ZipArchive::unchangeAll ( void )

Undo all changes done in the archive.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ZipArchive::statName | Up | ZipArchive::unchangeArchive


ZipArchive::unchangeArchive

(no version information, might be only in CVS)

ZipArchive::unchangeArchive -- Revert all global changes done in the archive.

Description

mixed ZipArchive::unchangeArchive ( void )

Revert all global changes to the archive archive. For now, this only reverts archive comment changes.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ZipArchive::unchangeAll | Up | ZipArchive::unchangeIndex


ZipArchive::unchangeIndex

(no version information, might be only in CVS)

ZipArchive::unchangeIndex -- Revert all changes done to an entry at the given index.

Description

mixed ZipArchive::unchangeIndex ( int index )

Revert all changes done to an entry at the given index.

Parameters

index

Index of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ZipArchive::unchangeArchive | Up | ZipArchive::unchangeName


ZipArchive::unchangeName

(no version information, might be only in CVS)

ZipArchive::unchangeName -- Revert all changes done to an entry with the given name.

Description

mixed ZipArchive::unchangeName ( string name )

Revert all changes done to an entry.

Parameters

name

Name of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

Prev | Home | Next
ZipArchive::unchangeIndex | Up | Zlib Compression Functions


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

Name | Default | Changeable | Description
http.etag.mode | "MD5" | PHP_INI_ALL |
http.log.cache | "" | PHP_INI_ALL |
http.log.redirect | "" | PHP_INI_ALL |
http.log.not_found | "" | PHP_INI_ALL |
http.log.allowed_methods | "" | PHP_INI_ALL |
http.log.composite | "" | PHP_INI_ALL |
http.request.methods.allowed | "" | PHP_INI_ALL |
http.request.methods.custom | "" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
http.send.inflate.start_flags | "0" | PHP_INI_ALL |
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
http.send.deflate.start_flags | "0" | PHP_INI_ALL |
http.send.not_found_404 | "1" | PHP_INI_ALL |
http.only_exceptions | "0" | PHP_INI_ALL |
http.force_exit | "1" | PHP_INI_ALL |

Prev | Home | Next
Installation | Up | Constants


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)

HTTP_SUPPORT_REQUESTS (integer)

HTTP_SUPPORT_MAGICMIME (integer)

HTTP_SUPPORT_ENCODINGS (integer)

HTTP_SUPPORT_SSLREQUESTS (integer)

Constants usable with http_parse_params()

HTTP_PARAMS_ALLOW_COMMA (integer)

HTTP_PARAMS_ALLOW_FAILURE (integer)

HTTP_PARAMS_RAISE_ERROR (integer)

HTTP_PARAMS_DEFAULT (integer)

Constants usable with http_parse_cookie() and its return value

HTTP_COOKIE_PARSE_RAW (integer)

HTTP_COOKIE_SECURE (integer)

HTTP_COOKIE_HTTPONLY (integer)

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)

HTTP_ENCODING_STREAM_FLUSH_SYNC (integer)

HTTP_ENCODING_STREAM_FLUSH_FULL (integer)

Constants used for error reporting and Exceptions

HTTP_E_RUNTIME (integer)

HTTP_E_INVALID_PARAM (integer)

HTTP_E_HEADER (integer)

HTTP_E_MALFORMED_HEADERS (integer)

HTTP_E_REQUEST_METHOD (integer)

HTTP_E_MESSAGE_TYPE (integer)

HTTP_E_ENCODING (integer)

HTTP_E_REQUEST (integer)

HTTP_E_REQUEST_POOL (integer)

HTTP_E_SOCKET (integer)

HTTP_E_RESPONSE (integer)

HTTP_E_URL (integer)

HTTP_E_QUERYSTRING (integer)

Constants usable with HttpMessage

HTTP_MSG_NONE (integer)

HTTP_MSG_REQUEST (integer)

HTTP_MSG_RESPONSE (integer)

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)

HTTP_AUTH_DIGEST (integer)

HTTP_AUTH_NTLM (integer)

HTTP_AUTH_ANY (integer)

Constants used for the HTTP protocol version request option

HTTP_VERSION_NONE (integer)

HTTP_VERSION_1_0 (integer)

HTTP_VERSION_1_1 (integer)

Constants used for the proxytype request option

HTTP_PROXY_SOCKS4 (integer)

HTTP_PROXY_SOCKS5 (integer)

HTTP_PROXY_HTTP (integer)

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)

HTTP_REDIRECT_PERM (integer)

HTTP_REDIRECT_FOUND (integer)

HTTP_REDIRECT_POST (integer)

HTTP_REDIRECT_PROXY (integer)

HTTP_REDIRECT_TEMP (integer)

Constants usable with http_build_url()

HTTP_URL_REPLACE (integer)

HTTP_URL_JOIN_PATH (integer)

HTTP_URL_JOIN_QUERY (integer)

HTTP_URL_STRIP_USER (integer)

HTTP_URL_STRIP_PASS (integer)

HTTP_URL_STRIP_AUTH (integer)

HTTP_URL_STRIP_PORT (integer)

HTTP_URL_STRIP_PATH (integer)

HTTP_URL_STRIP_QUERY (integer)

HTTP_URL_STRIP_FRAGMENT (integer)

HTTP_URL_STRIP_ALL (integer)

Prev | Home | Next
Configuration | Up | HttpMessage


HttpDeflateStream

(no version information, might be only in CVS)

HttpDeflateStream -- HTTP Deflate Stream Class

Synopsis

class HttpDeflateStream

Class Members

Predefined Constants

Table 1.

Type | Name | Description
int | TYPE_GZIP | gzip encoding
int | TYPE_ZLIB | zlib AKA deflate encoding
int | TYPE_RAW | raw deflate encoding
int | LEVEL_MIN | minimum compression level
int | TYPE_DEF | default compression level
int | LEVEL_MAX | maximum compression level
int | STRATEGY_DEF | default strategy
int | STRATEGY_FILT | filtered strategy
int | STRATEGY_HUFF | Huffman strategy
int | STRATEGY_RLE | RLE strategy
int | STRATEGY_FIXED | fixed strategy
int | FLUSH_NONE | no forced flush
int | FLUSH_SYNC | synching flush
int | FLUSH_FULL | full flush

Methods

HttpDeflateStream::construct()
HttpDeflateStream::update()
HttpDeflateStream:: flush()
HttpDeflateStream::finish()

Prev | Home | Next
HttpQueryString::xlate | Up | HttpDeflateStream::__construct


HttpInflateStream

(no version information, might be only in CVS)

HttpInflateStream -- HTTP Inflate Stream

Synopsis

class HttpInflateStream

Class Members

Constants

Table 1.

Type | Name | Description
int | FLUSH_NONE | no forced flush
int | FLUSH_SYNC | synching flush
int | FLUSH_FULL | full flush

Note: Flushing usually has no effect on inflate streams.

Methods

HttpInflateStream::construct()
HttpInflateStream::update()
HttpInflateStream:: flush()
HttpInflateStream::finish()

Prev | Home | Next
HttpDeflateStream::finish | Up | HttpInflateStream::__construct


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

Modifiers | Type | Name | Description
protected | int | type | message type
protected | string | body | message body
protected | float | httpVersion | HTTP protocol version
protected | array | headers | message headers
protected | string | requestMethod | request method name
protected | requestUrl | string | request URL
protected | int | responseCode | response code
protected | string | responseStatus | response status message
protected | HttpMessage | parentMessage | reference 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.

Type | Name | Description
int | TYPE_NONE | message has is of no specific type
int | TYPE_REQUEST | message is a request style HTTP message
int | TYPE_RESPONSE | message is a response style HTTP message

Methods

HttpMessage::construct()
HttpMessage::fromString()
HttpMessage::toString()
HttpMessage::toMessageTypeObject()
HttpMessage::guessContentType()
HttpMessage::detach()
HttpMessage::prepend()
HttpMessage::reverse()
HttpMessage::send()
HttpMessage::getParentMessage()
HttpMessage:: getType()
HttpMessage:: setType()
HttpMessage::getHttpVersion()
HttpMessage::setHttpVersion()
HttpMessage::getHeaders()
HttpMessage::getHeader()
HttpMessage::addHeaders()
HttpMessage::setHeaders()
HttpMessage::getBody()
HttpMessage::setBody()
HttpMessage::getRequestMethod()
HttpMessage::setRequestMethod()
HttpMessage::getRequestUrl()
HttpMessage::setRequestUrl()
HttpMessage::getResponseCode()
HttpMessage::setResponseCode()
HttpMessage::getResponseStatus()
HttpMessage::setResponseStatus()

Prev | Home | Next
Constants | Up | HttpMessage::__construct


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

Modifiers | Type | Name | Description
private | array | queryArray | query parameters
private | string | queryString | serialized query parameters

Table 2. Static Properties

Modifiers | Type | Name | Description
private | array | instance | holds singletons

Predefined Constants

Table 3.

Type | Name | Description
int | TYPE_BOOL | retrieve query param as bool
int | TYPE_INT | retrieve query param as int
int | TYPE_FLOAT | retrieve query param as float
int | TYPE_STRING | retrieve query param as string
int | TYPE_ARRAY | retrieve query param as array
int | TYPE_OBJECT | retrieve query param as object

Methods

HttpQueryString::construct()
HttpQueryString::singleton()
HttpQueryString::get()
HttpQueryString::mod()
HttpQueryString::set()
HttpQueryString::toArray()
HttpQueryString::toString()
HttpQueryString::xlate()

Prev | Home | Next
HttpMessage::setResponseStatus | Up | HttpQueryString::__construct


HttpRequest

(no version information, might be only in CVS)

HttpRequest -- HTTP Request Class

Synopsis

class HttpRequest

Class Members

Properties

Table 1. Instance Properties

Modifiers | Type | Name | Description
protected | array | options |
protected | array | postFields |
protected | array | postFiles |
protected | array | responseInfo |
protected | array | responseData |
protected | HttpMessage | responseMessage |
protected | integer | responseCode |
protected | string | responseStatus |
protected | integer | method |
protected | string | url |
protected | string | contentType |
protected | string | rawPostData |
protected | string | queryData |
protected | string | putFile |
protected | string | putData |
protected | HttpMessage | history |
public | boolean | recordHistory |

Predefined Constants

Table 2.

Type | Name | Description
integer | METH_GET |
integer | METH_HEAD |
integer | METH_POST |
integer | METH_PUT |
integer | METH_DELETE |
integer | METH_OPTIONS |
integer | METH_TRACE |
integer | METH_CONNECT |
integer | METH_PROPFIND |
integer | METH_PROPPATCH |
integer | METH_MKCOL |
integer | METH_COPY |
integer | METH_MOVE |
integer | METH_LOCK |
integer | METH_UNLOCK |
integer | METH_VERSION_CONTROL |
integer | METH_REPORT |
integer | METH_CHECKOUT |
integer | METH_CHECKIN |
integer | METH_UNCHECKOUT |
integer | METH_MKWORKSPACE |
integer | METH_UPDATE |
integer | METH_LABEL |
integer | METH_MERGE |
integer | METH_BASELINE_CONTROL |
integer | METH_MKACTIVITY |
integer | METH_ACL |
integer | VERSION_1_0 |
integer | VERSION_1_1 |
integer | VERSION_NONE |
integer | AUTH_BASIC |
integer | AUTH_DIGEST |
integer | AUTH_NTLM |
integer | AUTH_ANY |
integer | PROXY_SOCKS4 |
integer | PROXY_SOCKS5 |
integer | PROXY_HTTP |

Methods

HttpRequest::construct()
HttpRequest::getOptions()
HttpRequest::setOptions()
HttpRequest::getSslOptions()
HttpRequest::addSslOptions()
HttpRequest::setSslOptions()
HttpRequest::getUrl()
HttpRequest::setUrl()
HttpRequest::getMethod()
HttpRequest::setMethod()
HttpRequest::enableCookies()
HttpRequest::resetCookies()
HttpRequest::getCookies()
HttpRequest::addCookies()
HttpRequest::setCookies()
HttpRequest::getHeaders()
HttpRequest::addHeaders()
HttpRequest::setHeaders()
HttpRequest::getContentType()
HttpRequest::setContentType()
HttpRequest::getQueryData()
HttpRequest::addQueryData()
HttpRequest::setQueryData()
HttpRequest::getPostFields()
HttpRequest::addPostFields()
HttpRequest::setPostFields()
HttpRequest::getPostFiles()
HttpRequest::addPostFile()
HttpRequest::setPostFiles()
HttpRequest::getRawPostData()
HttpRequest::addRawPostData()
HttpRequest::setRawPostData()
HttpRequest::getPutData()
HttpRequest::addPutData()
HttpRequest::setPutData()
HttpRequest::getPutFile()
HttpRequest::setPutFile()
HttpRequest::send()
HttpRequest::getRequestMessage()
HttpRequest::getRawRequestMessage()
HttpRequest::getResponseMessage()
HttpRequest::getRawResponseMessage()
HttpRequest::getResponseCode()
HttpRequest::getResponseStatus()
HttpRequest::getResponseHeader()
HttpRequest::getResponseCookies()
HttpRequest::getResponseBody()
HttpRequest::getResponseData()
HttpRequest::getResponseInfo()
HttpRequest::clearHistory()
HttpRequest::getHistory()

Prev | Home | Next
HttpInflateStream::finish | Up | HttpRequest::addCookies


HttpRequestPool

(no version information, might be only in CVS)

HttpRequestPool -- HTTP Request Pool Class

Synopsis

class HttpRequest implements Iterator, Countable

Class Members

Properties

The HttpRequestPool class does not have any properties.

Predefined Constants

The HttpRequestPool class does not have any constants.

Methods

HttpRequestPool::construct()
HttpRequestPool::destruct()
HttpRequestPool::attach()
HttpRequestPool::detach()
HttpRequestPool::getAttachedRequests()
HttpRequestPool::getFinishedRequests()
HttpRequestPool:: reset()
HttpRequestPool::send()
HttpRequestPool::socketPerform()
HttpRequestPool::socketSelect()

Prev | Home | Next
HttpRequest::setUrl | Up | HttpRequestPool::attach


HttpResponse

(no version information, might be only in CVS)

HttpResponse -- HTTP Response Class

Synopsis

static class HttpResponse

Class Members

Properties

Table 1. Static Properties

Modifiers | Type | Name | Description
private | boolean | sent |
private | boolean | catch |
private | integer | mode |
private | resource | stream |
private | string | file |
private | string | data |
protected | boolean | cache |
protected | boolean | gzip |
protected | string | eTag |
protected | integer | lastModified |
protected | string | cacheControl |
protected | string | contentType |
protected | string | contentDisposition |
protected | integer | bufferSize |
protected | double | throttleDelay |

Predefined Constants

Table 2.

Type | Name | Description
integer | REDIRECT |
integer | REDIRECT_PERM |
integer | REDIRECT_FOUND |
integer | REDIRECT_POST |
integer | REDIRECT_PROXY |
integer | REDIRECT_TEMP |

Methods

HttpResponse::getBufferSize()
HttpResponse::setBufferSize()
HttpResponse::getCacheControl()
HttpResponse::setCacheControl()
HttpResponse::getCache()
HttpResponse::setCache()
HttpResponse::getContentDisposition()
HttpResponse::setContentDisposition()
HttpResponse::getContentType()
HttpResponse::setContentType()
HttpResponse::getData()
HttpResponse::setData()
HttpResponse::getETag()
HttpResponse::setETag()
HttpResponse::getFile()
HttpResponse::setFile()
HttpResponse::getGzip()
HttpResponse::setGzip()
HttpResponse::getHeader()
HttpResponse::setHeader()
HttpResponse::getLastModified()
HttpResponse::setLastModified()
HttpResponse::getStream()
HttpResponse::setStream()
HttpResponse::getThrottleDelay()
HttpResponse::setThrottleDelay()
HttpResponse::capture()
HttpResponse::send()
HttpResponse::guessContentType()

Prev | Home | Next
HttpRequestPool::socketSelect | Up | HttpResponse::capture


Installation

(no version information, might be only in CVS)

Installation -- Installing and configuring 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.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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, 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).

Prev | Home | Next
HTTP | Up | Configuration


php.ini directives

PHP Manual
Prev Next

Appendix G. php.ini directives

Table of Contents
List of php.ini directives
Description of core php.ini directives

List of php.ini directives

This list includes the php.ini directives you can set to configure your PHP setup.

Table G-1. Configuration options

Name | Default | Changeable | Changelog
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. Available since PHP 4.0.4.
allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.1.0.
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12p2
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in APC <= 3.0.12p2
apc.enable_cli | "0" | PHP_INI_SYSTEM |
apc.file_update_protection | "2" | PHP_INI_SYSTEM |
apc.filters | NULL | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.max_file_size | "1M" | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.optimization | "0" | PHP_INI_ALL |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "30" | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM |
apc.ttl | "0" | PHP_INI_SYSTEM |
apc.user_entries_hint | "100" | PHP_INI_SYSTEM |
apc.user_ttl | "0" | PHP_INI_SYSTEM |
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR | Available since PHP 4.0.5.
arg_separator.output | "&" | PHP_INI_ALL | Available since PHP 4.0.5.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
auto_detect_line_endings | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
auto_globals_jit | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
bcmath.scale | "0" | PHP_INI_ALL |
bcompiler.enabled | "1" | PHP_INI_ALL |
birdstep.max_links | "-1" | PHP_INI_ALL | Available since PHP 4.2.0.
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
cgi.discard_path | "0" | PHP_INI_ALL | Available since PHP 6.0.0.
cgi.fix_pathinfo | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
cgi.force_redirect | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
cgi.nph | "0" | PHP_INI_ALL | Available since PHP 4.3.5.
cgi.redirect_status_env | NULL | PHP_INI_ALL | Available since PHP 4.2.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
child_terminate | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
crack.default_dictionary | NULL | PHP_INI_PERDIR | Available since PHP 4.0.5.
daffodildb.default_host | "localhost" | PHP_INI_ALL |
daffodildb.default_password | "daffodil" | PHP_INI_ALL |
daffodildb.default_socket | NULL | PHP_INI_ALL |
daffodildb.default_user | "DAFFODIL" | PHP_INI_ALL |
daffodildb.port | "3456" | PHP_INI_ALL |
date.default_latitude | "31.7667" | PHP_INI_ALL | Available since PHP 5.0.0.
date.default_longitude | "35.2333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunrise_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunset_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0.
date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0.
dba.default_handler | "" | PHP_INI_ALL | Available since PHP 4.3.3.
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
default_charset | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0.
define_syslog_variables | "0" | PHP_INI_ALL |
disable_classes | "" | php.ini only | Available since PHP 4.3.2.
disable_functions | "" | php.ini only | Available since PHP 4.0.1.
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Available since PHP 4.0.3.
docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2.
docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0.
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM |
engine | "1" | PHP_INI_ALL | Available since PHP 4.0.5.
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0.
expect.logfile | "" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
fastcgi.logging | "1" | PHP_INI_ALL | Available since PHP 4.4.0.
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.batchsize | "1000" | PHP_INI_ALL | Available since PHP 5.1.0.
fbsql.default_database | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.0.3.
filter.default | "string" | PHP_INI_ALL |
filter.default_flags | NULL | PHP_INI_ALL |
from | "" | PHP_INI_ALL |
highlight.bg | "#FFFFFF" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2.
http.allowed_methods | "" | PHP_INI_ALL |
http.allowed_methods_log | "" | PHP_INI_ALL |
http.cache_log | "" | PHP_INI_ALL |
http.composite_log | "" | PHP_INI_ALL |
http.etag_mode | "MD5" | PHP_INI_ALL |
http.force_exit | "1" | PHP_INI_ALL |
http.ob_deflate_auto | "0" | PHP_INI_PERDIR |
http.ob_deflate_flags | "0" | PHP_INI_ALL |
http.ob_inflate_auto | "0" | PHP_INI_PERDIR |
http.ob_inflate_flags | "0" | PHP_INI_ALL |
http.only_exceptions | "0" | PHP_INI_ALL |
http.redirect_log | "" | PHP_INI_ALL |
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2.
hyperwave.default_port | "418" | PHP_INI_ALL |
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
ibase.default_db | NULL | PHP_INI_SYSTEM | Available since PHP 5.0.0.
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM |
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
ifx.allow_persistent | "1" | PHP_INI_SYSTEM |
ifx.blobinfile | "1" | PHP_INI_ALL |
ifx.byteasvarchar | "0" | PHP_INI_ALL |
ifx.charasvarchar | "0" | PHP_INI_ALL |
ifx.default_host | NULL | PHP_INI_SYSTEM |
ifx.default_password | NULL | PHP_INI_SYSTEM |
ifx.default_user | NULL | PHP_INI_SYSTEM |
ifx.max_links | "-1" | PHP_INI_SYSTEM |
ifx.max_persistent | "-1" | PHP_INI_SYSTEM |
ifx.nullformat | "0" | PHP_INI_ALL |
ifx.textasvarchar | "0" | PHP_INI_ALL |
ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3.
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.blob_segment_length | "4096" | PHP_INI_ALL |
ingres.cursor_mode | "0" | PHP_INI_ALL |
ingres.default_database | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.default_password | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.default_user | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2.
ingres.report_db_warnings | "1" | PHP_INI_ALL |
ingres.timeout | "-1" | PHP_INI_ALL |
ingres.trace_connect | "0" | PHP_INI_ALL |
ircg.control_user | "nobody" | PHP_INI_ALL | Available since PHP 5.0.0.
ircg.keep_alive_interval | "60" | PHP_INI_ALL | Available since PHP 5.0.0.
ircg.max_format_message_sets | "12" | PHP_INI_ALL | Available since PHP 5.0.0.
ircg.shared_mem_size | "6000000" | PHP_INI_ALL | Available since PHP 5.0.0.
ircg.work_dir | "/tmp/ircg" | PHP_INI_ALL | Available since PHP 5.0.0.
last_modified | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
magic_quotes_runtime | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_ALL |
mail.force_extra_parameters | NULL | PHP_INI_PERDIR | Available since PHP 5.0.0.
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Available since PHP 4.1.0.
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.func_overload | "0" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.2.0.
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.language | "neutral" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
memory_limit | "8M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2.
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Available since PHP 4.1.0.
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.3.0.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Available since PHP 4.0.1.
mysql.default_user | NULL | PHP_INI_ALL |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
namazu.debugmode | "0" | PHP_INI_ALL |
namazu.lang | NULL | PHP_INI_ALL |
namazu.loggingmode | "0" | PHP_INI_ALL |
namazu.sortmethod | NULL | PHP_INI_ALL |
namazu.sortorder | NULL | PHP_INI_ALL |
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3.
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.default_db | NULL | PHP_INI_ALL |
odbc.default_pw | NULL | PHP_INI_ALL |
odbc.default_user | NULL | PHP_INI_ALL |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
opendirectory.max_refs | "-1" | PHP_INI_ALL |
opendirectory.separator | "/" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_SYSTEM |
oracle.allow_persistent | "-1" | PHP_INI_ALL |
oracle.max_links | "-1" | PHP_INI_ALL |
oracle.max_persistent | "-1" | PHP_INI_ALL |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4.
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.defaultport | "443" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxyaddress | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxylogon | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxypassword | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pfpro.proxyport | "" | PHP_INI_ALL | Available since PHP 4.0.2.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.3.
precision | "14" | PHP_INI_ALL |
printer.default_printer | "" | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_long_arrays | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
report_zend_debug | "1" | PHP_INI_ALL | Available since PHP 5.0.0.
runkit.internal_override | "0" | PHP_INI_SYSTEM |
runkit.superglobal | "" | PHP_INI_PERDIR |
safe_mode | "0" | PHP_INI_SYSTEM |
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM |
safe_mode_exec_dir | "" | PHP_INI_SYSTEM |
safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | NULL | PHP_INI_SYSTEM |
serialize_precision | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.auto_start | "0" | PHP_INI_ALL |
session.bug_compat_42 | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.cache_expire | "180" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Available since PHP 4.0.4.
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.hash_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 5.0.0.
session.hash_function | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
session.name | "PHPSESSID" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.save_path | "" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session_pgsql.create_table | "1" | PHP_INI_SYSTEM |
session_pgsql.db | "host=localhost dbname=php_session user=nobody" | PHP_INI_SYSTEM |
session_pgsql.disable | "0" | PHP_INI_SYSTEM |
session_pgsql.failover_mode | "0" | PHP_INI_SYSTEM |
session_pgsql.gc_interval | "3600" | PHP_INI_SYSTEM |
session_pgsql.keep_expired | "0" | PHP_INI_SYSTEM |
session_pgsql.sem_file_name | "/tmp/php_session_pgsql" | PHP_INI_SYSTEM |
session_pgsql.serializable | "0" | PHP_INI_SYSTEM |
session_pgsql.short_circuit | "0" | PHP_INI_SYSTEM |
session_pgsql.use_app_vars | "0" | PHP_INI_SYSTEM |
session_pgsql.vacuum_interval | "21600" | PHP_INI_SYSTEM |
short_open_tag | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
simple_cvs.authMethod | "0" | PHP_INI_ALL |
simple_cvs.compressionLevel | "0" | PHP_INI_ALL |
simple_cvs.cvsRoot | "0" | PHP_INI_ALL |
simple_cvs.host | "0" | PHP_INI_ALL |
simple_cvs.moduleName | "0" | PHP_INI_ALL |
simple_cvs.userName | "0" | PHP_INI_ALL |
simple_cvs.workingDir | "0" | PHP_INI_ALL |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Available since PHP 4.3.0.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Available since PHP 5.0.0.
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.compatability_mode | "0" | PHP_INI_ALL |
sybase.interface_file | "" | PHP_INI_ALL |
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.login_timeout | "-1" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.packet_size | "0" | PHP_INI_ALL | Available since PHP 4.3.5.
sybct.timeout | "0" | PHP_INI_ALL | Available since PHP 4.0.2.
sysvshm.init_mem | "10000" | PHP_INI_ALL |
tidy.clean_output | "0" | PHP_INI_PERDIR | Available since PHP 5.0.0.
tidy.default_config | "" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
track_errors | "0" | PHP_INI_ALL |
unicode.fallback_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_mode | "2" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_subst_char | "3f" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.http_input_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.output_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.runtime_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.script_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode_semantics | "off" | PHP_INI_PERDIR | Available since PHP 6.0.0.
unserialize_callback_func | NULL | PHP_INI_ALL | Available since PHP 4.2.0.
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Available since PHP 4.0.4.
user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
user_dir | NULL | PHP_INI_SYSTEM |
valkyrie.auto_validate | "0" | PHP_INI_ALL |
valkyrie.config_path | NULL | PHP_INI_ALL |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
xbithack | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0.
xmlrpc_error_number | "0" | PHP_INI_ALL | Available since PHP 4.1.0.
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL |
xmms.session | "0" | PHP_INI_ALL |
y2k_compliance | "1" | PHP_INI_ALL |
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
yaz.log_mask | NULL | PHP_INI_ALL |
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0.
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
zlib.output_compression | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Available since PHP 4.3.0.

Table G-2. Definition of PHP_INI_* constants

Constant | Value | Meaning
PHP_INI_USER | 1 | Entry can be set in user scripts or in Windows registry
PHP_INI_PERDIR | 2 | Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM | 4 | Entry can be set in php.ini or httpd.conf
PHP_INI_ALL | 7 | Entry can be set anywhere

Prev | Home | Next
Configure options | Up | Description of core php.ini directives


Description of core php.ini directives

This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page.

Httpd Options

Table G-3. Httpd Options

Name | Default | Changeable | Changelog
async_send | "0" | PHP_INI_ALL |

Language Options

Table G-4. Language and Misc Configuration Options

Name | Default | Changeable | Changelog
short_open_tag | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
precision | "14" | PHP_INI_ALL |
y2k_compliance | "1" | PHP_INI_ALL |
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0.
expose_php | "1" | php.ini only |
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Available since PHP 5.0.0.

Here's a short explanation of the configuration directives.

short_open_tag boolean

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

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

asp_tags boolean

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

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

precision integer

The number of significant digits displayed in floating point numbers.

y2k_compliance boolean

Enforce year 2000 compliance (will cause problems with non-compliant browsers)

allow_call_time_pass_reference boolean

Whether to warn when arguments are passed by reference at function call time. This method is deprecated and is likely to be unsupported in future versions of PHP/Zend. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature).

Passing arguments by reference at function call time was deprecated for code cleanliness reason. Function can modify its argument in undocumented way if it didn't declared that the argument is passed by reference. To prevent side-effects it's better to specify which arguments are passed by reference in function declaration only.

See also References Explained.

expose_php boolean

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.

zend.ze1_compatibility_mode boolean

Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

See also the section titled Migrating from PHP 4 to PHP 5.

Resource Limits

Table G-5. Resource Limits

Name | Default | Changeable | Changelog
memory_limit | "8M" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. In order to use this directive you must have enabled it at compile time. So, your configure line would have included: --enable-memory-limit. Note that you have to set it to -1 if you don't want any limit for your memory.

As of PHP 4.3.2, and when memory_limit is enabled, the PHP function memory_get_usage() is made available.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

See also: max_execution_time.

Performance Tuning

Table G-6. Performance Tuning

Name | Default | Changeable | Changelog
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.

Here's a short explanation of the configuration directives.

realpath_cache_size integer

Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed.

realpath_cache_ttl integer

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Data Handling

Table G-7. Data Handling Configuration Options

Name | Default | Changeable | Changelog
track_vars | "On" | PHP_INI_?? |
arg_separator.output | "&" | PHP_INI_ALL | Available since PHP 4.0.5.
arg_separator.input | "&" | PHP_INI_PERDIR | Available since PHP 4.0.5.
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
auto_globals_jit | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_long_arrays | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.3.
gpc_order | "GPC" | PHP_INI_ALL |
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "" | PHP_INI_ALL |
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.1.0.
allow_webdav_methods | "0" | PHP_INI_PERDIR |

Here's a short explanation of the configuration directives.

track_vars boolean

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

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

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Note: Every character in this directive is considered as separator!

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set.

If the deprecated register_globals directive is on (removed as of PHP 6), then variables_order also configures the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope. So for example if variables_order is set to "EGPCS", register_globals is enabled, and both $_GET['action'] and $_POST['action'] are set, then $action will contain the value of $_POST['action'] as P comes after G in our example directive value.

Note: The content and order of $_REQUEST is also affected by this directive.

auto_globals_jit boolean

When enabled, the SERVER and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

The PHP directives register_globals, register_long_arrays, and register_argc_argv must be disabled for this directive to have any affect. Since PHP 5.1.3 it is not necessary to have register_argc_argv disabled.

register_globals boolean

Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables.

As of PHP 4.2.0, this directive defaults to off.

Please read the security chapter on Using register_globals for related information.

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

Note: register_globals is affected by the variables_order directive.

This directive was removed in PHP 6.0.0.

register_argc_argv boolean

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

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

register_long_arrays boolean

Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET.

This directive became available in PHP 5.0.0 and was dropped in PHP 6.0.0.

post_max_size integer

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

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

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set.

gpc_order string

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

Note: This option is not available in PHP 4. Use variables_order instead.

auto_prepend_file string

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

The special value none disables auto-prepending.

auto_append_file string

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

The special value none disables auto-appending.

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

default_mimetype string

default_charset string

As of 4.0.0, PHP always outputs a character encoding by default in the Content-type: header. To disable sending of the charset, simply set it to be empty.

always_populate_raw_post_data boolean

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only with unrecognized MIME type of the data. However, the preferred method for accessing the raw POST data is php://input. $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

allow_webdav_methods boolean

Allow handling of WebDAV http requests within PHP scripts (eg. PROPFIND, PROPPATCH, MOVE, COPY, etc.). This directive does not exist as of PHP 4.3.2. If you want to get the post data of those requests, you have to set always_populate_raw_post_data as well.

See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.

Paths and Directories

Table G-8. Paths and Directories Configuration Options

Name | Default | Changeable | Changelog
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini only |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
cgi.fix_pathinfo | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
cgi.force_redirect | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
cgi.redirect_status_env | NULL | PHP_INI_ALL | Available since PHP 4.2.0.
fastcgi.impersonate | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

include_path string

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

Example G-1. Unix include_path

include_path=".:/php/includes"

Example G-2. Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_dir string

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

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

cgi.check_shebang_line boolean

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting of zero causes PHP to behave as before. Default is zero. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Note: Windows Users: You can safely turn this off for IIS, in fact, you must. To get OmniHTTPD or Xitami to work you must turn it off.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Note: Setting this variable may cause security issues, know what you are doing first.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set 0, PHP sends a Status: header that is supported by Apache and other web servers. When this option is set to 1, PHP will send RFC 2616 compliant headers. Leave it set to 0 unless you know what you're doing.

File Uploads

Table G-9. File Uploads Configuration Options

Name | Default | Changeable | Changelog
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.0.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.

Here's a short explanation of the configuration directives.

file_uploads boolean

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

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

upload_max_filesize integer

The maximum size of an uploaded file.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

General SQL

Table G-10. General SQL Configuration Options

Name | Default | Changeable | Changelog
sql.safe_mode | "0" | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

sql.safe_mode boolean

If turned on, database connect functions that specify default values will use those values in place of supplied arguments. For default values see connect function documentation for the relevant database.

Debugger Configuration Directives

Caution

Only PHP 3 implements a default debugger, for more information see Appendix E.

debugger.host string

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

debugger.port string

Port number used by the debugger.

debugger.enabled boolean

Whether the debugger is enabled.

Prev | Home | Next
php.ini directives | Up | List of Supported Timezones


Installation and Configuration

PHP Manual
Prev Next

II. Installation and Configuration

Table of Contents
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

Prev | Home | Next
What's next? |  | General Installation Considerations


General Installation Considerations

PHP Manual
Prev Next

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.

Prev | Home | Next
Installation and Configuration | Up | Installation on Unix systems


Installation on Mac OS X

PHP Manual
Prev Next

Chapter 5. Installation on Mac OS X

Table of Contents
Using Packages
Using the bundled PHP
Compiling for OS X Server
Compiling for MacOS X Client

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:

  • Darwin: http://darwinports.opendarwin.org/

  • Entropy: http://www.entropy.ch/software/macosx/php/

  • Fink: http://fink.sourceforge.net/

Prev | Home | Next
Debian GNU/Linux installation notes | Up | Using the bundled PHP


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:

    &#60;?php phpinfo(); ?&#62;

  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 commandline 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.

Prev | Home | Next
Installation on Mac OS X | Up | Compiling for OS X Server


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.

Prev | Home | Next
Compiling for OS X Server | Up | Installation on Windows systems


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.

Prev | Home | Next
Using the bundled PHP | Up | Compiling for MacOS X Client


Installation of PECL extensions

PHP Manual
Prev Next

Chapter 7. Installation of PECL extensions

Table of Contents
Introduction to PECL Installations
Downloading PECL extensions
PECL for Windows users
Compiling shared PECL extensions with PEAR
Compiling shared PECL extensions with phpize
Compiling PECL extensions statically into PHP

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.

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.

Prev | Home | Next
Installation of extensions on Windows | Up | Downloading PECL extensions


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 pear 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.

Prev | Home | Next
Installation of PECL extensions | Up | PECL for Windows users


Compiling shared PECL extensions with PEAR

PEAR makes it easy to create shared PHP extensions. Using the pear 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 pear 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

Prev | Home | Next
PECL for Windows users | Up | Compiling shared PECL extensions with phpize


Compiling shared PECL extensions with phpize

Sometimes, using the pear 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 PEAR 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.

Prev | Home | Next
Compiling shared PECL extensions with PEAR | Up | Compiling PECL extensions statically into PHP


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
$ pear 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

Prev | Home | Next
Compiling shared PECL extensions with phpize | Up | Problems?


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.

Prev | Home | Next
Downloading PECL extensions | Up | Compiling shared PECL extensions with PEAR


Problems?

PHP Manual
Prev Next

Chapter 8. Problems?

Table of Contents
Read the FAQ
Other problems
Bug reports

Read the FAQ

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

Prev | Home | Next
Compiling PECL extensions statically into PHP | Up | Other problems


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!

Prev | Home | Next
Other problems | Up | Runtime Configuration


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.

Prev | Home | Next
Problems? | Up | Bug reports


Installation on Unix systems

PHP Manual
Prev Next

Chapter 4. Installation on Unix systems

Table of Contents
Apache 1.3.x on Unix systems
Apache 2.0 on Unix systems
Caudium
fhttpd related notes
Sun, iPlanet and Netscape servers on Sun Solaris
CGI and commandline setups
HP-UX specific installation notes
OpenBSD installation notes
Solaris specific installation tips
Debian GNU/Linux installation notes

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 webserver. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

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 commandline 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 webpage 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.

Prev | Home | Next
General Installation Considerations | Up | Apache 2.0 on Unix systems


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:

  • PHP 4.3.0 or later available at http://www.php.net/downloads.php.
  • the latest stable development version. Get the source code http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php5-win32-latest.zip.
  • a prerelease version downloadable from http://qa.php.net/.
  • you have always the option to obtain PHP through anonymous CVS.
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.

Prev | Home | Next
Installation on Unix systems | Up | Caudium


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.

Prev | Home | Next
Apache 2.0 on Unix systems | Up | fhttpd related notes


CGI and commandline setups

The default is to build PHP as a CGI program. This creates a commandline interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables 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'.

Prev | Home | Next
Sun, iPlanet and Netscape servers on Sun Solaris | Up | HP-UX specific installation notes


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.

Prev | Home | Next
Solaris specific installation tips | Up | Installation on Mac OS X


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.

Prev | Home | Next
Caudium | Up | Sun, iPlanet and Netscape servers on Sun Solaris


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

Prev | Home | Next
CGI and commandline setups | Up | OpenBSD installation notes


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).

Prev | Home | Next
HP-UX specific installation notes | Up | Solaris specific installation tips


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.

Prev | Home | Next
OpenBSD installation notes | Up | Debian GNU/Linux installation notes


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 webservers 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 webservers, 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 webserver. 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 webserver 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 webserver. 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 webserver 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 webserver without any valid CGI variables!

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

Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver 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 webserver and insert the result in the webpage. 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!!!

Prev | Home | Next
fhttpd related notes | Up | CGI and commandline setups


Installation on Windows systems

PHP Manual
Prev Next

Chapter 6. Installation on Windows systems

Table of Contents
Windows Installer (PHP 5.1 and earlier)
Windows Installer (PHP 5.2 and later)
Manual Installation Steps
ActiveScript
Microsoft IIS / PWS
Apache 1.3.x on Microsoft Windows
Apache 2.0.x on Microsoft Windows
Sun, iPlanet and Netscape servers on Microsoft Windows
OmniHTTPd Server
Sambar Server on Microsoft Windows
Xitami on Microsoft Windows
Building from source
Installation of extensions on Windows

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.1 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.

Prev | Home | Next
Compiling for MacOS X Client | Up | Windows Installer (PHP 5.2 and later)


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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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.

Prev | Home | Next
Manual Installation Steps | Up | Microsoft IIS / PWS


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'); ?>.

Prev | Home | Next
Microsoft IIS / PWS | Up | Apache 2.0.x on Microsoft Windows


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:

  • PHP 4.3.0 or later available at http://www.php.net/downloads.php.
  • the latest stable development version. Get the source code http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php5-win32-latest.zip.
  • a prerelease version downloadable from http://qa.php.net/.
  • you have always the option to obtain PHP through anonymous CVS.
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.

Prev | Home | Next
Apache 1.3.x on Microsoft Windows | Up | Sun, iPlanet and Netscape servers on Microsoft Windows


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:

  • the win32 buildtools from the PHP site at http://www.php.net/extra/win32build.zip.

  • the source code for the DNS name resolver used by PHP from http://www.php.net/extra/bindlib_w32.zip. This is a replacement for the resolv.lib library included in win32build.zip.

  • If you plan to compile PHP as a Apache module you will also need the Apache sources.

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.

Prev | Home | Next
Xitami on Microsoft Windows | Up | Installation of extensions on Windows


Installation of extensions on Windows

After installing PHP and a webserver 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 webserver 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

Extension | Description | Notes
php_bz2.dll | bzip2 compression functions | None
php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3
php_cpdf.dll | ClibPDF functions | None
php_crack.dll | Crack functions | None
php_ctype.dll | ctype family functions | Built in since PHP 4.3.0
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled)
php_cybercash.dll | Cybercash payment functions | PHP <= 4.2.0
php_db.dll | DBM functions | Deprecated. Use DBA instead (php_dba.dll)
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None
php_dbase.dll | dBase functions | None
php_dbx.dll | dbx functions |
php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll | .NET functions | PHP <= 4.1.1
php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dll | FrontBase functions | PHP <= 4.2.0
php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled)
php_filepro.dll | filePro functions | Read-only access
php_ftp.dll | FTP functions | Built-in since PHP 4.0.3
php_gd.dll | GD 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.dll | GD library image functions | GD2
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dll | HyperWave functions | None
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dll | Informix functions | Requires: Informix libraries
php_iisfunc.dll | IIS management functions | None
php_imap.dll | IMAP POP3 and NNTP functions | None
php_ingres.dll | Ingres II functions | Requires: Ingres II libraries
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled)
php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dll | Multi-Byte String functions | None
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll
php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled)
php_ming.dll | Ming functions for Flash | None
php_msql.dll | mSQL functions | Requires: msql.dll (bundled)
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled)
php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled)
php_oracle.dll | Oracle functions | Requires: Oracle 7 client libraries
php_overload.dll | Object overloading functions | Built in since PHP 4.3.0
php_pdf.dll | PDF functions | None
php_pgsql.dll | PostgreSQL functions | None
php_printer.dll | Printer functions | None
php_shmop.dll | Shared Memory functions | None
php_snmp.dll | SNMP get and walk functions | NT only!
php_soap.dll | SOAP functions | PHP >= 5.0.0
php_sockets.dll | Socket functions | None
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries
php_tidy.dll | Tidy functions | PHP >= 5.0.0
php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0
php_w32api.dll | W32api functions | None
php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dll | XSLT 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.dll | YAZ functions | Requires: yaz.dll (bundled)
php_zip.dll | Zip File functions | Read only access
php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0

Prev | Home | Next
Building from source | Up | Installation of PECL extensions


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.

Prev | Home | Next
ActiveScript | Up | Apache 1.3.x on Microsoft Windows


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

Prev | Home | Next
Installation on Windows systems | Up | Manual Installation Steps


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 commandline 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 webserver from the table of contents.

Prev | Home | Next
Windows Installer (PHP 5.2 and later) | Up | ActiveScript


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.

Prev | Home | Next
Sun, iPlanet and Netscape servers on Microsoft Windows | Up | Sambar Server on Microsoft Windows


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.

Prev | Home | Next
OmniHTTPd Server | Up | Xitami on Microsoft Windows


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 webservers 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 webserver config 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 webserver. 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 webserver 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 webserver without any valid CGI variables!

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

Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver 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 webserver and insert the result in the webpage. 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!!!

Prev | Home | Next
Apache 2.0.x on Microsoft Windows | Up | OmniHTTPd Server


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 webserver is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

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

  • In Filter command or script put the path and name of your PHP 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.

Prev | Home | Next
Sambar Server on Microsoft Windows | Up | Building from source


PHP and Zend Engine Internals

PHP Manual
Prev Next

VII. PHP and Zend Engine Internals

If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.

Table of Contents
44. Streams API for PHP Extension Authors
45. PDO Driver How-To
46. Zend API: Hacking the Core of PHP
47. TSRM API
48. Extending PHP 3

Prev | Home | Next
zlib_get_coding_type |  | Streams API for PHP Extension Authors


PDO Driver How-To

PHP Manual
Prev Next

Chapter 45. PDO Driver How-To

Table of Contents
A brief note about this How-To
Prerequisites
Preparation and Housekeeping
Fleshing out your skeleton
Building
Testing
Packaging and distribution
pdo_dbh_t definition
pdo_stmt_t definition
Constants
Error handling

A brief note about this How-To

The original version of this PDO driver specification was written by Bill Abt and Rick McGuire of IBM and contributed to the PHP community to assist in the development of drivers for more databases and to encourage the emerging standard for database access in PHP.

Prev | Home | Next
Stream open options | Up | Prerequisites


Building

The build process is designed to work with PEAR (see http://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:

Before first build:

$ sudo pear install PDO

For each build:

$ cd pdo_SKEL
$ phpize
$ ./configure
$ make
$ sudo make install

The process can then be repeated as necessary during the development process.

Prev | Home | Next
Fleshing out your skeleton | Up | Testing


Constants

Table 45-1. Database and Statement Attributes Table

Attribute

Valid value(s)

PDO_ATTR_AUTOCOMMIT

BOOL

TRUE if autocommit is set, FALSE otherwise.

dbh->auto_commit contains value. Processed by PDO directly.

PDO_ATTR_PREFETCH

LONG

Value of the prefetch size in drivers that support it.

PDO_ATTR_TIMEOUT

LONG

How long to wait for a db operation before timing out.

PDO_ATTR_ERRMODE

LONG

Processed and handled by PDO

PDO_ATTR_SERVER_VERSION

STRING

The "human-readable" string representing the Server/Version this driver is currently connected to.

PDO_ATTR_CLIENT_VERSION

STRING

The "human-readable" string representing the Client/Version this driver supports.

PDO_ATTR_SERVER_INFO

STRING

The "human-readable" description of the Server.

PDO_ATTR_CONNECTION_STATUS

LONG

Values not yet defined

PDO_ATTR_CASE

LONG

Processed and handled by PDO.

PDO_ATTR_CURSOR_NAME

STRING

String representing the name for a database cursor for use in "where current in <name>" SQL statements.

PDO_ATTR_CURSOR

LONG

PDO_CURSOR_FWDONLY

Forward only cursor

PDO_CURSOR_SCROLL

Scrollable cursor

The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.

Prev | Home | Next
pdo_stmt_t definition | Up | Error handling


Error handling

Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO than an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.

The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default "Unknown Message" value will be used.

In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:

  1. A native error code. This will frequently be an error code obtained from the database API.

  2. A descriptive string. This string can contain anything additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.

Prev | Home | Next
Constants | Up | Zend API: Hacking the Core of PHP


Fleshing out your skeleton

Major Structures and Attributes

The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.

pdo_SKEL.c: PHP extension glue

function entries

static function_entry pdo_SKEL_functions[] = {
  { NULL, NULL, NULL }
};

This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.

Module entry

/* {{{ pdo_SKEL_module_entry */
#if ZEND_EXTENSION_API_NO >= 220050617
static zend_module_dep pdo_SKEL_deps[] = {
    ZEND_MOD_REQUIRED("pdo")
    {NULL, NULL, NULL}
};
#endif
/* }}} */

zend_module_entry pdo_SKEL_module_entry = {
#if ZEND_EXTENSION_API_NO >= 220050617
    STANDARD_MODULE_HEADER_EX, NULL,
    pdo_SKEL_deps,
#else
    STANDARD_MODULE_HEADER,
#endif
    "pdo_SKEL",
    pdo_SKEL_functions,
    PHP_MINIT(pdo_SKEL),
    PHP_MSHUTDOWN(pdo_SKEL),
    NULL,
    NULL,
    PHP_MINFO(pdo_SKEL),
    PHP_PDO_<DB>_MODULE_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_PDO_<DB>
ZEND_GET_MODULE(pdo_db)
#endif

A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.

Standard PHP Module Extension Functions

PHP_MINIT_FUNCTION

/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_SKEL)
{
    return php_pdo_register_driver(&pdo_SKEL_driver);
}
/* }}} */

This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.

PHP_MSHUTDOWN_FUNCTION

/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_SKEL)
{
    php_pdo_unregister_driver(&pdo_SKEL_driver);
    return SUCCESS;
}
/* }}} */

This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.

PHP_MINFO_FUNCTION

This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.

SKEL_driver.c: Driver implementation

This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.

pdo_SKEL_error

static int pdo_SKEL_error(pdo_dbh_t *dbh,
  pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)

The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error "HY000". The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.

file

The source file where the error occurred or NULL if not available.

line

The line number within the source file if available.

If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.

Example 45-1. Example macros for invoking pdo_SKEL_error

#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)

For more info on error handling, see the Section called Error handling.

Note: Despite being documented here, the PDO driver interface does not specify that his function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.

pdo_SKEL_fetch_error_func

static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt,
    zval *info TSRMLS_DC)

The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.

info

A hash table containing error codes and messages.

The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.

/* now add the error information. */
/* These need to be added in a specific order */
add_next_index_long(info, error_code);   /* driver specific error code */
add_next_index_string(info, message, 0); /* readable error message */

This function should return 1 if information is available, 0 if the driver does not have additional info.

SKEL_handle_closer

static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to close an open database.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.

SKEL_handle_preparer

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)

This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

Stmt

Pointer to the returned statement or NULL if an error occurs.

driver_options

Any driver specific/defined options.

This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.

PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.

One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.

Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involved some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.

Example 45-2. Using pdo_parse_params

int ret;
    char *nsql = NULL;
    int nsql_len = 0;

    /* before we prepare, we need to peek at the query; if it uses named parameters,
     * we want PDO to rewrite them for us */
    stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
    ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);

    if (ret == 1) {
        /* query was re-written */
        sql = nsql;
    } else if (ret == -1) {
        /* couldn't grok it */
        strcpy(dbh->error_code, stmt->error_code);
        return 0;
    }

    /* now proceed to prepare the query in "sql" */

Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:

Example 45-3. implementing preparer for drivers that don't support native prepared statements

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
    long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
    pdo_SKEL_db_handle *H = (pdo_SKEL_db_handle *)dbh->driver_data;
    pdo_SKEL_stmt *S = ecalloc(1, sizeof(pdo_SKEL_stmt));

    S->H = H;
    stmt->driver_data = S;
    stmt->methods = &SKEL_stmt_methods;
    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;

    return 1;
}

This function returns 1 on success or 0 on failure.

SKEL_handle_doer

static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)

This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

This function returns 1 on success or 0 on failure.

SKEL_handle_quoter

static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted,
  int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC)

This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.

dbh

Pointer to the database handle initialized by the handle factory

unquoted

Pointer to a character string containing the string to be quoted.

unquoted_len

The length of the string to be quoted.

quoted

Pointer to the address where a pointer to the newly quoted string will be returned.

quoted_len

The length of the new string.

param_type

A driver specific hint for driver that have alternate quoting styles

This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.

If your driver does not support native prepared statements, implementation of this function is required.

This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.

SKEL_handle_begin

static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to begin a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_commit

static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to end a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_rollback

static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to rollback a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_get_attribute

static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)

This function will be called by PDO to retrieve a database attribute.

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Table 45-1 for valid attributes.

return_value

The returned value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_set_attribute

static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Table 45-1 for valid attributes.

val

The new value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_last_id

static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC)

This function will be called by PDO to retrieve the ID of the last inserted row.

dbh

Pointer to the database handle initialized by the handle factory

name

string representing a table or sequence name.

len

the length of the name parameter.

This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.

SKEL_check_liveness

static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.

dbh

Pointer to the database handle initialized by the handle factory

This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.

Note: This is an optional function.

SKEL_get_driver_methods

static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)

This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.

dbh

Pointer to the database handle initialized by the handle factory

kind

One of the following:

PDO_DBH_DRIVER_METHOD_KIND_DBH

Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.

PDO_DBH_DRIVER_METHOD_KIND_STMT

Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.

This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.

SKEL_handle_factory

static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC)

This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.

dbh

Pointer to the database handle initialized by the handle factory

driver_options

An array of driver options, keyed by integer option number. See Table 45-1 for a list of possible attributes.

This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.

PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.

Driver method table

A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

pdo_SKEL_driver

A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.

SKEL_statement.c: Statement implementation

This unit implements all of the database statement handling methods that support the PDO statement object.

SKEL_stmt_dtor

static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to destroy a previously constructed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.

SKEL_stmt_execute

static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to execute the prepared SQL statement in the passed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_fetch

static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
   long offset TSRMLS_DC)

This function will be called by PDO to fetch a row from a previously executed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

ori

One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.

offset

If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.

The results of this fetch are driver dependent and the data is usually stored in the driver_data member of pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_param_hook

static int SKEL_stmt_param_hook(pdo_stmt_t *stmt,
  struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC)

This function will be called by PDO for handling of both bound parameters and bound columns.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

param

The structure describing either a statement parameter or a bound column.

event_type

The type of event to occur for this parameter, one of the following:

PDO_PARAM_EVT_ALLOC

Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.

PDO_PARAM_EVT_FREE

Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.

PDO_PARAM_EXEC_PRE

Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.

PDO_PARAM_EXEC_POST

Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.

PDO_PARAM_FETCH_PRE

Called once for each parameter immediately prior to calling SKEL_stmt_fetch.

PDO_PARAM_FETCH_POST

Called once for each parameter immediately after calling SKEL_stmt_fetch.

This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.

For all other events, PDO may call you multiple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.

If this is a bound parameter, the is_param flag in the param structure, otherwise, the param structure refers to a bound column.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_describe_col

static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC)

This function will be called by PDO to query information about a particular column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_get_col_data

static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno,
  char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)

This function will be called by PDO to retrieve data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

ptr

Pointer to the retrieved data.

len

The length of the data pointed to by ptr.

caller_frees

If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.

The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_set_attr

static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to allow the setting of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Table 45-1 for valid attributes.

val

The new value for the attribute.

This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_attr

static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval
   *return_value TSRMLS_DC)

This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Table 45-1 for valid attributes.

return_value

The returned value for the attribute.

This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_col_meta

static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno,
   zval *return_value TSRMLS_DC)

Warning

This function is not well defined and is subject to change.

This function will be called by PDO to retrieve meta-data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number for which data is to be retrieved.

return_value

Holds the returned meta data.

The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.

Statement handling method table

A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

Prev | Home | Next
Preparation and Housekeeping | Up | Building


Packaging and distribution

Creating a package

PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:

$ pear package

This will create a tarball named PDO_SKEL-X.Y.Z.tgz.

Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:

$ pear build package.xml

Once this is proven to work, you can test installation:

$ pear package
$ sudo pear install PDO_SKEL-X.Y.X.tgz

Full details about package.xml can be found in the PEAR Programmer's documentation (http://pear.php.net/manual/).

Releasing the package

A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at http://pecl.php.net/index.php.

Prev | Home | Next
Testing | Up | pdo_dbh_t definition


pdo_dbh_t definition

All fields should be treated as read-only by the driver, unless explicitly stated otherwise.

Figure 45-1. pdo_dbh_t

/* represents a connection to a database */
struct _pdo_dbh_t {
    /* driver specific methods */
    struct pdo_dbh_methods *methods;      (1)
    /* driver specific data */
    void *driver_data;                    (2)

    /* credentials */
    char *username, *password;            (3)

    /* if true, then data stored and pointed at by this handle must all be
     * persistently allocated */
    unsigned is_persistent:1;             (4)

    /* if true, driver should act as though a COMMIT were executed between
     * each executed statement; otherwise, COMMIT must be carried out manually
     * */
    unsigned auto_commit:1;               (5)

    /* if true, the driver requires that memory be allocated explicitly for
     * the columns that are returned */
    unsigned alloc_own_columns:1;         (6)

    /* if true, commit or rollBack is allowed to be called */
    unsigned in_txn:1;

    /* max length a single character can become after correct quoting */
    unsigned max_escaped_char_length:3;     (7)

    /* data source string used to open this handle */
    const char *data_source;              (8)
    unsigned long data_source_len;

    /* the global error code. */
    pdo_error_type error_code;            (9)

    enum pdo_case_conversion native_case  (10) , desired_case;
};
The driver must set this during SKEL_handle_factory().
This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
The username and password that were passed into the PDO constructor. The driver should use these values when it initiates a connection to the database.
If this is set to 1, then any data that is referenced by the dbh, including whatever structure your driver allocates, MUST be allocated persistently. This is easy to achieve; rather than using the usual emalloc() simply use pemalloc() and pass the value of this flag as the last parameter. Failure to use the appropriate kind of memory can lead to serious memory faults, resulting (in the best case) a hard crash, and in the worst case, an exploitable memory problem.

If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.

You should check this value in your SKEL_handle_doer() and SKEL_stmt_execute() functions; if it evaluates to true, you must attempt to commit the query now. Most database implementations offer an auto-commit mode that handles this automatically.
If your database client library API operates by fetching data into a caller-supplied buffer, you should set this flag to 1 during your SKEL_handle_factory(). When set, PDO will call your SKEL_stmt_describer() earlier that it would otherwise. This early call allows you to determine those buffer sizes and issue appropriate calls to the database client library.

If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.

If your driver doesn't support native prepared statements (supports_placeholders is set to PDO_PLACEHOLDER_NONE), you must set this value to the maximum length that can be taken up by a single character when it is quoted by your SKEL_handle_quoter() function. This value is used to calculate the amount of buffer space required when PDO it executes the statement.
This holds the value of the DSN that was passed into the PDO constructor. If your driver implementation needed to modify the DSN for whatever reason, it should update this member during SKEL_handle_factory(). Modifying this member should be avoided. If you do change it, you must ensure that data_source_len is also correct.
Whenever an error occurs during a call to one of your driver methods, you should set this member to the SQLSTATE code that best describes the error and return an error. In this HOW-TO, the suggested practice is to call SKEL_handle_error() when an error is detected, and have it set the error code.
Your driver should set this during SKEL_handle_factory(); the value should reflect how the database returns the names of the columns in result sets. If the name matches the case that was used in the query, set it to PDO_CASE_NATURAL (this is actually the default). If the column names are always returned in upper case, set it to PDO_CASE_UPPER. If the column names are always return in lower case, set it to PDO_CASE_LOWER. The value you set it used to determine if PDO should perform case folding when the user sets the PDO_ATTR_CASE attribute.

Prev | Home | Next
Packaging and distribution | Up | pdo_stmt_t definition


pdo_stmt_t definition

All fields should be treated as read-only unless explicitly stated otherwise.

Figure 45-2. pdo_stmt_t

/* represents a prepared statement */
struct _pdo_stmt_t {
    /* driver specifics */
    struct pdo_stmt_methods *methods;     (1)
    void *driver_data;                    (2)

    /* if true, we've already successfully executed this statement at least
     * once */
    unsigned executed:1;                  (3)
    /* if true, the statement supports placeholders and can implement
     * bindParam() for its prepared statements, if false, PDO should
     * emulate prepare and bind on its behalf */
    unsigned supports_placeholders:2;     (4)

    /* the number of columns in the result set; not valid until after
     * the statement has been executed at least once.  In some cases, might
     * not be valid until fetch (at the driver level) has been called at least once.
     * */
    int column_count;                     (5)
    struct pdo_column_data *columns;      (6)

    /* points at the dbh that this statement was prepared on */
    pdo_dbh_t *dbh;

    /* keep track of bound input parameters.  Some drivers support
     * input/output parameters, but you can't rely on that working */
    HashTable *bound_params;
    /* When rewriting from named to positional, this maps positions to names */
    HashTable *bound_param_map;
    /* keep track of PHP variables bound to named (or positional) columns
     * in the result set */
    HashTable *bound_columns;

    /* not always meaningful */
    long row_count;

    /* used to hold the statement's current query */
    char *query_string;
    int query_stringlen;

    /* the copy of the query with expanded binds ONLY for emulated-prepare drivers */
    char *active_query_string;
    int active_query_stringlen;

    /* the cursor specific error code. */
    pdo_error_type error_code;

    /* used by the query parser for driver specific
     * parameter naming (see pgsql driver for example) */
    const char *named_rewrite_template;
};
The driver must set this during SKEL_handle_preparer().
This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
This is set by PDO after the statement has been executed for the first time. Your driver can inspect this value to determine if it can skip one-time actions as an optimization.
Discussed in more detail in the Section called SKEL_handle_preparer
Your driver is responsible for setting this field to the number of columns available in a result set. This is usually set during SKEL_stmt_execute() but with some database implementations, the column count may not be available until SKEL_stmt_fetch() has been called at least once. Drivers that SKEL_stmt_next_rowset() should update the column count when a new rowset is available.
PDO will allocate this field based on the value that you set for the column count. You are responsible for populating each column during SKEL_stmt_describe(). You must set the precision, maxlen, name, namelen and param_type members for each column. The name is expected to be allocated using emalloc(); PDO will efree() at the appropriate time.

Prev | Home | Next
pdo_dbh_t definition | Up | Constants


Preparation and Housekeeping

Source directory layout

The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.

pdo_SKEL/
  config.m4                    (1)
  config.w32                   (2)
  CREDITS
  package.xml                  (3)
  pdo_SKEL.c             (4)
  php_pdo_SKEL.h
  php_pdo_SKEL_int.h     (5)
  SKEL_dbh.c             (6)
  SKEL_stmt.c            (7)
unix build script
win32 build script
meta information about the package
standard PHP extension glue
driver private header
contains the implementation of the PDO driver interface
contains the implementation of the PDO statement interface

The contents of these files are defined later in this document.

Creating a skeleton

The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:

./ext_skel --extname=pdo_SKEL

This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory . PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.

Standard Includes

Build Specific Headers

The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.

PHP Headers

The following standard public php headers should be included in each source module:

  1. php.h

  2. php_ini.h

  3. ext/standard/info.h

PDO Interface Headers

The following standard public PDO header files are also included in each source module:

pdo/php_pdo.h

This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.

pdo/php_pdo_driver.h

This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.

Driver Specific Headers

The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:

php_pdo_SKEL.h

This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.

php_pdo_SKEL_int.h

This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specific definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.

Optional Headers

Depending on the implementation details for a particular driver it may be necessary to include the following header:

#include <zend_exceptions.h>

Prev | Home | Next
Prerequisites | Up | Fleshing out your skeleton


Prerequisites

The following is list of prerequisites and assumptions needed for writing a PDO database driver:

  1. A working target database, examples, demos, etc. working as per vendor specifications;

  2. A working development environment:

    1. Other Unix: standard development tools supplied by vendor plus the GNU development tool set;

    2. Win32: Visual Studio compiler suite;

    3. Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;

  3. A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;

  4. A working PDO environment (can be installed using 'sudo pear install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;

  5. A good working knowledge of the 'C' programming language;

  6. A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;

  7. Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.

Prev | Home | Next
PDO Driver How-To | Up | Preparation and Housekeeping


Testing

PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:

$ cp -r pdo_SKEL /path/to/php-5.1/ext

This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:

--TEST--
SKEL
--SKIPIF--
<?php # vim:ft=php
if (!extension_loaded('pdo_SKEL')) print 'skip'; ?>
--REDIRECTTEST--
if (false !== getenv('PDO_SKEL_TEST_DSN')) {
# user set them from their shell
   $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN');
   $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER');
   $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS');
   if (false !== getenv('PDO_SKEL_TEST_ATTR')) {
      $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR');
   }
   return $config;
}
return array(
   'ENV' => array(
           'PDOTEST_DSN' => 'SKEL:dsn',
           'PDOTEST_USER' => 'username',
           'PDOTEST_PASS' => 'password'
       ),
   'TESTS' => 'ext/pdo/tests'
   );

This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.

The test harness can be invoked as follows:

$ cd /path/to/php-5.1
$ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \
 PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test

Prev | Home | Next
Building | Up | Packaging and distribution


SWFAction

(PHP 4 >= 4.0.5)

SWFAction -- SWFAction Class

Description

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break

  • for

  • continue

  • if

  • else

  • do

  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()

Returns the number of milliseconds (?) elapsed since the movie started.

random(seed)

Returns a pseudo-random number in the range 0-seed.

length(expr)

Returns the length of the given expression.

int(number)

Returns the given number rounded down to the nearest integer.

concat(expr, expr)

Returns the concatenation of the given expressions.

ord(expr)

Returns the ASCII code for the given character

chr(num)

Returns the character for the given ASCII code

substr(string, location, length)

Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)

Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.

removeClip(expr)

Removes the named movie clip.

trace(expr)

Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.

startDrag(target, lock, [left, top, right, bottom])

Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.

stopDrag()

Stop dragging my heart around. And this movie clip, too.

callFrame(expr)

Call the named frame as a function.

getURL(url, target, [method])

Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.

loadMovie(url, target)

Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).

nextFrame()

Go to the next frame.

prevFrame()

Go to the last (or, rather, previous) frame.

play()

Start playing the movie.

stop()

Stop playing the movie.

toggleQuality()

Toggle between high and low quality.

stopSounds()

Stop playing all sounds.

gotoFrame(num)

Go to frame number num. Frame numbers start at 0.

gotoFrame(name)

Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.

setTarget(expr)

Sets the context for action. Or so they say- I really have no idea what this does.

And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x

  • y

  • xScale

  • yScale

  • currentFrame - (read-only)

  • totalFrames - (read-only)

  • alpha - transparency level

  • visible - 1=on, 0=off (?)

  • width - (read-only)

  • height - (read-only)

  • rotation

  • target - (read-only) (???)

  • framesLoaded - (read-only)

  • name

  • dropTarget - (read-only) (???)

  • url - (read-only) (???)

  • highQuality - 1=high, 0=low (?)

  • focusRect - (???)

  • soundBufTime - (???)

So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a Unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

Class Members

Methods

SWFAction->__construct()

Examples

This simple example will move the red square across the window.

Example 1. swfaction() example

&#60;?php
  $s = new SWFShape();
  $f = $s-&#62;addFill(0xff, 0, 0);
  $s-&#62;setRightFill($f);

  $s-&#62;movePenTo(-500, -500);
  $s-&#62;drawLineTo(500, -500);
  $s-&#62;drawLineTo(500, 500);
  $s-&#62;drawLineTo(-500, 500);
  $s-&#62;drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p-&#62;add($s);
  $i-&#62;setDepth(1);
  $p-&#62;nextFrame();

  for ($n=0; $n&#60;5; ++$n) {
    $i-&#62;rotate(-15);
    $p-&#62;nextFrame();
  }

  $m = new SWFMovie();
  $m-&#62;setBackground(0xff, 0xff, 0xff);
  $m-&#62;setDimension(6000, 4000);

  $i = $m-&#62;add($p);
  $i-&#62;setDepth(1);
  $i-&#62;moveTo(-500,2000);
  $i-&#62;setName("box");

  $m-&#62;add(new SWFAction("/box.x += 3;"));
  $m-&#62;nextFrame();
  $m-&#62;add(new SWFAction("gotoFrame(0); play();"));
  $m-&#62;nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m-&#62;output();
?&#62;

This simple example tracks down your mouse on the screen.

Example 2. swfaction() example

&#60;?php

  $m = new SWFMovie();
  $m-&#62;setRate(36.0);
  $m-&#62;setDimension(1200, 800);
  $m-&#62;setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m-&#62;add(new SWFSprite());
  $i-&#62;setName('mouse');

  $m-&#62;add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m-&#62;add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r-&#62;getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s-&#62;setLeftFill($s-&#62;addFill(0xff, 0xff, 0xff));
  $s-&#62;movePenTo(-40, -40);
  $s-&#62;drawLine(80, 0);
  $s-&#62;drawLine(0, 80);
  $s-&#62;drawLine(-80, 0);
  $s-&#62;drawLine(0, -80);

  $s = $r-&#62;getShape2();

  $s-&#62;setLeftFill($s-&#62;addFill(0x00, 0x00, 0x00));
  $s-&#62;movePenTo(-1, -1);
  $s-&#62;drawLine(2, 0);
  $s-&#62;drawLine(0, 2);
  $s-&#62;drawLine(-2, 0);
  $s-&#62;drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box-&#62;add(new SWFAction("
    stop();
  "));
  $i = $box-&#62;add($r);

  for ($n=0; $n&#60;=20; ++$n) {
    $i-&#62;setRatio($n/20);
    $box-&#62;nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell-&#62;add($box);
  $i-&#62;setName('box');

  $cell-&#62;add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell-&#62;nextFrame();
  $cell-&#62;add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell-&#62;nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x&#60;12; ++$x) {
    for ($y=0; $y&#60;8; ++$y) {
      $i = $m-&#62;add($cell);
      $i-&#62;moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m-&#62;nextFrame();

  $m-&#62;add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m-&#62;output();
?&#62;

Same as above, but with nice colored balls...

Example 3. swfaction() example

&#60;?php

  $m = new SWFMovie();
  $m-&#62;setDimension(11000, 8000);
  $m-&#62;setBackground(0x00, 0x00, 0x00);

  $m-&#62;add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m-&#62;add($t);
  $i-&#62;setName('mouse');

  $g = new SWFGradient();
  $g-&#62;addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g-&#62;addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g-&#62;addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g-&#62;addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s-&#62;addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f-&#62;scaleTo(0.03);
  $s-&#62;setRightFill($f);
  $s-&#62;movePenTo(-600, -600);
  $s-&#62;drawLine(1200, 0);
  $s-&#62;drawLine(0, 1200);
  $s-&#62;drawLine(-1200, 0);
  $s-&#62;drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p-&#62;add($s);
  $p-&#62;nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q-&#62;add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q-&#62;add($p);

  $i-&#62;multColor(1.0, 1.0, 1.0);
  $q-&#62;nextFrame();
  $i-&#62;multColor(1.0, 0.5, 0.5);
  $q-&#62;nextFrame();
  $i-&#62;multColor(1.0, 0.75, 0.5);
  $q-&#62;nextFrame();
  $i-&#62;multColor(1.0, 1.0, 0.5);
  $q-&#62;nextFrame();
  $i-&#62;multColor(0.5, 1.0, 0.5);
  $q-&#62;nextFrame();
  $i-&#62;multColor(0.5, 0.5, 1.0);
  $q-&#62;nextFrame();
  $i-&#62;multColor(1.0, 0.5, 1.0);
  $q-&#62;nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p-&#62;add($q);
  $i-&#62;setName('frames');
  $p-&#62;add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p-&#62;nextFrame();

  $p-&#62;add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p-&#62;nextFrame();

  $p-&#62;add(new SWFAction("prevFrame(); play();"));
  $p-&#62;nextFrame();

  $i = $m-&#62;add($p);
  $i-&#62;setName('frames');
  $m-&#62;nextFrame();

  $m-&#62;add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' &#38; num);
duplicateClip(/frames, 'char' &#38; num, num);

  "));

  $m-&#62;nextFrame();
  $m-&#62;add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m-&#62;output();
?&#62;

Prev | Home | Next
Ming functions for Flash | Up | SWFAction->__construct()


SWFBitmap

(PHP 4 >= 4.0.5)

SWFBitmap -- SWFBitmap Class

Description

Class Members

Methods

SWFBitmap->__construct()
SWFBitmap->getHeight()
SWFBitmap->getWidth()

Prev | Home | Next
SWFAction->__construct() | Up | SWFBitmap->__construct()


SWFButton

(PHP 4 >= 4.0.5)

SWFButton -- SWFButton Class

Description

Class Members

Methods

SWFButton->__construct()
SWFButton->addAction()
SWFButton->addASound()
SWFButton->addShape()
SWFButton->setAction()
SWFButton->setDown()
SWFButton->setHit()
SWFButton->setMenu()
SWFButton->setOver()
SWFButton->setUp()

Prev | Home | Next
SWFBitmap->getWidth() | Up | SWFButton->__construct()


SWFDisplayItem

(no version information, might be only in CVS)

SWFDisplayItem -- SWFDisplayItem Class

Description

Class Members

Methods

SWFDisplayItem->addAction()
SWFDisplayItem->addColor()
SWFDisplayItem->endMask()
SWFDisplayItem->getRot()
SWFDisplayItem->getX()
SWFDisplayItem->getXScale()
SWFDisplayItem->getXSkew()
SWFDisplayItem->getY()
SWFDisplayItem->getYScale()
SWFDisplayItem->getYSkew()
SWFDisplayItem->move()
SWFDisplayItem->moveTo()
SWFDisplayItem->multColor()
SWFDisplayItem->remove()
SWFDisplayItem->rotate()
SWFDisplayItem->rotateTo()
SWFDisplayItem->scale()
SWFDisplayItem->scaleTo()
SWFDisplayItem->setDepth()
SWFDisplayItem->setMaskLevel()
SWFDisplayItem->setMatrix()
SWFDisplayItem->setName()
SWFDisplayItem->setRatio()
SWFDisplayItem->skewX()
SWFDisplayItem->skewXTo()
SWFDisplayItem->skewY()
SWFDisplayItem->skewYTo()

Prev | Home | Next
SWFButton->setUp() | Up | SWFDisplayItem->addAction()


SWFFill

(PHP 4 >= 4.0.5)

SWFFill -- SWFFill Class

Description

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape->addFill() method.

Class Members

Methods

SWFFill->moveTo()
SWFFill->rotateTo()
SWFFill->scaleTo()
SWFFill->skewXTo()
SWFFill->skewYTo()

Prev | Home | Next
SWFDisplayItem->skewYTo() | Up | SWFFill->moveTo()


SWFFont

(PHP 4 >= 4.0.5)

SWFFont -- SWFFont Class

Description

The SWFFont object represent a reference to the font definition, for us with SWFText->setFont() and SWFTextField->setFont().

Class Members

Methods

SWFFont->__construct()
SWFFont->getAscent()
SWFFont->getDescent()
SWFFont->getLeading()
SWFFont->getShape()
SWFFont->getUTF8Width()
SWFFont->getWidth()

Prev | Home | Next
SWFFill->skewYTo() | Up | SWFFont->__construct()


SWFFontChar

(no version information, might be only in CVS)

SWFFontChar -- SWFFontChar Class

Description

Class Members

Methods

SWFFontChar->addChars()
SWFFontChar->addUTF8Chars()

Prev | Home | Next
SWFFont->getWidth() | Up | SWFFontChar->addChars()


SWFGradient

(PHP 4 >= 4.0.5)

SWFGradient -- SWFGradient Class

Description

Class Members

Methods

SWFGradient->__construct()
SWFGradient->addEntry()

Prev | Home | Next
SWFFontChar->addUTF8Chars() | Up | SWFGradient->__construct()


SWFMorph

(PHP 4 >= 4.0.5)

SWFMorph -- SWFMorph Class

Description

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

Class Members

Methods

SWFMorph->__construct()
SWFMorph->getShape1()
SWFMorph->getShape2()

Prev | Home | Next
SWFGradient->addEntry() | Up | SWFMorph->__construct()


SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- SWFMovie Class

Description

SWFMovie is a movie object representing an SWF movie.

Class Members

Methods

SWFMovie->__construct()
SWFMovie->add()
SWFMovie->addExport()
SWFMovie->addFont()
SWFMovie->importChar()
SWFMovie->importFont()
SWFMovie->labelFrame()
SWFMovie->nextFrame()
SWFMovie->output()
SWFMovie->remove()
SWFMovie->save()
SWFMovie->saveToFile()
SWFMovie->setbackground()
SWFMovie->setDimension()
SWFMovie->setFrames()
SWFMovie->setRate()
SWFMovie->startSound()
SWFMovie->stopSound()
SWFMovie->streamMP3()
SWFMovie->writeExports()

Prev | Home | Next
SWFMorph->getShape2() | Up | SWFMovie->__construct()


SWFPrebuiltClip

(no version information, might be only in CVS)

SWFPrebuiltClip -- SWFPrebuiltClip Class

Description

Class Members

Methods

SWFPrebuiltClip->__construct()

Prev | Home | Next
SWFMovie->writeExports() | Up | SWFPrebuiltClip->__construct()


SWFShape

(PHP 4 >= 4.0.5)

SWFShape -- SWFShape Class

Description

Class Members

Methods

SWFShape->__construct()
SWFShape->addFill()
SWFShape->drawArc()
SWFShape->drawCircle()
SWFShape->drawCubic()
SWFShape->drawCubicTo()
SWFShape->drawCurve()
SWFShape->drawCurveTo()
SWFShape->drawGlyph()
SWFShape->drawLine()
SWFShape->drawLineTo()
SWFShape->movePen()
SWFShape->movePenTo()
SWFShape->setLeftFill()
SWFShape->setLine()
SWFShape->setRightFill()

Prev | Home | Next
SWFPrebuiltClip->__construct() | Up | SWFShape->__construct()


SWFSound

(no version information, might be only in CVS)

SWFSound -- SWFSound Class

Description

Class Members

Methods

SWFSound

Prev | Home | Next
SWFShape->setRightFill() | Up | SWFSound


SWFSoundInstance

(no version information, might be only in CVS)

SWFSoundInstance -- SWFSoundInstance Class

Description

SWFSoundInstance objects are returned by the SWFSprite->startSound() and SWFMovie->startSound() methods.

Class Members

Methods

SWFSoundInstance->loopCount()
SWFSoundInstance->loopInPoint()
SWFSoundInstance->loopOutPoint()
SWFSoundInstance->noMultiple()

Prev | Home | Next
SWFSound | Up | SWFSoundInstance->loopCount()


SWFSprite

(PHP 4 >= 4.0.5)

SWFSprite -- SWFSprite Class

Description

An SWFSprite is also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

Class Members

Methods

SWFSprite->__construct()
SWFSprite->add()
SWFSprite->labelFrame()
SWFSprite->nextFrame()
SWFSprite->remove()
SWFSprite->setFrames()
SWFSprite->startSound()
SWFSprite->stopSound()

Examples

This simple example will spin gracefully a big red square.

Example 1. swfsprite() example

&#60;?php
$s = new SWFShape();
$s-&#62;setRightFill($s-&#62;addFill(0xff, 0, 0));
$s-&#62;movePenTo(-500, -500);
$s-&#62;drawLineTo(500, -500);
$s-&#62;drawLineTo(500, 500);
$s-&#62;drawLineTo(-500, 500);
$s-&#62;drawLineTo(-500, -500);

$p = new SWFSprite();
$i = $p-&#62;add($s);
$p-&#62;nextFrame();
$i-&#62;rotate(15);
$p-&#62;nextFrame();
$i-&#62;rotate(15);
$p-&#62;nextFrame();
$i-&#62;rotate(15);
$p-&#62;nextFrame();
$i-&#62;rotate(15);
$p-&#62;nextFrame();
$i-&#62;rotate(15);
$p-&#62;nextFrame();

$m = new SWFMovie();
$i = $m-&#62;add($p);
$i-&#62;moveTo(1500, 1000);
$i-&#62;setName("blah");

$m-&#62;setBackground(0xff, 0xff, 0xff);
$m-&#62;setDimension(3000, 2000);

header('Content-type: application/x-shockwave-flash');
$m-&#62;output();
?&#62;

Prev | Home | Next
SWFSoundInstance->noMultiple() | Up | SWFSprite->__construct()


SWFText

(PHP 4 >= 4.0.5)

SWFText -- SWFText Class

Description

Class Members

Methods

SWFText->__construct()
SWFText->addString()
SWFText->addUTF8String()
SWFText->getAscent()
SWFText->getDescent()
SWFText->getLeading()
SWFText->getUTF8Width()
SWFText->getWidth()
SWFText->moveTo()
SWFText->setColor()
SWFText->setFont()
SWFText->setHeight()
SWFText->setSpacing()

Prev | Home | Next
SWFSprite->stopSound() | Up | SWFText->__construct()


SWFTextField

(PHP 4 >= 4.0.5)

SWFTextField -- SWFTextField Class

Description

Class Members

Methods

SWFTextField->__construct()
SWFTextField->addChars()
SWFTextField->addString()
SWFTextField->align()
SWFTextField->setBounds()
SWFTextField->setColor()
SWFTextField->setFont()
SWFTextField->setHeight()
SWFTextField->setIndentation()
SWFTextField->setLeftMargin()
SWFTextField->setLineSpacing()
SWFTextField->setMargins()
SWFTextField->setName()
SWFTextField->setPadding()
SWFTextField->setRightMargin()

Prev | Home | Next
SWFText->setSpacing() | Up | SWFTextField->__construct()


SWFVideoStream

(no version information, might be only in CVS)

SWFVideoStream -- SWFVideoStream Class

Description

Class Members

Methods

SWFVideoStream->__construct()
SWFVideoStream->getNumFrames()
SWFVideoStream->setDimension()

Prev | Home | Next
SWFTextField->setRightMargin() | Up | SWFVideoStream->__construct()


Usage

(no version information, might be only in CVS)

Usage -- Examples on using the ogg:// wrapper.

Examples

Example 1. Reading an OGG/Vorbis file

&#60;?php
dl("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');

/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);

/* Inspect the first song (usually the only song,
   but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];

echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo "  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
    echo "  $comment\n";
}

while ($audio_data = fread($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems,
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?&#62;

Example 2. Encode an audio file to OGG/Vorbis

&#60;?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=&#62;array(
             'pcm_mode' =&#62; OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' =&#62; 44100,                 /* 44kHz CD quality */
             'bitrate' =&#62; 0.5,                /* Midquality VBR */
             'channels' =&#62; 1,                 /* Mono */
             'serialno' =&#62; 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);

$pcm = fopen('mysample.pcm', 'r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);

fclose($pcm);
fclose($ogg);
?&#62;

Prev | Home | Next
oggvorbis | Up | OpenAL Audio Bindings


Alternative PHP Cache

PHP Manual
Prev Next

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.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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

Name | Default | Changeable | Changelog
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_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.ttl | "0" | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12p2
apc.filters | NULL | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM |
apc.file_update_protection | "2" | PHP_INI_SYSTEM |
apc.enable_cli | "0" | PHP_INI_SYSTEM | > APC 3.0.6
apc.max_file_size | "1M" | PHP_INI_SYSTEM | > APC 3.0.6
apc.stat | "1" | PHP_INI_SYSTEM | > APC 3.0.9
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a 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.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
apc_cache_info -- Retrieves cached information (and meta-data) from APC's data store
apc_clear_cache -- Clears the APC cache
apc_define_constants -- Defines a set of constants for later retrieval and mass-definition
apc_delete -- Removes a stored variable from the cache
apc_fetch -- Fetch a stored variable from the cache
apc_load_constants -- Loads a set of constants from the cache
apc_sma_info -- Retrieves APC's Shared Memory Allocation information
apc_store -- Cache a variable in the data store

Prev | Home | Next
virtual | Up | apc_cache_info


Credit Mutuel CyberMUT functions

PHP Manual
Prev Next

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

Prev | Home | Next
cybercash_encr | Up | cybermut_creerformulairecm


enchant Functions

PHP Manual
Prev Next

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

&#60;?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);
?&#62;
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.

Prev | Home | Next
xptr_new_context | Up | enchant_broker_describe


Expect Functions

PHP Manual
Prev Next

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. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.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

Name | Default | Changeable | Changelog
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 G.

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

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.

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

&#60;?php
ini_set ("expect.loguser", "Off");

$stream = fopen ("expect://ssh root@remotehost uptime", "r");

$cases = array (
  array (0 =&#62; "password:", 1 =&#62; 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);
?&#62;
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

Prev | Home | Next
read_exif_data | Up | expect_expectl


Fileinfo Functions

PHP Manual
Prev Next

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

A short installation note: just type

$ pear install fileinfo
in your console.

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

Prev | Home | Next
fdf_set_version | Up | finfo_buffer


Filter Functions

PHP Manual
Prev Next

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

ID | Name | Options | Flags | Description
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" |  |  | 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

Name | Default | Changeable | Changelog
filter.default | unsafe_raw | PHP_INI_PERDIR |
filter.default_flags |  | PHP_INI_PERDIR |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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

Prev | Home | Next
unlink | Up | filter_has_var


GeoIP Functions

PHP Manual
Prev Next

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

Prev | Home | Next
unregister_tick_function | Up | geoip_country_code_by_name


gnupg Functions

PHP Manual
Prev Next

LI. gnupg Functions

Introduction

This module allows you to interact with gnupg.

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

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.

&#60;?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint =&#62; $userid){
    echo $fingerprint." -&#62; ".$userid."\n";
}
?&#62;

Examples

This example will clearsign a given text.

Example 1. gnupg clearsign example (procedural)

&#60;?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("just a test");
echo $signed;
?&#62;

Example 2. gnupg clearsign example (OO)

&#60;?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg-&#62;setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg-&#62;addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg-&#62;sign("just a test");
echo $signed;
?&#62;
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

Prev | Home | Next
gmp_xor | Up | gnupg_adddecryptkey


hash Functions

PHP Manual
Prev Next

LIII. 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.

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)

Prev | Home | Next
gopher_parsedir | Up | hash_algos


IBM DB2, Cloudscape and Apache Derby Functions

PHP Manual
Prev Next

LVIII. 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.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. ibm_db2 Configure Options

Name | Default | Changeable | Changelog
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_name | NULL | PHP_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.

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_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_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

Prev | Home | Next
PDO_IBM DSN | Up | db2_autocommit


Image magick Functions

PHP Manual
Prev Next

LXIV. Image magick Functions

Introduction

Image magick extension lets you create and manipulate images. Its function is similar to Image extension but provides more powerful and faster functions.

Requirements

To use this extension, either "ImageMagick" or "GraphicsMagick" library is required.

Installation

Windows binaries may be found at http://snaps.php.net/. To install, download php_imagick.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_imagick.dll to your php.ini and restarting your webserver.

extension_dir=c:/php5/exts/
extension=php_imagick.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Either:

    • Run the pear installer for PECL/imagick: pecl install imagick

    • Copy imagick.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.

    • Add extension=imagick.so to your php.ini

    Or:

    • Set the path to your php.ini via:

      pecl config-set php_ini /path/to/php.ini

    • Run the pear installer for PECL/imagick: pecl install imagick

  • Restart your webserver to reload your php.ini settings.

Development Versions: There are currently no stable versions of PECL/imagick, to force installation of the beta version of PECL/imagick execute: pecl install imagick-beta

Compiling PECL/imagick without using the PEAR command: Rather than using pecl install imagick to automatically download and install PECL/imagick, you may download the tarball from PECL. From the root of the unpacked tarball, run: phpize && ./configure --enable-imagick && make to generate imagick.so. Once built, continue the installation from step 4 above.

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/imagick.

Resource Types

This extension uses the "imagemagick handle" resource.

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.

IMAGICK_FILTER_UNDEFINED (integer)

IMAGICK_FILTER_POINT (integer)

IMAGICK_FILTER_BOX (integer)

IMAGICK_FILTER_TRIANGLE (integer)

IMAGICK_FILTER_HERMITE (integer)

IMAGICK_FILTER_HANNING (integer)

IMAGICK_FILTER_HAMMING (integer)

IMAGICK_FILTER_BLACKMAN (integer)

IMAGICK_FILTER_GAUSSIAN (integer)

IMAGICK_FILTER_QUADRATIC (integer)

IMAGICK_FILTER_CUBIC (integer)

IMAGICK_FILTER_CATROM (integer)

IMAGICK_FILTER_MITCHELL (integer)

IMAGICK_FILTER_LANCZOS (integer)

IMAGICK_FILTER_BESSEL (integer)

IMAGICK_FILTER_SINC (integer)

IMAGICK_FILTER_UNKNOWN (integer)

IMAGICK_FONTSTYLE_NORMAL (integer)

IMAGICK_FONTSTYLE_ITALIC (integer)

IMAGICK_FONTSTYLE_OBLIQUE (integer)

IMAGICK_FONTSTYLE_ANY (integer)

IMAGICK_RAISE (integer)

IMAGICK_LOWER (integer)

IMAGICK_COMPOSITE_OP_UNDEFINED (integer)

IMAGICK_COMPOSITE_OP_OVER (integer)

IMAGICK_COMPOSITE_OP_IN (integer)

IMAGICK_COMPOSITE_OP_OUT (integer)

IMAGICK_COMPOSITE_OP_ATOP (integer)

IMAGICK_COMPOSITE_OP_XOR (integer)

IMAGICK_COMPOSITE_OP_PLUS (integer)

IMAGICK_COMPOSITE_OP_MINUS (integer)

IMAGICK_COMPOSITE_OP_ADD (integer)

IMAGICK_COMPOSITE_OP_SUBTRACT (integer)

IMAGICK_COMPOSITE_OP_DIFFERENCE (integer)

IMAGICK_COMPOSITE_OP_MULTIPLY (integer)

IMAGICK_COMPOSITE_OP_BUMPMAP (integer)

IMAGICK_COMPOSITE_OP_COPY (integer)

IMAGICK_COMPOSITE_OP_COPYRED (integer)

IMAGICK_COMPOSITE_OP_COPYGREEN (integer)

IMAGICK_COMPOSITE_OP_COPYBLUE (integer)

IMAGICK_COMPOSITE_OP_COPYOPACITY (integer)

IMAGICK_COMPOSITE_OP_CLEAR (integer)

IMAGICK_COMPOSITE_OP_DISSOLVE (integer)

IMAGICK_COMPOSITE_OP_DISPLACE (integer)

IMAGICK_COMPOSITE_OP_MODULATE (integer)

IMAGICK_COMPOSITE_OP_THRESHOLD (integer)

IMAGICK_COMPOSITE_OP_NONE (integer)

IMAGICK_COMPOSITE_OP_DARKEN (integer)

IMAGICK_COMPOSITE_OP_LIGHTEN (integer)

IMAGICK_COMPOSITE_OP_HUE (integer)

IMAGICK_COMPOSITE_OP_SATURATE (integer)

IMAGICK_COMPOSITE_OP_COLORIZE (integer)

IMAGICK_COMPOSITE_OP_LUMINIZE (integer)

IMAGICK_COMPOSITE_OP_SCREEN (integer)

IMAGICK_COMPOSITE_OP_OVERLAY (integer)

IMAGICK_PROFILE_OWN (integer)

IMAGICK_PROFILE_COPY (integer)

IMAGICK_TYPE_UNDEFINED (integer)

IMAGICK_TYPE_BILEVEL (integer)

IMAGICK_TYPE_GRAYSCALE (integer)

IMAGICK_TYPE_GRAYSCALEMATTE (integer)

IMAGICK_TYPE_PALETTE (integer)

IMAGICK_TYPE_PALETTEMATTE (integer)

IMAGICK_TYPE_TRUECOLOR (integer)

IMAGICK_TYPE_TRUECOLORMATTE (integer)

IMAGICK_TYPE_COLORSEPARATION (integer)

IMAGICK_TYPE_COLORSEPARATIONMATTE (integer)

IMAGICK_TYPE_OPTIMIZE (integer)

IMAGICK_COLORSPACE_UNDEFINED (integer)

IMAGICK_COLORSPACE_RGB (integer)

IMAGICK_COLORSPACE_GRAY (integer)

IMAGICK_COLORSPACE_TRANSPARENT (integer)

IMAGICK_COLORSPACE_OHTA (integer)

IMAGICK_COLORSPACE_XYZ (integer)

IMAGICK_COLORSPACE_YCBCR (integer)

IMAGICK_COLORSPACE_YCC (integer)

IMAGICK_COLORSPACE_YIQ (integer)

IMAGICK_COLORSPACE_YPBPR (integer)

IMAGICK_COLORSPACE_YUV (integer)

IMAGICK_COLORSPACE_CMYK (integer)

IMAGICK_COLORSPACE_SRGB (integer)

IMAGICK_COMPRESSION_UNDEFINED (integer)

IMAGICK_COMPRESSION_NONE (integer)

IMAGICK_COMPRESSION_BZIP (integer)

IMAGICK_COMPRESSION_FAX (integer)

IMAGICK_COMPRESSION_GROUP4 (integer)

IMAGICK_COMPRESSION_JPEG (integer)

IMAGICK_COMPRESSION_LOSSLESSJPEG (integer)

IMAGICK_COMPRESSION_LZW (integer)

IMAGICK_COMPRESSION_RLE (integer)

IMAGICK_COMPRESSION_ZIP (integer)

Table of Contents
imagick_begindraw -- Begin draw
imagick_blob2image -- Read image from BLOB
imagick_blur -- Blur image
imagick_border -- Surrounds the image with a border
imagick_charcoal -- Highlight edges
imagick_chop -- Remove a region of an image and collapse the image to occupy the removed portion
imagick_clonehandle -- Clone image
imagick_composite -- Composite the second image onto the first at the specified offsets
imagick_contrast -- Enhance the intensity differences between the lighter and darker elements of the image
imagick_convert -- Convert image
imagick_crop -- Extract a region of the image
imagick_despeckle -- Reduce the speckle noise
imagick_destroyhandle -- Free image from memory
imagick_drawannotation -- Write text
imagick_drawarc -- Draw arc
imagick_drawcircle -- Draw circle
imagick_drawellipse -- Draw ellipse
imagick_drawline -- Draw line
imagick_drawpoint -- Draw point
imagick_drawrectangle -- Draw rectangle
imagick_edge -- Find edges
imagick_emboss -- Return a grayscale image with a three-dimensional effect
imagick_enhance -- Apply a digital filter that improves the quality of a noisy image
imagick_equalize -- Apply a histogram equalization to the image
imagick_error -- Check whether there is an error
imagick_faileddescription -- Get description of failure
imagick_failedreason -- Get reason of failure
imagick_first -- Set the internal pointer of an image list to its first element
imagick_flatten -- Merge a sequence of images
imagick_flip -- Create a vertical mirror image by reflecting the pixels around the central x-axis
imagick_flop -- Create a horizontal mirror image by reflecting the pixels around the central y-axis
imagick_frame -- Add a simulated three-dimensional border around the image
imagick_free -- Alias of imagick_destroyhandle()
imagick_gamma -- Gamma-correct a particular image channel
imagick_gaussianblur -- Blur image
imagick_getcanvas -- Get canvas
imagick_getcolorspace -- Get color space
imagick_getdpix -- Get DPI in X axis
imagick_getdpiy -- Get DPI in Y axis
imagick_getheight -- Get height
imagick_getimagedepth -- Get color depth
imagick_getimagefromlist -- Return copy of an image from the list
imagick_getimagetype -- Get image type
imagick_getlistindex -- Get position in the list of the specified image
imagick_getlistsize -- Get list size
imagick_getmagick -- Get Magick string
imagick_getmimetype -- Get MIME type
imagick_getnumbercolors -- Get number of colors
imagick_getwidth -- Get width
imagick_goto -- Go to specified image in a list
imagick_image2blob -- Return image as BLOB
imagick_implode -- Implode image pixels
imagick_iserror -- Check whether there is an error with image
imagick_isgrayimage -- Check whether image is gray
imagick_isimagesequal -- Compare two images
imagick_ismonochromeimage -- Check whether image is monochrome
imagick_isopaqueimage -- Check whether image is opaque
imagick_ispaletteimage -- Check whether image is palette
imagick_level -- Adjust levels of a particular image channel by scaling the colors falling between specified white and black points to the full available quantum range
imagick_magnify -- Double-size the image using bilinear interpolation
imagick_medianfilter -- Replace each pixel by the median in a set of neighboring pixels
imagick_minify -- Half-size the image using the weighted average of a 4x4 cell
imagick_modulate -- Control brightness, saturation and hue
imagick_mosaic -- Inlay a number of images to form a single coherent picture
imagick_motionblur -- Simulate motion blur
imagick_negate -- Negate the colors
imagick_newimagelist -- Create new image list
imagick_next -- Advance the internal pointer of an image list
imagick_normalize -- Enhance the contrast of a color image by mapping the darkest 2 percent of all pixel to black and the brightest 1 percent to white
imagick_oilpaint -- Simulate oil painting
imagick_ordereddither -- Use the ordered dithering technique of reducing color images to monochrome
imagick_poplist -- Remove the last image in the list
imagick_prev -- Rewind the internal pointer of an image list
imagick_profile -- Add or remove a ICC, IPTC, or generic profile from an image
imagick_pushlist -- Add an image to the end of the list
imagick_raise -- Create a simulated three-dimensional button-like effect
imagick_read -- Alias of imagick_readimage()
imagick_readimage -- Read image
imagick_reducenoise -- Smooth the contours of an image while still preserving edge information
imagick_resize -- Resize image
imagick_roll -- Offset an image as defined by x and y
imagick_rotate -- Rotate image
imagick_sample -- Scale image using pixel sampling
imagick_scale -- Scale image using pnmscale() of PBMPLUS
imagick_set_image_comment -- Set "comment" attribute of image
imagick_set_image_quality -- Set image quality
imagick_setcompressionquality -- Set compression quality
imagick_setcompressiontype -- Set compression type
imagick_setdpi -- Set DPI
imagick_setfillcolor -- Set fill color
imagick_setfillopacity -- Set fill opacity
imagick_setfontface -- Set font face
imagick_setfontsize -- Set font size
imagick_setfontstyle -- Set font style
imagick_shade -- Shine a distant light on an image to create a three-dimensional effect
imagick_sharpen -- Sharpen image
imagick_shear -- Slide one edge of an image along the X or Y axis, creating a parallelogram
imagick_solarize -- Solarize image
imagick_spread -- Randomly displace each pixel in a block
imagick_swirl -- Swirl pixels around the center of image
imagick_threshold -- Change the value of individual pixels based on the intensity of each pixel compared to threshold
imagick_transformrgb -- Convert the image from RGB to an alternate colorspace
imagick_transparent -- Make image transparent
imagick_unsharpmask -- Sharpen image
imagick_wave -- Creates a ripple effect in the image by shifting the pixels vertically along a sine wave
imagick_writeimage -- Write image
imagick_writeimages -- Write images
imagick_zoom -- Zoom image using selected filter

Prev | Home | Next
png2wbmp | Up | imagick_begindraw


JSON Functions

PHP Manual
Prev Next

LXXI. JSON Functions

Introduction

This extension implements the JavaScript Object Notation (JSON) data-interchange format. The decoding is handled by a parser based on the JSON_checker by Douglas Crockford.

Requirements

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

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/json

Table of Contents
json_decode -- Decodes a JSON string
json_encode -- Returns the JSON representation of a value

Prev | Home | Next
java_last_exception_get | Up | json_decode


KADM5

PHP Manual
Prev Next

LXXII. KADM5

Introduction

These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.

More information about Kerberos can be found at http://web.mit.edu/kerberos/www/.

Documentation for Kerberos and KADM5 can be found at http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.

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 for Attribute Flags

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_modify_principal() allow to specify
special attributes using a bitfield. The symbols are defined below:

Table 1. Attributes for use by the KDC

constant
KRB5_KDB_DISALLOW_POSTDATED
KRB5_KDB_DISALLOW_FORWARDABLE
KRB5_KDB_DISALLOW_TGT_BASED
KRB5_KDB_DISALLOW_RENEWABLE
KRB5_KDB_DISALLOW_PROXIABLE
KRB5_KDB_DISALLOW_DUP_SKEY
KRB5_KDB_DISALLOW_ALL_TIX
KRB5_KDB_REQUIRES_PRE_AUTH
KRB5_KDB_REQUIRES_HW_AUTH
KRB5_KDB_REQUIRES_PWCHANGE
KRB5_KDB_DISALLOW_SVR
KRB5_KDB_PWCHANGE_SERVER
KRB5_KDB_SUPPORT_DESMD5
KRB5_KDB_NEW_PRINC

Constants for Options

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_get_principal() allow to specify or return
principal's options as an associative array. The keys for the associative
array are defined as string constants below:

Table 2. Options for creating/modifying/retrieving principals

constant | funcdef | description
KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp.
KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed.
KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp.
KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal.
KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal.
KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal.
KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp.
KADM5_KVNO | long | The version of the principal's current key.
KADM5_POLICY | string | The name of the policy controlling this principal.
KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour.
KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ.
KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs.
KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored.
KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC.

Examples

This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Example 1. KADM5 extension overview example

&#60;?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "&#60;h1&#62;get_principals&#60;/h1&#62;\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i&#60;count($principals); $i++)
      print "$principals[$i]&#60;br&#62;\n";

  print "&#60;h1&#62;get_policies&#60;/h1&#62;\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i&#60;count($policies); $i++)
      print "$policies[$i]&#60;br&#62;\n";

  print "&#60;h1&#62;get_principal burbach@GONICUS.LOCAL&#60;/h1&#62;\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i&#60;count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value&#60;br&#62;\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME =&#62; 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?&#62;

Contact Information

If you have comments, bugfixes, enhancements or want to help in developing this you can send me a mail at holger.burbach@gonicus.de. The project homepage can be found at http://oss.gonicus.de/project/?group_id=7.

Table of Contents
kadm5_chpass_principal -- Changes the principal's password
kadm5_create_principal -- Creates a kerberos principal with the given parameters
kadm5_delete_principal -- Deletes a kerberos principal
kadm5_destroy -- Closes the connection to the admin server and releases all related resources
kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open
kadm5_get_policies -- Gets all policies from the Kerberos database
kadm5_get_principal -- Gets the principal's entries from the Kerberos database
kadm5_get_principals -- Gets all principals from the Kerberos database
kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state information
kadm5_modify_principal -- Modifies a kerberos principal with the given parameters

Prev | Home | Next
json_encode | Up | kadm5_chpass_principal


Net_Gopher

PHP Manual
Prev Next

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.

Requirements

Installation

Net_Gopher is installed through the usual PECL package installation process.

  • Prerequisite: PHP 4.3.0.

  • $ pear install Net_Gopher

  • Copy the resulting gopher.so to an appropriate location and add extension=gopher.so to your php.ini file or load it dynamically in your PHP script using dl("gopher.so");

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

Constant | Value | Description
GOPHER_DOCUMENT | 0 | Standard text/plain document.
GOPHER_DIRECTORY | 1 | A resource containing a gopher formatted directory listing.
GOPHER_BINHEX | 4 | A BinHex encoded binary file.
GOPHER_DOSBINARY | 5 | A DOS formatted binary archive.
GOPHER_UUENCODED | 6 | A UUEncoded file.
GOPHER_BINARY | 9 | A generic binary file.
GOPHER_INFO | 255 | An Informational entry
GOPHER_HTTP | 254 | A reference to an HTTP resource.
GOPHER_UNKNOWN | -1 | An unrecognized entry.

Examples

&#60;?php
readfile("gopher://gopher.example.com/somedocument");
?&#62;

Table of Contents
gopher_parsedir -- Translate a gopher formatted directory entry into an associative array.

Prev | Home | Next
gnupg_verify | Up | gopher_parsedir


Newt Functions

PHP Manual
Prev Next

CI. Newt Functions

Introduction

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.

Requirements

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.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/newt.

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 CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Note: This extension is not available for Windows platform.

You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang

Resource Types

This extension uses two resource types: "newt component" and "newt grid". Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button()) Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())

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.

Newt form exit reasons

Table 1. Newt form exit reasons

constant | meaning
NEWT_EXIT_HOTKEY | hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT | some component has caused form to exit
NEWT_EXIT_FDREADY | file descriptor specified in newt_form_watch_fd() is ready to be read or written to
NEWT_EXIT_TIMER | time specified in newt_form_set_timer() has elapsed

Newt colorsets

Table 2. Newt colorsets

constant | meaning
NEWT_COLORSET_ROOT |
NEWT_COLORSET_BORDER |
NEWT_COLORSET_WINDOW |
NEWT_COLORSET_SHADOW |
NEWT_COLORSET_TITLE |
NEWT_COLORSET_BUTTON |
NEWT_COLORSET_ACTBUTTON |
NEWT_COLORSET_CHECKBOX |
NEWT_COLORSET_ACTCHECKBOX |
NEWT_COLORSET_ENTRY |
NEWT_COLORSET_LABEL |
NEWT_COLORSET_LISTBOX |
NEWT_COLORSET_ACTLISTBOX |
NEWT_COLORSET_TEXTBOX |
NEWT_COLORSET_ACTTEXTBOX |
NEWT_COLORSET_HELPLINE |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |

Newt argument flags

Table 3. Newt argument flags

constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |

Newt Flags Sense

Table 4. Newt Flags Sense

constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |

Newt Components Flags

Table 5. Newt Components Flags

constant | meaning
NEWT_FLAG_RETURNEXIT | Exit form, when component is activated
NEWT_FLAG_HIDDEN | Component is hidden
NEWT_FLAG_SCROLL | Component is scrollable
NEWT_FLAG_DISABLED | Component is disabled
NEWT_FLAG_BORDER |
NEWT_FLAG_WRAP | Wrap text
NEWT_FLAG_NOF12 | Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE |
NEWT_FLAG_SELECTED | Component is selected
NEWT_FLAG_CHECKBOX | Component is checkbox
NEWT_FLAG_PASSWORD | Entry component is password entry
NEWT_FLAG_SHOWCURSOR | Show cursor

File Descriptor Flags

Table 6. File Descriptor Flags

constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |

Checkbox Tree Flags

Table 7. Checkbox Tree Flags

constant | meaning
NEWT_CHECKBOXTREE_UNSELECTABLE |
NEWT_CHECKBOXTREE_HIDE_BOX |
NEWT_CHECKBOXTREE_COLLAPSED |
NEWT_CHECKBOXTREE_EXPANDED |
NEWT_CHECKBOXTREE_UNSELECTED |
NEWT_CHECKBOXTREE_SELECTED |

Entry Flags

Table 8. Entry Flags

constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |

Listbox Flags

Table 9. Listbox Flags

constant | meaning
NEWT_LISTBOX_RETURNEXIT |

Textbox Flags

Table 10. Textbox Flags

constant | meaning
NEWT_TEXTBOX_WRAP | Wrap text in the textbox
NEWT_TEXTBOX_SCROLL | Scroll text in the textbox

Form Flags

Table 11. Form Flags

constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press

Newt Keys

Table 12. Newt Keys

constant | meaning
NEWT_KEY_TAB |
NEWT_KEY_ENTER |
NEWT_KEY_SUSPEND |
NEWT_KEY_ESCAPE |
NEWT_KEY_RETURN |
NEWT_KEY_EXTRA_BASE |
NEWT_KEY_UP |
NEWT_KEY_DOWN |
NEWT_KEY_LEFT |
NEWT_KEY_RIGHT |
NEWT_KEY_BKSPC |
NEWT_KEY_DELETE |
NEWT_KEY_HOME |
NEWT_KEY_END |
NEWT_KEY_UNTAB |
NEWT_KEY_PGUP |
NEWT_KEY_PGDN |
NEWT_KEY_INSERT |
NEWT_KEY_F1 |
NEWT_KEY_F2 |
NEWT_KEY_F3 |
NEWT_KEY_F4 |
NEWT_KEY_F5 |
NEWT_KEY_F6 |
NEWT_KEY_F7 |
NEWT_KEY_F8 |
NEWT_KEY_F9 |
NEWT_KEY_F10 |
NEWT_KEY_F11 |
NEWT_KEY_F12 |
NEWT_KEY_RESIZE |

Newt Anchors

Table 13. Newt Anchors

constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |

Grid Flags

Table 14. Grid Flags

constant | meaning
NEWT_GRID_FLAG_GROWX |
NEWT_GRID_FLAG_GROWY |
NEWT_GRID_EMPTY |
NEWT_GRID_COMPONENT |
NEWT_GRID_SUBGRID |

Examples

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example 1. Newt Usage Example

&#60;?php
    newt_init ();
    newt_cls ();

    newt_draw_root_text (0, 0, "Test Mode Setup Utility 1.12");
    newt_push_help_line (null);
    newt_draw_root_text (-30, 0, "(c) 1999-2002 RedHat, Inc");

    newt_get_screen_size (&#38;$rows, &#38;$cols);

    newt_open_window ($rows/2-17, $cols/2-10, 34, 17, "Choose a Tool");

    $form = newt_form ();

    $list = newt_listbox (3, 2, 10);

    foreach (array (
        "Authentication configuration",
        "Firewall configuration",
        "Mouse configuration",
        "Network configuration",
        "Printer configuration",
        "System services") as $l_item)
    {
        newt_listbox_add_entry ($list, $l_item, $l_item);
    }

    $b1 = newt_button (5, 12, "Run Tool");
    $b2 = newt_button (21, 12, "Quit");

    newt_form_add_component ($form, $list);
    newt_form_add_components ($form, array($b1, $b2));

    newt_refresh ();
    newt_run_form ($form);

    newt_pop_window ();
    newt_pop_help_line ();
    newt_finished ();
    newt_form_destroy ($form);
?&#62;
Table of Contents
newt_bell -- Send a beep to the terminal
newt_button_bar --
newt_button --
newt_centered_window -- Open a centered window of the specified size
newt_checkbox_get_value --
newt_checkbox_set_flags --
newt_checkbox_set_value --
newt_checkbox_tree_add_item -- *
newt_checkbox_tree_find_item --
newt_checkbox_tree_get_current --
newt_checkbox_tree_get_entry_value --
newt_checkbox_tree_get_multi_selection --
newt_checkbox_tree_get_selection --
newt_checkbox_tree_multi --
newt_checkbox_tree_set_current --
newt_checkbox_tree_set_entry_value --
newt_checkbox_tree_set_entry --
newt_checkbox_tree_set_width --
newt_checkbox_tree --
newt_checkbox --
newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional input
newt_cls --
newt_compact_button --
newt_component_add_callback --
newt_component_takes_focus --
newt_create_grid --
newt_cursor_off --
newt_cursor_on --
newt_delay --
newt_draw_form --
newt_draw_root_text -- Displays the string text at the position indicated
newt_entry_get_value --
newt_entry_set_filter --
newt_entry_set_flags --
newt_entry_set --
newt_entry --
newt_finished -- Uninitializes newt interface
newt_form_add_component -- Adds a single component to the form
newt_form_add_components -- Add several components to the form
newt_form_add_host_key --
newt_form_destroy -- Destroys a form
newt_form_get_current --
newt_form_run -- Runs a form
newt_form_set_background --
newt_form_set_height --
newt_form_set_size --
newt_form_set_timer --
newt_form_set_width --
newt_form_watch_fd --
newt_form -- Create a form
newt_get_screen_size -- Fills in the passed references with the current size of the terminal
newt_grid_add_components_to_form --
newt_grid_basic_window --
newt_grid_free --
newt_grid_get_size --
newt_grid_h_close_stacked --
newt_grid_h_stacked --
newt_grid_place --
newt_grid_set_field --
newt_grid_simple_window --
newt_grid_v_close_stacked --
newt_grid_v_stacked --
newt_grid_wrapped_window_at --
newt_grid_wrapped_window --
newt_init -- Initialize newt
newt_label_set_text --
newt_label --
newt_listbox_append_entry --
newt_listbox_clear_selection --
newt_listbox_clear --
newt_listbox_delete_entry --
newt_listbox_get_current --
newt_listbox_get_selection --
newt_listbox_insert_entry --
newt_listbox_item_count --
newt_listbox_select_item --
newt_listbox_set_current_by_key --
newt_listbox_set_current --
newt_listbox_set_data --
newt_listbox_set_entry --
newt_listbox_set_width --
newt_listbox --
newt_listitem_get_data --
newt_listitem_set --
newt_listitem --
newt_open_window -- Open a window of the specified size and position
newt_pop_help_line -- Replaces the current help line with the one from the stack
newt_pop_window -- Removes the top window from the display
newt_push_help_line -- Saves the current help line on a stack, and displays the new line
newt_radio_get_current --
newt_radiobutton --
newt_redraw_help_line --
newt_reflow_text --
newt_refresh -- Updates modified portions of the screen
newt_resize_screen --
newt_resume -- Resume using the newt interface after calling newt_suspend()
newt_run_form -- Runs a form
newt_scale_set --
newt_scale --
newt_scrollbar_set --
newt_set_help_callback --
newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend key
newt_suspend -- Tells newt to return the terminal to its initial state
newt_textbox_get_num_lines --
newt_textbox_reflowed --
newt_textbox_set_height --
newt_textbox_set_text --
newt_textbox --
newt_vertical_scrollbar --
newt_wait_for_key -- Doesn't return until a key has been pressed
newt_win_choice --
newt_win_entries --
newt_win_menu --
newt_win_message --
newt_win_messagev --
newt_win_ternary --

Prev | Home | Next
syslog | Up | newt_bell


oggvorbis

PHP Manual
Prev Next

CVIII. oggvorbis

Introduction

The OGG/Vorbis file format, as defined by http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.

Requirements

This extension requires PHP >= 4.3.0, libogg >= 1.0, and libvorbis >= 1.0.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Installation

oggvorbis is installed through the usual PECL package installation process.

  • $ pear install oggvorbis

  • Copy the resulting oggvorbis.so to an appropriate location and add extension=oggvorbis.so to your php.ini file or load it dynamically in your PHP script using dl('oggvorbis.so');

Context options

Table 1. OGG/Vorbis tuning options

Option | Definition | Relevance | Default
pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE
rate | PCM Sampling rate. Measured in Hz. | Write only | 44100
bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000
channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2
serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random
comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis')

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. OGG/Vorbis supports PCM encodings in the following formats

Constant | Definition
OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8 | Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order.
Table of Contents
Usage -- Examples on using the ogg:// wrapper.

Prev | Home | Next
PDO_ODBC DSN | Up | Usage


Paradox File Access

PHP Manual
Prev Next

CXV. Paradox File Access

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.

This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.

Note: This module is also in development and may change, though I don't expect major changes to the API.

Requirements

You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at http://pxlib.sourceforge.net.

Installation

A short installation note: just type

$ pear install paradox
in your console. Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Object oriented API

The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.

Table 1. Methods of class paradox_db

Name of method | Equivalent function
Constructor | px_new()
Destructor | px_delete()
open_fp() | px_open_fp()
create_fp() | px_create_fp()
close() | px_close()
numrecords() | px_numrecords()
numfields() | px_numfields()
get_record() | px_get_record()
put_record() | px_put_record()
retrieve_record() | px_retrieve_record()
delete_record() | px_delete_record()
insert_record() | px_insert_record()
update_record() | px_update_record()
get_field() | px_get_field()
get_schema() | px_get_schema()
get_info() | px_get_info()
set_parameter() | px_set_parameter()
get_parameter() | px_get_parameter()
set_value() | px_set_value()
get_value() | px_get_value()
get_info() | px_get_info()
set_targetencoding() | px_set_targetencoding()
set_tablename() | px_set_tablename()
set_blob_file() | px_set_blob_file()
date2string() | px_date2string()
timestamp2string() | px_timestamp2string()

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 two tables lists all constants defined by the paradox extension.

Table 2. Contants for field types

Name | Meaning
PX_FIELD_ALPHA | Character data with fixed length
PX_FIELD_DATE | Date, number of days since 1.1.0000
PX_FIELD_SHORT | Short integer (2 Bytes)
PX_FIELD_LONG | Long integer (4 Bytes)
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER
PX_FIELD_NUMBER | Double
PX_FIELD_LOGICAL | Boolean
PX_FIELD_MEMOBLOB | Binary large object
PX_FIELD_BLOB | Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB | Binary large object
PX_FIELD_OLE | OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported)
PX_FIELD_TIME | time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP | timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD | Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER | Turn all field names into lower case
PX_KEYTOUPPER | Turn all field names into upper case

Table 3. Contants for file types

Name | Meaning
PX_FILE_INDEX_DB | Indexed database
PX_FILE_PRIM_INDEX | Primary index
PX_FILE_NON_INDEX_DB | None indexed database
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index
PX_FILE_SEC_INDEX | Secondary index
PX_FILE_INC_SEC_INDEX | Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G | Non incremental secondary index
PX_FILE_SEC_INDEX_G | Secondary index
PX_FILE_INC_SEC_INDEX_G | Non incremental secondary index

Table of Contents
px_close -- Closes a paradox database
px_create_fp -- Create a new paradox database
px_date2string -- Converts a date into a string.
px_delete_record -- Deletes record from paradox database
px_delete -- Deletes resource of paradox database
px_get_field -- Returns the specification of a single field
px_get_info -- Return lots of information about a paradox file
px_get_parameter -- Gets a parameter
px_get_record -- Returns record of paradox database
px_get_schema -- Returns the database schema
px_get_value -- Gets a value
px_insert_record -- Inserts record into paradox database
px_new -- Create a new paradox object
px_numfields -- Returns number of fields in a database
px_numrecords -- Returns number of records in a database
px_open_fp -- Open paradox database
px_put_record -- Stores record into paradox database
px_retrieve_record -- Returns record of paradox database
px_set_blob_file -- Sets the file where blobs are read from
px_set_parameter -- Sets a parameter
px_set_tablename -- Sets the name of a table (deprecated)
px_set_targetencoding -- Sets the encoding for character fields (deprecated)
px_set_value -- Sets a value
px_timestamp2string -- Converts the timestamp into a string.
px_update_record -- Updates record in paradox database

Prev | Home | Next
ovrimos_rollback | Up | px_close


Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

PHP Manual
Prev Next

XCI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

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_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS libary.

On Windows, you should use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

Table of Contents
PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databases

Prev | Home | Next
mssql_select_db | Up | PDO_DBLIB DSN


PDO_DBLIB DSN

(no version information, might be only in CVS)

PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databases

Description

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sybase: if PDO_DBLIB was linked against the FreeTDS libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if linked against any other variety of DB-lib.

host

The hostname on which the database server resides.

dbname

The name of the database.

Examples

Example 1. PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:

mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb

Prev | Home | Next
Microsoft SQL Server and Sybase Functions (PDO_DBLIB) | Up | Mohawk Software Session Handler Functions


Firebird/Interbase Functions (PDO_FIREBIRD)

PHP Manual
Prev Next

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

Prev | Home | Next
ibase_wait_event | Up | PDO_FIREBIRD DSN


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

Prev | Home | Next
Firebird/Interbase Functions (PDO_FIREBIRD) | Up | FriBiDi Functions


IBM Functions (PDO_IBM)

PHP Manual
Prev Next

LVII. 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

Prev | Home | Next
hw_api->userlist | Up | PDO_IBM DSN


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");

Prev | Home | Next
IBM Functions (PDO_IBM) | Up | IBM DB2, Cloudscape and Apache Derby Functions


Informix Functions (PDO_INFORMIX)

PHP Manual
Prev Next

LXVII. Informix Functions (PDO_INFORMIX)

Introduction

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

Installation

To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or higher must be installed on the same system as PHP. The Informix Client SDK is available from the IBM Informix Support Site.

PDO_INFORMIX is a PECL extension, so follow the instructions in Chapter 7 to install the PDO_INFORMIX extension. Issue the configure command to point to the location of your Informix Client SDK header files and libraries as follows:

bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]
The configure command defaults to the value of the INFORMIXDIR environment variable.

Scrollable cursors

PDO_INFORMIX supports scrollable cursors; however, they are not enabled by default. To enable scrollable cursor support, you must either set ENABLESCROLLABLECURSORS=1 in the corresponding ODBC connection settings in odbc.ini or pass the EnableScrollableCursors=1 clause in the DSN connection string.

Table of Contents
PDO_INFORMIX DSN -- Connecting to Informix databases

Prev | Home | Next
ifxus_write_slob | Up | PDO_INFORMIX DSN


PDO_INFORMIX DSN

(no version information, might be only in CVS)

PDO_INFORMIX DSN -- Connecting to Informix databases

Description

The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN string. Details on configuring an Informix ODBC DSN are available from the Informix Dynamic Server Information Center. The major components of the PDO_INFORMIX DSN are:

DSN prefix

The DSN prefix is informix:.

DSN

The DSN can be either a data source setup using odbc.ini or a complete connection string.

Examples

Example 1. PDO_INFORMIX DSN example using odbc.ini

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database cataloged as Infdrv33 in odbc.ini:

$db = new PDO("informix:DSN=Infdrv33", "", "");
[ODBC Data Sources]
Infdrv33=INFORMIX 3.3 32-BIT

[Infdrv33]
Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
Description=INFORMIX 3.3 32-BIT
Database=common_db
LogonID=testuser
pwd=testpass
Servername=ids_server
DB_LOCALE=en_US.819
OPTIMIZEAUTOCOMMIT=1
ENABLESCROLLABLECURSORS=1

Example 2. PDO_INFORMIX DSN example using a connection string

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database named common_db using the Informix connection string syntax.

$db = new PDO("informix:host=host.domain.com; service=9800;
    database=common_db; server=ids_server; protocol=onsoctcp;
    EnableScrollableCursors=1", "testuser", "tespass");

Prev | Home | Next
Informix Functions (PDO_INFORMIX) | Up | Ingres II Functions


MySQL Functions (PDO_MYSQL)

PHP Manual
Prev Next

XCVII. MySQL Functions (PDO_MYSQL)

Introduction

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x, 4.x and 5.x databases.

PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.1 and higher. If you're using an older version of the mysql client libraries, PDO will emulate them for you.

Warning

Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using mysql-specific attributes with the postgres driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (integer)

If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.

Example 1. Forcing queries to be buffered in mysql

&#60;?php
if ($db-&#62;getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
    $stmt = $db-&#62;prepare('select * from foo',
        array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY =&#62; true));
} else {
    die("my application only works with mysql; I should use \$stmt-&#62;fetchAll() instead");
}
?&#62;

PDO::MYSQL_ATTR_LOCAL_INFILE (integer)

Enable LOAD LOCAL INFILE.

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)

Read options from the named option file instead of from my.cnf.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)

Maximum buffer size. Defaults to 1 MiB.

PDO::MYSQL_ATTR_DIRECT_QUERY (integer)

Perform direct queries, don't use prepared statements.

Table of Contents
PDO_MYSQL DSN -- Connecting to MySQL databases

Prev | Home | Next
mysql_unbuffered_query | Up | PDO_MYSQL DSN


PDO_MYSQL DSN

(no version information, might be only in CVS)

PDO_MYSQL DSN -- Connecting to MySQL databases

Description

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is mysql:.

host

The hostname on which the database server resides.

port

The port number where the database server is listening.

dbname

The name of the database.

unix_socket

The MySQL unix socket (shouldn't be used with host or port).

Examples

Example 1. PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:

mysql:host=localhost;dbname=testdb
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb

Prev | Home | Next
MySQL Functions (PDO_MYSQL) | Up | MySQL Improved Extension


Oracle Functions (PDO_OCI)

PHP Manual
Prev Next

CXII. Oracle Functions (PDO_OCI)

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_OCI is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Oracle databases through the OCI library.

Table of Contents
PDO_OCI DSN -- Connecting to Oracle databases

Prev | Home | Next
ora_rollback | Up | PDO_OCI DSN


PDO_OCI DSN

(no version information, might be only in CVS)

PDO_OCI DSN -- Connecting to Oracle databases

Description

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is oci:.

dbname (Oracle Instant Client)

The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database. If you are connecting to a database defined in tnsnames.ora, use only the name of the database: dbname=database.

charset

The client-side character set for the current environment handle.

Examples

Example 1. PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:

oci:mydb
oci:dbname=//localhost:1521/mydb

Prev | Home | Next
Oracle Functions (PDO_OCI) | Up | Output Control Functions


ODBC and DB2 Functions (PDO_ODBC)

PHP Manual
Prev Next

CVII. ODBC and DB2 Functions (PDO_ODBC)

Introduction

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:

ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.

unixODBC

Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, PDO_ODBC is built into the PHP core by default. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.

Installation

PDO_ODBC on UNIX systems

  1. As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.

    ibm_db2

    ./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/
    To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database support site.

    If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

    unixODBC

    ./configure --with-pdo-odbc=unixODBC,/usr/local
    If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.

    generic
    ./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. PDO_ODBC Configuration Options

Name | Default | Changeable | Changelog
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2instance_name | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

pdo_odbc.connection_pooling string

Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

Warning

relaxed matching should not be used on a shared server, for security reasons.

Tip: Leave this setting at the default strict setting unless you have good reason to change it.

pdo_odbc.db2instance_name string

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Table of Contents
PDO_ODBC DSN -- Connecting to ODBC or DB2 databases

Prev | Home | Next
odbc_tables | Up | PDO_ODBC DSN


PDO_ODBC DSN

(no version information, might be only in CVS)

PDO_ODBC DSN -- Connecting to ODBC or DB2 databases

Description

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is odbc:. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

DSN

The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at http://www.connectionstrings.com/.

UID

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

PWD

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Examples

Example 1. PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

odbc:testdb

Example 2. PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:

odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Example 3. PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:

odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

Prev | Home | Next
ODBC and DB2 Functions (PDO_ODBC) | Up | oggvorbis


PostgreSQL Functions (PDO_PGSQL)

PHP Manual
Prev Next

CXXVI. PostgreSQL Functions (PDO_PGSQL)

Introduction

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

Table of Contents
PDO_PGSQL DSN -- Connecting to PostgreSQL databases
PDO::pgsqlLOBCreate -- Creates a new large object
PDO::pgsqlLOBOpen -- Opens an existing large object stream
PDO::pgsqlLOBUnlink -- Deletes the large object

Prev | Home | Next
pg_version | Up | PDO_PGSQL DSN


PDO_PGSQL DSN

(no version information, might be only in CVS)

PDO_PGSQL DSN -- Connecting to PostgreSQL databases

Description

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces:

DSN prefix

The DSN prefix is pgsql:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

password

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Examples

Example 1. PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:

pgsql:host=localhost port=5432 dbname=testdb user=bruce password=mypass

Prev | Home | Next
PostgreSQL Functions (PDO_PGSQL) | Up | PDO::pgsqlLOBCreate


SQLite Functions (PDO_SQLITE)

PHP Manual
Prev Next

CLV. SQLite Functions (PDO_SQLITE)

Introduction

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy sqlite 2 database files into an application that uses the faster, more efficient sqlite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.

Table of Contents
PDO_SQLITE DSN -- Connecting to SQLite databases
PDO->sqliteCreateAggregate() -- Registers an aggregating User Defined Function for use in SQL statements
PDO->sqliteCreateFunction() -- Registers a User Defined Function for use in SQL statements

Prev | Home | Next
sqlite_valid | Up | PDO_SQLITE DSN


PDO_SQLITE DSN

(no version information, might be only in CVS)

PDO_SQLITE DSN -- Connecting to SQLite databases

Description

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

The DSN prefix is sqlite:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append memory: to the DSN prefix.

DSN prefix (SQLite 2)

The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.

Note: The sqlite2 driver is only available in PHP 5.1 if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.

The DSN prefix for connecting to SQLite 2 databases is sqlite2:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append memory: to the DSN prefix.

Examples

Example 1. PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:

sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:

Prev | Home | Next
SQLite Functions (PDO_SQLITE) | Up | PDO->sqliteCreateAggregate()


Phar archive stream and classes

PHP Manual
Prev Next

CXXI. Phar archive stream and classes

Introduction

The phar extension provides the phar stream wrapper and the Phar class for manipulating self-contained PHP Archive (phar) files. The Phar class can be used to create and to extract contents of phar files as well as iterating over their contents.

PHP Archive files (Phars) are special collections of files that can be transparently run right out of the file, similar to Java's jar archive files. Using a phar archive, it is possible to distribute a complete PHP application in a single file that will run out of the file without modification or extraction. Phar archives can also be used to store files for extraction similar to tar or zip archive files. Phars support compression using gzip if the zlib extension is present, and using bzip2 if the bz2 extension is present. In addition, iteration and other features are available if the SPL extension is available. Phar signature verification using md5 or sha1 is natively supported to ensure archive integrity.

The original implementation for Phar archives was in the PEAR package PHP_Archive, and the implementation details are very similar, although the Phar extension is more full-featured. PHP_Archive has more flexibility in Phar creation, and helpful debugging tools like the PHP_Archive_Manager class, and the Phar extension supports iteration, array access, and directly manipulating Phar contents through a simple interface. PHP_Archive supports creation of Phar archives that can be processed using the Phar extension or PHP_Archive seamlessly, whereas the Phar extension is designed to create extensions that function with the Phar extension. In addition, the Phar extension will continue to work even if the allow_url_include or allow_url_fopen INI variables are disabled, while PHP_Archive-based Phar archives (without the Phar extension) will not function.

Requirements

Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.

You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support.

Installation

Windows binaries may be found at http://snaps.php.net/. To install, download php_phar.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_phar.dll to your php.ini and restarting your webserver.

extension_dir=c:/php5/exts/
extension=php_phar.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Either:

    • Run the pear installer for PECL/phar: pecl install phar

    • Copy phar.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.

    • Add extension=phar.so to your php.ini

    Or:

    • Set the path to your php.ini via:

      pecl config-set php_ini /path/to/php.ini

    • Run the pear installer for PECL/phar: pecl install phar

  • Restart your webserver to reload your php.ini settings.

Development Versions: There are currently no stable versions of PECL/phar, to force installation of the alpha version of PECL/phar execute: pecl install phar-alpha

Compiling PECL/phar without using the PEAR command: Rather than using pecl install phar to automatically download and install PECL/phar, you may download the tarball from PECL. From the root of the unpacked tarball, run: phpize && ./configure --enable-phar && make to generate phar.so. Once built, continue the installation from step 4 above.

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/phar.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Filesystem and Streams Configuration Options

Name | Default | Changeable | Changelog
phar.readonly | "1" | PHP_INI_SYSTEM disable/enable, PHP_INI_ALL enable | Available Since version 1.0.0
phar.require_hash | "0" | PHP_INI_SYSTEM disable/enable, PHP_INI_ALL enable | Available Since version 1.0.0

Here's a short explanation of the configuration directives.

phar.readonly boolean

This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.

Note: This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.require_hash boolean

This option will force all opened Phar archives to contain some kind of signature (currently MD5 and SHA1 are supported), and will refuse to process any Phar archive that does not contain a signature.

Note: This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

Resource Types

The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. The file format of a Phar is described here

Predefined Classes

Phar
PharFileInfo
PharException

Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. Unlike Java's implementation of JAR archives, no external tool is required to process or run a PHP Phar archive. A Phar archive application is processed exactly like any other PHP application:

php coolapplication.phar

Using a Phar archive library is identical to using any other PHP library:

&#60;?php
include 'coollibrary.phar';
?&#62;

What makes Phar archives incredibly useful is the phar stream wrapper, which is explained in depth here. Using this stream wrapper, it is possible to access individual files within a phar as if the phar were its own filesystem. The phar stream wrapper supports all read/write operations on files, and opendir() on directories.

&#60;?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?&#62;

Also provided with the Phar extension is the Phar class, which allows accessing the files of the Phar archive as if it were an associative array, and other functionality. The Phar class is explained here.

&#60;?php
try {
    // open an existing phar
    $p = new Phar('coollibrary.phar');
    foreach ($p as $file) {
        // $file is a PharFileInfo class, and inherits from SplFileInfo
        echo $file-&#62;getFileName() . "\n";
        echo $file . "\n"; // display contents;
    }
    if (isset($p['internal/file.php'])) {
        var_dump($p['internal/file.php']-&#62;getMetaData());
    }

    // create a new phar - phar.readonly must be 0 in php.ini
    // phar.readonly is enabled by default for security reasons.
    // On production servers, Phars need never be created,
    // only executed.
    if (Phar::canWrite()) {
        $p = new Phar(dirname(__FILE__) . '/newphar.phar', 0, 'newphar.phar');
        // create transaction - nothing is written to newphar.phar
        // until commit() is called, although temporary storage is needed
        $p-&#62;begin();
        // add a new file, set its contents
        $p['file1.txt'] = 'Information';
        $fp = fopen('hugefile.dat', 'rb');
        // copy from the stream
        $p['data/hugefile.dat'] = $fp;
        if (Phar::canCompress()) {
            $p['data/hugefile.dat']-&#62;setCompressedGZ();
        }
        $p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
        // any value can be saved as file-specific meta-data
        $p['images/wow.jpg']-&#62;setMetaData(array('mime-type' =&#62; 'image/jpeg'));
        $p['index.php'] = file_get_contents('index.php');
        $p-&#62;setMetaData(array('bootstrap' =&#62; 'index.php'));
        // set the loader stub
        $p-&#62;setStub('&#60;?php
$p = new Phar(__FILE__);
$m = $p-&#62;getMetaData();
require "phar://" . __FILE__ . "/" . $m["bootstrap"];
__HALT_COMPILER();');
        // save the phar archive to disk
        $p-&#62;commit();
    }
} catch (Exception $e) {
    echo 'Could not open Phar: ', $e;
}
?&#62;

Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read, write or append, unlink(), stat(), fstat(), fseek(), rename() and directory stream operation opendir(). The Phar stream wrapper does not support creating or erasing a directory, as files are stored only as files, and the concept of an abstract directory does not exist.

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

&#60;?php
$context = stream_context_create(array('phar' =&#62;
                                    array('compression' =&#62; Phar::GZ)),
                                    array('metadata' =&#62; array('user' =&#62; 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?&#62;

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read operations.

Using Phar Archives: the Phar class

The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.

It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.

Assuming that $p is a Phar object initialized as follows:

&#60;?php
$p = new Phar('/path/to/myphar.phar', 0, 'myphar.phar');
?&#62;
An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar deomnstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:
&#60;?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f = file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f = file_get_contents('phar://myphar.phar/whatever.txt');
?&#62;
With the newly created $p Phar object, the following is possible:

  • $a = $p['file.php'] creates a PharFileInfo class that refers to the contents of phar://myphar.phar/file.php

  • $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php), or overwrites an existing file within myphar.phar. $v can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file.

  • isset($p['file.php']) can be used to determine whether phar://myphar.phar/file.php exists within myphar.phar.

  • unset($p['file.php']) erases phar://myphar.phar/file.php from myphar.phar.

In addition, the Phar object is the only way to access Phar-specific metadata, through Phar->getMetaData(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar->getStub() and Phar->setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.

The full list of Phar object functionality is documented below.

The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.

Phar file format

All Phar files contain three to four sections:

  1. a stub

  2. a manifest describing the contents

  3. the file contents

  4. [optional] a signature for verifying Phar integrity

Phar file stub

A Phar's stub is a simple PHP file. The smallest possible stub follows:

&#60;?php __HALT_COMPILER();

A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:

&#60;?php
Phar::mapPhar();
include 'phar://myphar.phar/index.php';
__HALT_COMPILER();

There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with __HALT_COMPILER();. The closing PHP tag ?> may be included or omitted, but there can be no more than 1 space between the ; and the close tag ?> or the phar extension will be unable to process the Phar archive's manifest.

Phar Manifest Format

The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.

All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.

The basic file format of a Phar archive manifest is as follows:

Table 2. Global Phar manifest format

Size in bytes | Description
4 bytes | Length of manifest in bytes (1 MB limit)
4 bytes | Number of files in the Phar
2 bytes | API version of the Phar manifest (currently 1.0.0)
4 bytes | Global Phar bitmapped flags
4 bytes | Length of Phar alias
?? | Phar alias (length based on previous)
4 bytes | Length of Phar metadata (0 for none)
?? | Serialized Phar Meta-data, stored in serialize() format
at least 24 * number of entries bytes | entries for each file

Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Table 3. Bitmap values recognized

Value | Description
0x00010000 | If set, this Phar contains a verification signature
0x00001000 | If set, this Phar contains at least 1 file that is compressed with zlib compression
0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip compression

Phar manifest file entry definition

Each file in the manifest contains the following information:

Table 4. Phar Manifest file entry

Size in bytes | Description
4 bytes | Filename length in bytes
?? | Filename (length specified in previous)
4 bytes | Un-compressed file size in bytes
4 bytes | Unix timestamp of file
4 bytes | Compressed file size in bytes
4 bytes | CRC32 checksum of un-compressed file contents
4 bytes | Bit-mapped File-specific flags
4 bytes | Serialized File Meta-data length (0 for none)
?? | Serialized File Meta-data, stored in serialize() format

The File-specific bitmap values recognized are:

Table 5. Bitmap values recognized

Value | Description
0x000001FF | These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction.
0x00001000 | If set, this file is compressed with zlib compression
0x00002000 | If set, this file is compressed with bzip compression

Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The two signature formats supported at this time are MD5 and SHA1.

Table 6. Signature format

Length in bytes | Description
16 or 20 bytes | The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature.
4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, and 0x0002 is used to define an SHA1 signature.
4 bytes | Magic GBMB used to define the presence of a signature.

Table of Contents
Phar::apiVersion -- Returns the api version
Phar->begin -- Begin a Phar modification transaction
Phar::canCompress -- Returns whether phar extension supports compression using either zlib or bzip2
Phar::canWrite -- Returns whether phar extension supports writing and creating phars
Phar->commit -- End a Phar modification transaction by writing the Phar archive to disk
Phar->compressAllFilesBZIP2 -- Compresses all files in the current Phar archive using Bzip2 compression
Phar->compressAllFilesGZ -- Compresses all files in the current Phar archive using Gzip compression
Phar::__construct -- Construct a Phar archive object
Phar->count -- Returns the number of entries (files) in the Phar archive
Phar->getMetaData -- Returns phar archive meta-data
Phar->getModified -- Return whether phar was modified
Phar->getSignature -- Return MD5/SHA1 signature of a Phar archive
Phar->getStub -- Return the PHP loader or bootstrap stub of a Phar archive
Phar->getVersion -- Return version info of Phar archive
Phar->isFlushingToPhar -- Used to determine whether a Phar creation transaction is active
Phar::loadPhar -- Loads any phar archive with an alias
Phar::mapPhar -- Reads the currently executed file (a phar) and registers its manifest
Phar::offsetExists -- determines whether a file exists in the phar
Phar::offsetGet -- get a PharFileInfo object for a specific file
Phar::offsetSet -- set the contents of an internal file to those of an external file
Phar::offsetUnset -- remove a file from a phar
Phar->setMetaData -- Sets phar archive meta-data
Phar->setStub -- Used to set the PHP loader or bootstrap stub of a Phar archive
Phar->uncompressAllFiles -- Uncompresses all files in the current Phar archive
PharFileInfo->chmod -- Sets file-specific meta-data saved with a file
PharFileInfo::__construct -- Construct a Phar entry object
PharFileInfo->getCompressedSize -- Returns the actual size of the file (with compression) inside the Phar archive
PharFileInfo->getCRC32 -- Returns CRC32 code or throws an exception if not CRC checked
PharFileInfo->getMetaData -- Returns file-specific meta-data saved with a file
PharFileInfo->getPharFlags -- Returns the Phar file entry flags
PharFileInfo->isCompressed -- Returns whether the entry is compressed
PharFileInfo->isCompressedBZIP2 -- Returns whether the entry is compressed using bzip2
PharFileInfo->isCompressedGZ -- Returns whether the entry is compressed using gz
PharFileInfo->isCRCChecked -- Returns whether file entry has had its CRC verified
PharFileInfo->setCompressedBZIP2 -- Compresses the current Phar entry within the phar using Bzip2 compression
PharFileInfo->setCompressedGZ -- Compresses the current Phar entry within the phar using gz compression
PharFileInfo->setMetaData -- Sets file-specific meta-data saved with a file
PharFileInfo->setUncompressed -- Uncompresses the current Phar entry within the phar, if it is compressed

Prev | Home | Next
PDOStatement->setFetchMode() | Up | Phar::apiVersion


PostScript document creation

PHP Manual
Prev Next

CXXIX. PostScript document creation

Introduction

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.

Requirements

You need at least PHP 4.3.0 and pslib >= 0.1.12. The ps library (pslib) is available at http://pslib.sourceforge.net/.

Installation

A short installation note: just type

$ pecl install ps
in your console.

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.

The following two tables lists all constants defined by the ps extension.

Table 1. Contants for line caps

Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |

Table 2. Contants for line joins

Name | Meaning
ps_LINEJOIN_MITER |
ps_LINEJOIN_ROUND |
ps_LINEJOIN_BEVEL |

Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail steinm@php.net. Any help is very welcome.

Table of Contents
ps_add_bookmark -- Add bookmark to current page
ps_add_launchlink -- Adds link which launches file
ps_add_locallink -- Adds link to a page in the same document
ps_add_note -- Adds note to current page
ps_add_pdflink -- Adds link to a page in a second pdf document
ps_add_weblink -- Adds link to a web location
ps_arc -- Draws an arc counterclockwise
ps_arcn -- Draws an arc clockwise
ps_begin_page -- Start a new page
ps_begin_pattern -- Start a new pattern
ps_begin_template -- Start a new template
ps_circle -- Draws a circle
ps_clip -- Clips drawing to current path
ps_close_image -- Closes image and frees memory
ps_close -- Closes a PostScript document
ps_closepath_stroke -- Closes and strokes path
ps_closepath -- Closes path
ps_continue_text -- Continue text in next line
ps_curveto -- Draws a curve
ps_delete -- Deletes all resources of a PostScript document
ps_end_page -- End a page
ps_end_pattern -- End a pattern
ps_end_template -- End a template
ps_fill_stroke -- Fills and strokes the current path
ps_fill -- Fills the current path
ps_findfont -- Loads a font
ps_get_buffer -- Fetches the full buffer containig the generated PS data
ps_get_parameter -- Gets certain parameters
ps_get_value -- Gets certain values
ps_hyphenate -- Hyphenates a word
ps_lineto -- Draws a line
ps_makespotcolor -- Create spot color
ps_moveto -- Sets current point
ps_new -- Creates a new PostScript document object
ps_open_file -- Opens a file for output
ps_open_image_file -- Opens image from file
ps_open_image -- Reads an image for later placement
ps_place_image -- Places image on the page
ps_rect -- Draws a rectangle
ps_restore -- Restore previously save context
ps_rotate -- Sets rotation factor
ps_save -- Save current context
ps_scale -- Sets scaling factor
ps_set_border_color -- Sets color of border for annotations
ps_set_border_dash -- Sets length of dashes for border of annotations
ps_set_border_style -- Sets border style of annotations
ps_set_info -- Sets information fields of document
ps_set_parameter -- Sets certain parameters
ps_set_text_pos -- Sets position for text output
ps_set_value -- Sets certain values
ps_setcolor -- Sets current color
ps_setdash -- Sets appearance of a dashed line
ps_setflat -- Sets flatness
ps_setfont -- Sets font to use for following output
ps_setgray -- Sets gray value
ps_setlinecap -- Sets appearance of line ends
ps_setlinejoin -- Sets how contected lines are joined
ps_setlinewidth -- Sets width of a line
ps_setmiterlimit -- Sets the miter limit
ps_setpolydash -- Sets appearance of a dashed line
ps_shading_pattern -- Creates a pattern based on a shading
ps_shading -- Creates a shading for later use
ps_shfill -- Fills an area with a shading
ps_show_boxed -- Output text in a box
ps_show_xy -- Output text at given position
ps_show -- Output text
ps_string_geometry -- Gets geometry of a string
ps_stringwidth -- Gets width of a string
ps_stroke -- Draws the current path
ps_symbol_name -- Gets name of a glyph
ps_symbol_width -- Gets width of a glyph
ps_symbol -- Output a glyph
ps_translate -- Sets translation

Prev | Home | Next
system | Up | ps_add_bookmark


Radius

PHP Manual
Prev Next

CXXXII. Radius

Introduction

This package is based on the libradius of FreeBSD. This PECL adds full support for Radius Authentication (RFC 2865) and Radius Accounting (RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Note: An exact description for libradius can be found here. A detailed description of the configuration file can be found here.

Installation

Howto install the package?

  • untar the package (usually into php4/ext)

  • rename radius-x.x to radius

  • run ./buildconf in php4

  • run ./configure --enable-radius

  • make; make install

or if you would like to have it as .so:

  • untar the package

  • run phpize in the radius-x.x directory

  • run ./configure in the radius-x.x directory

  • make; make install

For windows I recommend to use the php_radius.dll from http://snaps.php.net/. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.

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.

RADIUS_ACCESS_REQUEST ()

Authentication Request

RADIUS_ACCESS_ACCEPT ()

Access accepted

RADIUS_ACCESS_REJECT ()

Access rejected

RADIUS_ACCOUNTING_REQUEST ()

Accounting request

RADIUS_ACCOUNTING_RESPONSE ()

Accounting response

RADIUS_ACCESS_CHALLENGE ()

Accsess challenge

RADIUS_USER_NAME (string)

Username

RADIUS_USER_PASSWORD (string)

Password

RADIUS_CHAP_PASSWORD (string)

Chap Password: chappass = md5(ident + plaintextpass + challenge)

RADIUS_NAS_IP_ADDRESS (string)

NAS IP-Adress

RADIUS_NAS_PORT (int)

NAS Port

RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

RADIUS_LOGIN
RADIUS_FRAMED
RADIUS_CALLBACK_LOGIN
RADIUS_CALLBACK_FRAMED
RADIUS_OUTBOUND
RADIUS_ADMINISTRATIVE
RADIUS_NAS_PROMPT
RADIUS_AUTHENTICATE_ONLY
RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

RADIUS_PPP
RADIUS_SLIP
RADIUS_ARAP
RADIUS_GANDALF
RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (string)

IP-Address

RADIUS_FRAMED_IP_NETMASK (string)

Netmask

RADIUS_FRAMED_ROUTING (int)

Routing

RADIUS_FILTER_ID (string)

Filter ID

RADIUS_FRAMED_MTU (int)

MTU

RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

RADIUS_COMP_NONE
RADIUS_COMP_VJ
RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)

Login IP Host

RADIUS_LOGIN_SERVICE (int)

Login Service

RADIUS_LOGIN_TCP_PORT (int)

Login TCP Port

RADIUS_REPLY_MESSAGE (string)

Reply Message

RADIUS_CALLBACK_NUMBER (string)

Callback Number

RADIUS_CALLBACK_ID (string)

Callback ID

RADIUS_FRAMED_ROUTE (string)

Framed Route

RADIUS_FRAMED_IPX_NETWORK (string)

Framed IPX Network

RADIUS_STATE (string)

State

RADIUS_CLASS (int)

Class

RADIUS_VENDOR_SPECIFIC (int)

Vendor specific attribute

RADIUS_SESSION_TIMEOUT (int)

Session timeout

RADIUS_IDLE_TIMEOUT (int)

Idle timeout

RADIUS_TERMINATION_ACTION (int)

Termination action

RADIUS_CALLED_STATION_ID (int)

Called Station Id

RADIUS_CALLING_STATION_ID (string)

Calling Station Id

RADIUS_NAS_IDENTIFIER (int)

NAS ID

RADIUS_PROXY_STATE (int)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (int)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (int)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (int)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (int)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (int)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (int)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (string)

Challenge

RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

RADIUS_ASYNC
RADIUS_SYNC
RADIUS_ISDN_SYNC
RADIUS_ISDN_ASYNC_V120
RADIUS_ISDN_ASYNC_V110
RADIUS_VIRTUAL
RADIUS_PIAFS
RADIUS_HDLC_CLEAR_CHANNEL
RADIUS_X_25
RADIUS_X_75
RADIUS_G_3_FAX
RADIUS_SDSL
RADIUS_ADSL_CAP
RADIUS_ADSL_DMT
RADIUS_IDSL
RADIUS_ETHERNET
RADIUS_XDSL
RADIUS_CABLE
RADIUS_WIRELESS_OTHER
RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)

Port Limit

RADIUS_LOGIN_LAT_PORT (int)

Login LAT Port

RADIUS_CONNECT_INFO (string)

Connect info

RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

RADIUS_START
RADIUS_STOP
RADIUS_ACCOUNTING_ON
RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (int)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (int)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (int)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

RADIUS_AUTH_RADIUS
RADIUS_AUTH_LOCAL
RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (int)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (int)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

RADIUS_TERM_USER_REQUEST
RADIUS_TERM_LOST_CARRIER
RADIUS_TERM_LOST_SERVICE
RADIUS_TERM_IDLE_TIMEOUT
RADIUS_TERM_SESSION_TIMEOUT
RADIUS_TERM_ADMIN_RESET
RADIUS_TERM_ADMIN_REBOOT
RADIUS_TERM_PORT_ERROR
RADIUS_TERM_NAS_ERROR
RADIUS_TERM_NAS_REQUEST
RADIUS_TERM_NAS_REBOOT
RADIUS_TERM_PORT_UNNEEDED
RADIUS_TERM_PORT_PREEMPTED
RADIUS_TERM_PORT_SUSPENDED
RADIUS_TERM_SERVICE_UNAVAILABLE
RADIUS_TERM_CALLBACK
RADIUS_TERM_USER_ERROR
RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (int)

Accounting link count

RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (RFC 2548), one of:

RADIUS_MICROSOFT_MS_CHAP_RESPONSE
RADIUS_MICROSOFT_MS_CHAP_ERROR
RADIUS_MICROSOFT_MS_CHAP_PW_1
RADIUS_MICROSOFT_MS_CHAP_PW_2
RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
RADIUS_MICROSOFT_MS_RAS_VENDOR
RADIUS_MICROSOFT_MS_CHAP_DOMAIN
RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
RADIUS_MICROSOFT_MS_BAP_USAGE
RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
RADIUS_MICROSOFT_MS_RAS_VERSION
RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
RADIUS_MICROSOFT_MS_FILTER
RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
RADIUS_MICROSOFT_MS_CHAP2_PW
RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

Quickstart

Howto start?

  • get a radius resource

  • configure the library

  • create the request

  • put attributes

  • send the request

  • receive attributes

  • close the radius resource (optional)

Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.

Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at mbretter@php.net. Binaries for Windows can be downloaded from here.

Table of Contents
radius_acct_open -- Creates a Radius handle for accounting
radius_add_server -- Adds a server
radius_auth_open -- Creates a Radius handle for authentication
radius_close -- Frees all ressources
radius_config -- Causes the library to read the given configuration file
radius_create_request -- Create accounting or authentication request
radius_cvt_addr -- Converts raw data to IP-Address
radius_cvt_int -- Converts raw data to integer
radius_cvt_string -- Converts raw data to string
radius_demangle_mppe_key -- Derives mppe-keys from mangled data
radius_demangle -- Demangles data
radius_get_attr -- Extracts an attribute
radius_get_vendor_attr -- Extracts a vendor specific attribute
radius_put_addr -- Attaches an IP-Address attribute
radius_put_attr -- Attaches a binary attribute
radius_put_int -- Attaches an integer attribute
radius_put_string -- Attaches a string attribute
radius_put_vendor_addr -- Attaches a vendor specific IP-Address attribute
radius_put_vendor_attr -- Attaches a vendor specific binary attribute
radius_put_vendor_int -- Attaches a vendor specific integer attribute
radius_put_vendor_string -- Attaches a vendor specific string attribute
radius_request_authenticator -- Returns the request authenticator
radius_send_request -- Sends the request and waites for a reply
radius_server_secret -- Returns the shared secret
radius_strerror -- Returns an error message

Prev | Home | Next
qdom_tree | Up | radius_acct_open


RPM Header Reading Functions

PHP Manual
Prev Next

CXXXVI. RPM Header Reading Functions

Introduction

This module allows you to read the meta information stored in the headers of a RedHat Package Manager (RPM) file.

Requirements

The RPMReader extension requires PHP 5.

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/rpmreader.

Resource Types

There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.

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 list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.

RPMREADER_MINIMUM (integer)

The minimum valid value of any RPM tag number.

RPMREADER_NAME (integer)

The name of the RPM package.

RPMREADER_VERSION (integer)

The version of the RPM package.

RPMREADER_RELEASE (integer)

The release of the RPM package.

RPMREADER_EPOCH (integer)

RPMREADER_SERIAL (integer)

RPMREADER_SUMMARY (integer)

The summary text of the RPM package.

RPMREADER_DESCRIPTION (integer)

The full description text of the RPM package.

RPMREADER_BUILDTIME (integer)

The date and time when the RPM package was built.

RPMREADER_BUILDHOST (integer)

The name of the host on which the RPM package was built.

RPMREADER_INSTALLTIME (integer)

RPMREADER_SIZE (integer)

The size of the RPM package.

RPMREADER_DISTRIBUTION (integer)

RPMREADER_VENDOR (integer)

RPMREADER_GIF (integer)

RPMREADER_XPM (integer)

RPMREADER_LICENSE (integer)

RPMREADER_COPYRIGHT (integer)

RPMREADER_PACKAGER (integer)

RPMREADER_GROUP (integer)

RPMREADER_SOURCE (integer)

RPMREADER_PATCH (integer)

RPMREADER_URL (integer)

RPMREADER_OS (integer)

RPMREADER_ARCH (integer)

RPMREADER_PREIN (integer)

RPMREADER_POSTIN (integer)

RPMREADER_PREUN (integer)

RPMREADER_POSTUN (integer)

RPMREADER_OLDFILENAMES (integer)

The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.

RPMREADER_FILESIZES (integer)

RPMREADER_FILESTATES (integer)

RPMREADER_FILEMODES (integer)

RPMREADER_FILERDEVS (integer)

RPMREADER_FILEMTIMES (integer)

RPMREADER_FILEMD5S (integer)

RPMREADER_FILELINKTOS (integer)

RPMREADER_FILEFLAGS (integer)

RPMREADER_FILEUSERNAME (integer)

RPMREADER_FILEGROUPNAME (integer)

RPMREADER_ICON (integer)

RPMREADER_SOURCERPM (integer)

RPMREADER_FILEVERIFYFLAGS (integer)

RPMREADER_ARCHIVESIZE (integer)

RPMREADER_PROVIDENAME (integer)

RPMREADER_PROVIDES (integer)

RPMREADER_REQUIREFLAGS (integer)

RPMREADER_REQUIRENAME (integer)

RPMREADER_REQUIREVERSION (integer)

RPMREADER_CONFLICTFLAGS (integer)

RPMREADER_CONFLICTNAME (integer)

RPMREADER_CONFLICTVERSION (integer)

RPMREADER_EXCLUDEARCH (integer)

RPMREADER_EXCLUDEOS (integer)

RPMREADER_EXCLUSIVEARCH (integer)

RPMREADER_EXCLUSIVEOS (integer)

RPMREADER_RPMVERSION (integer)

RPMREADER_TRIGGERSCRIPTS (integer)

RPMREADER_TRIGGERNAME (integer)

RPMREADER_TRIGGERVERSION (integer)

RPMREADER_TRIGGERFLAGS (integer)

RPMREADER_TRIGGERINDEX (integer)

RPMREADER_VERIFYSCRIPT (integer)

RPMREADER_CHANGELOGTIME (integer)

The list of dates from changelog entries.

RPMREADER_CHANGELOGNAME (integer)

The list of changelog entry names.

RPMREADER_CHANGELOGTEXT (integer)

The list of the text from changelog entries.

RPMREADER_PREINPROG (integer)

RPMREADER_POSTINPROG (integer)

RPMREADER_PREUNPROG (integer)

RPMREADER_POSTUNPROG (integer)

RPMREADER_BUILDARCHS (integer)

RPMREADER_OBSOLETENAME (integer)

RPMREADER_OBSOLETES (integer)

RPMREADER_VERIFYSCRIPTPROG (integer)

RPMREADER_TRIGGERSCRIPTPROG (integer)

RPMREADER_COOKIE (integer)

RPMREADER_FILEDEVICES (integer)

RPMREADER_FILEINODES (integer)

RPMREADER_FILELANGS (integer)

RPMREADER_PREFIXES (integer)

RPMREADER_INSTPREFIXES (integer)

RPMREADER_PROVIDEFLAGS (integer)

RPMREADER_PROVIDEVERSION (integer)

RPMREADER_OBSOLETEFLAGS (integer)

RPMREADER_OBSOLETEVERSION (integer)

RPMREADER_DIRINDEXES (integer)

The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_BASENAMES (integer)

The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_DIRNAMES (integer)

The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_OPTFLAGS (integer)

RPMREADER_DISTURL (integer)

RPMREADER_PAYLOADFORMAT (integer)

RPMREADER_PAYLOADCOMPRESSOR (integer)

RPMREADER_PAYLOADFLAGS (integer)

RPMREADER_INSTALLCOLOR (integer)

RPMREADER_INSTALLTID (integer)

RPMREADER_REMOVETID (integer)

RPMREADER_RHNPLATFORM (integer)

RPMREADER_PLATFORM (integer)

RPMREADER_PATCHESNAME (integer)

RPMREADER_PATCHESFLAGS (integer)

RPMREADER_PATCHESVERSION (integer)

RPMREADER_CACHECTIME (integer)

RPMREADER_CACHEPKGPATH (integer)

RPMREADER_CACHEPKGSIZE (integer)

RPMREADER_CACHEPKGMTIME (integer)

RPMREADER_FILECOLORS (integer)

RPMREADER_FILECLASS (integer)

RPMREADER_CLASSDICT (integer)

RPMREADER_FILEDEPENDSX (integer)

RPMREADER_FILEDEPENDSN (integer)

RPMREADER_DEPENDSDICT (integer)

RPMREADER_SOURCEPKGID (integer)

RPMREADER_FILECONTEXTS (integer)

RPMREADER_FSCONTEXTS (integer)

RPMREADER_RECONTEXTS (integer)

RPMREADER_POLICIES (integer)

RPMREADER_MAXIMUM (integer)

The maximum valid value of any RPM tag number.

Examples

This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.

Example 1. Basic RPMReader Example

&#60;?php

$filename = "/path/to/file.rpm";

// open file
$rpmr = rpm_open($filename);

// get "Name" tag
$name = rpm_get_tag($rpmr, RPMREADER_NAME);

// get "Version" tag
$ver = rpm_get_tag($rpmr, RPMREADER_VERSION);

// get "Release" tag
$rel = rpm_get_tag($rpmr, RPMREADER_RELEASE);

echo "$name-$ver-$rel&#60;br&#62;\n";

// close file
rpm_close($rpmr);

?&#62;
Table of Contents
rpm_close -- Closes an RPM file
rpm_get_tag -- Retrieves a header tag from an RPM file
rpm_is_valid -- Tests a filename for validity as an RPM file
rpm_open -- Opens an RPM file
rpm_version -- Returns a string representing the current version of the rpmreader extension

Prev | Home | Next
recode | Up | rpm_close


runkit Functions

PHP Manual
Prev Next

CXXXVII. runkit Functions

Introduction

The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.

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/runkit.

This package is meant as a feature added replacement for the classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.

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/runkit.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Requirements

Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.

Custom Superglobals are only available in PHP 4.2.0 or later.

Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Runkit Configuration Options

Name | Default | Changeable | Changelog
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

runkit.superglobal string

Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Example 1. Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

&#60;?php
function show_values() {
  echo "Foo is $_FOO\n";
  echo "Bar is $_BAR\n";
  echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?&#62;

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.

RUNKIT_IMPORT_FUNCTIONS (integer)

runkit_import() flag indicating that normal functions should be imported from the specified file.

RUNKIT_IMPORT_CLASS_METHODS (integer)

runkit_import() flag indicating that class methods should be imported from the specified file.

RUNKIT_IMPORT_CLASS_CONSTS (integer)

runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.

RUNKIT_IMPORT_CLASS_PROPS (integer)

runkit_import() flag indicating that class standard properties should be imported from the specified file.

RUNKIT_IMPORT_CLASSES (integer)

runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.

RUNKIT_IMPORT_OVERRIDE (integer)

runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.

RUNKIT_ACC_PUBLIC (integer)

PHP5 specific flag to runkit_method_add()

RUNKIT_ACC_PROTECTED (integer)

PHP5 specific flag to runkit_method_add()

RUNKIT_ACC_PRIVATE (integer)

PHP5 specific flag to runkit_method_add()

CLASSKIT_ACC_PUBLIC (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_ACC_PROTECTED (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_ACC_PRIVATE (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_AGGREGATE_OVERRIDE (integer)

PHP5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.

RUNKIT_VERSION (string)

Defined to the current version of the runkit package.

CLASSKIT_VERSION (string)

Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.

Table of Contents
Runkit_Sandbox -- Runkit Sandbox Class -- PHP Virtual Machine
Runkit_Sandbox_Parent -- Runkit Anti-Sandbox Class
runkit_class_adopt -- Convert a base class to an inherited class, add ancestral methods when appropriate
runkit_class_emancipate -- Convert an inherited class to a base class, removes any method whose scope is ancestral
runkit_constant_add -- Similar to define(), but allows defining in class definitions as well
runkit_constant_redefine -- Redefine an already defined constant
runkit_constant_remove -- Remove/Delete an already defined constant
runkit_function_add -- Add a new function, similar to create_function()
runkit_function_copy -- Copy a function to a new function name
runkit_function_redefine -- Replace a function definition with a new implementation
runkit_function_remove -- Remove a function definition
runkit_function_rename -- Change a function's name
runkit_import -- Process a PHP file importing function and class definitions, overwriting where appropriate
runkit_lint_file -- Check the PHP syntax of the specified file
runkit_lint -- Check the PHP syntax of the specified php code
runkit_method_add -- Dynamically adds a new method to a given class
runkit_method_copy -- Copies a method from class to another
runkit_method_redefine -- Dynamically changes the code of the given method
runkit_method_remove -- Dynamically removes the given method
runkit_method_rename -- Dynamically changes the name of the given method
runkit_return_value_used -- Determines if the current functions return value will be used
runkit_sandbox_output_handler -- Specify a function to capture and/or process output from a runkit sandbox
runkit_superglobals -- Return numerically indexed array of registered superglobals

Prev | Home | Next
rpm_version | Up | Runkit_Sandbox


SAM - Simple Asynchronous Messaging

PHP Manual
Prev Next

CXXXVIII. SAM - Simple Asynchronous Messaging

Introduction

This extension provides access to the functionality of messaging and queueing systems, such as the IBM WebSphere MQSeries family of products, from PHP scripts. The interface is designed to make it extremely simple to do the more commonly required tasks such as deliver simple text messages to queues while still allowing skilled users to do more complex messaging operations. For many users the complexities of setting up numerous options can be simply ignored.

The SAM extension is a framework that provides a very simple API that can be used to access a number of messaging middleware systems. Currently the package includes built-in support for the MQTT (MQ Telemetry Transport) messaging protocol and support for the IBM Messaging and Queuing middleware products. SAM is designed to be readily extended to support other messaging systems and extension modules may be written in C or PHP.

Installation

The SAM framework and MQTT support can be built and used without any other prerequisites. Support for protocols other than MQTT is provided via a set of libraries and some client side code referred to as XMS.

If you only intend to use the built-in MQTT support then you can build and configure SAM as an extension or simply refer to "php_sam.php" with a "requires" or "requires_once" clause in your PHP script. In this case you need only install the code without building the extension using the pear installer:

pecl install -B SAM

Prerequisites

The SAM extension interfaces to the IBM Messaging and Queuing middleware products using a set of libraries and some client side code referred to as XMS. This package is available as a free download in the guise of IBM support pack IA94. There is a description of this package and download links in the article Introducing XMS - The IBM Message Service API.

If you intend to use SAM to access the Messaging and Queuing infrastructure within WebSphere MQ then you will also need to have installed a local MQ queue manager or installed the WebSphere MQ clients package. The clients package is freely available as a support pack (MQC6).

If you are only aiming to experiment with sending messages to and from WebSphere Application Server queues using the WebSphere Platform Messaging protocol (WPM) then you do not need to install the MQC6 package.

After installing these packages you will need to ensure the XMS binary and, if you are using it, the MQ client bin directory are included in the PATH environment variable so that Apache and PHP can find the dependent .DLLs/libraries.

Linux installation steps

The sam extension is supplied as a PECL module, which you should be able to download and install in one step as follows:

pecl install sam
(Depending on your php environment, you will probably need to be root to do this.)

Make sure that the module is loaded by PHP, by adding following line to php.ini:

extension=sam.so
If you intend to use the XMS support to access the IBM Messaging and Queuing family you must also enable the SAM XMS extension.
extension=sam_xms.so

If you cannot use the PEAR installer, you can download the extension and build it manually:

pear download sam          #downloads sam-<version>.tgz
tar -xzf sam-<version>.tgz
cd sam-<version>
phpize
./configure
make
make install               #you may need to be root for this step

To work with the very latest source, you'll need to extract it from cvs and build manually as above.

Windows installation steps

You will probably need to build the sam extension for Windows as there are only a limited range of pre-built binaries available from the SAM website. The extension can be built using the standard Windows extension build procedures.

You will need the PHP source tree for the version of PHP you wish to build the SAM extension against which you can obtain from php.net. This should be unpacked into a working directory of your choice.

You will also need the libraries and headers used by PHP extensions available from http://www.php.net/extra/win32build.zip and this should be unzipped so that is in your working directory.

You should have something like:

c:\php-build\-
              |
              |---php-5.0.5--|---build
              |              |---ext
              |              |--- ...
              |
              |---win32build--|---bin
                              |---include
                              |---lib

You will need a compiler such as the free version of Visual Studio C++ Express from the Microsoft web site. Also you need the Microsoft Windows Platform SDK which again can be downloaded from the Microsoft web site.

Obtain the SAM extension source using pear (pecl download sam) or by using CVS and copy the files to a new "sam" directory under the "ext" directory in your PHP source tree.

To build the extension open a build environment window by going to the start menu->all programs->microsoft platform SDK for windows-> open build environment window->windows 200 build environment-> set windows 2000 build environment (retail)

This should open a command prompt with all the environment variables set up to access the platform SDK etc. You then need to set the environment variables for Visual Studio by issuing the command "vcvars32.bat" in the window.

Change directory to your working directory e.g. cd c:\php-build. Then make sure the win32build tools are accessible by adding them to the PATH environment variable:

set PATH=..\win32build\bin;%PATH%

Run the buildconf.bat command. This should rebuild the configure.js file.

Run the cscript command with the appropriate options. To build just the SAM extension framework and MQTT support use:

cscript /nologo configure.js --with-sam
To build the SAM framework and the XMS support use:
cscript /nologo configure.js --with-sam --with-sam_xms="c:\program files\ibm\xms"

The additional parameter passed for sam_xms is the installation path to the XMS libraries and runtime that were installed as described under prerequisites at the top of this page.

You can specify whatever other cscript parameters you require to include or exclude items from the php build or select options.

Assuming all has gone well so far you can now finally run a make for the SAM framework!

nmake php_sam.dll
Also if you are using the XMS support you must make the sam_xms extensions:
nmake php_sam_xms.dll

If you have used Visual Studio 2005 to build the DLLs please see below for additional steps that must be carried out before proceeding further.

The DLLs created (php_sam.dll and optionally php_sam_xms.dll) can now be copied to the subdirectory appropriate for your PHP set-up. Make sure that the module(s) are loaded by PHP, by adding following line to php.ini :

extension=php_sam.dll
If you intend to use the XMS support to access the IBM Messgaing and Queuing family you must also enable the SAM XMS extension.
extension=php_sam_xms.dll

Additional steps for Visual Studio 2005

If you build the SAM extension with the Microsoft Visual Studio 2005 compiler and tools you need to perform an additional step in the build process to ensure the php_sam.dll is able to link with the C runtime libraries at runtime. This step includes the dependancy manifest into the DLL. Switch to the directory where the php_sam.dll has been generated (usually Release_TS or Debug_TS below the php source directory) and issue the following magic incantation:

mt.exe -manifest php_sam.dll.manifest -outputresource:php_sam.dll;2
If you are using the XMS capabilities you will need to do the same with the SAM XMS DLL:
mt.exe -manifest php_sam_xms.dll.manifest -outputresource:php_sam_xms.dll;2

If you build the SAM extension using the compiler and libaries from Microsoft Visual Studio 2005 you will also need to ensure that the runtime components are installed on the system on which you intend to use SAM. This can be accomplished by installing Visual Studio 2005 or by using the freely distributable runtime package.

Protocol support and mapping

The SAM framework can be extended to support other messaging protocols and connection mechanisms. To add support for a new protocol or connection library a support class has to be defined, either as a C extension or as a PHP script, and a "factory" script must be created. The support class must implement all the methods of the SAMConnection class though it should not inherit from SAMConnection. The factory script will be called by the SAM framework to create an instance of the implemented class. The way SAM chooses which factory to call is based on the protocol specified as the first parameter of the "connect" call.

By default the built-in MQTT support will be used if a connect call specifies a protocol of SAM_MQTT ("mqtt"), for any other protocol SAM will attempt to use the XMS support extension. To add support for additional protocols or to modify the default behavior entries may be added to php.ini in the [sam] section. The default mapping is equivalent to the following entries:

[sam]
sam.factory.mqtt=mqtt
sam.factory.wmq=xms
sam.factory.wmq:client=xms
sam.factory.wmq:bindings=xms
sam.factory.wpm=xms
sam.factory.rtt=xms
As can be seen from these examples the entries take the form of "sam.factory.pppp=xxx" where pppp is the protocol string specified on the connect call and xxx is a factory suffix. Note: SAM defines constants for these protocol strings such that SAM_WMQ=wmq, SAM_WPM=wpm, SAM_RTT=rtt, SAM_MQTT=mqtt, etc.

When identifying the support code to use on a connect call SAM looks up the protocol name in the php.ini entries and then invokes a factory script named sam_factory_xxx.php. If no entry is found the support will default to XMS.

API Usage

Connections

In order to perform any messaging and queueing functions a connection must be established with a messaging server by creating a SAMConnection object and calling its "connect" method, with a set of connection properties, to connect the PHP script to the messaging server. Until such time as the SAMConnection object is destroyed the connection will be maintained and available for use. All SAMConnection objects are destroyed when the PHP script exits.

A set of default properties may be used in connecting to a messaging server but as a minimum the PHP script must specify a protocol to be used.

Example 1. Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server

&#60;?php
   $conn = new SAMConnection();
   $conn-&#62;connect(SAM_WMQ, array(SAM_HOST =&#62; 'myhost.mycompany.com',
                                 SAM_PORT =&#62; 1506,
                                 SAM_BROKER =&#62; 'mybroker'));
?&#62;

Example 2. Creating a connection and connecting to a remote WebSphere Application Server

&#60;?php
   $conn = new SAMConnection();
   $conn-&#62;connect(SAM_WPM, array(SAM_ENDPOINTS =&#62; 'localhost:7278:BootstrapBasicMessaging',
                                 SAM_BUS =&#62; 'Bus1',
                                 SAM_TARGETCHAIN =&#62; 'InboundBasicMessaging'));
?&#62;

Example 3. Creating a connection and connecting to an MQTT server

&#60;?php
   $conn = new SAMConnection();
   $conn-&#62;connect(SAM_MQTT, array(SAM_HOST =&#62; 'myhost.mycompany.com',
                                 SAM_PORT =&#62; 1883));
?&#62;

Messages

Messages sent to and received from queues are represented by the SAMMessage object. The SAMMessage object encapsulates the body of the message (if one exists) and the header properties associated with the message. A SAMMessage object is either supplied as a parameter to a messaging operation or returned as a result.

Example 4. Creating a message with a simple text body

&#60;?php
$msg = new SAMMessage('This is a simple text message');
?&#62;

Messages may have header properties associated with them that provide control over the transport of the message or further information to the receiving application. By default message properties are delivered to the underlying messaging system as strings and in this case they may be set with the following simple syntax:

Example 5. Setting a text format property using the default syntax

&#60;?php
   $msg-&#62;header-&#62;myPropertyName = 'textData';
?&#62;

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Example 6. Setting a property using a type hint

&#60;?php
   $msg-&#62;header-&#62;myPropertyName = array(3.14159, SAM_FLOAT);
?&#62;

Properties may also be extracted from the header of a message.

Example 7. Retrieving a property from a message header

&#60;?php
   $myProperty = $msg-&#62;header-&#62;myPropertyName;
?&#62;

Messaging operations

All messaging operations are performed through calls to methods on the connection object. To add a message to a queue the "send" method is used, to obtain a message from a queue the "receive" method is used. Other methods provide publish and subscribe functionality and control of transaction boundaries.

Example 8. Adding a message to a queue and receiving a response

&#60;?php
$msg = new SAMMessage('This is a simple text message');
$msg-&#62;header-&#62;SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn-&#62;send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
} else {
  $resp = $conn-&#62;receive('queue://receive/test', array(SAM_CORRELID =&#62; $correlid));
}
?&#62;

Publish/Subscribe and suscriptions to topics

SAM allows messages to be sent either to queues or, for WebSphere MQ and WPM, to publish/subscribe topics. A topic desintation is specified to SAM in the usual way, i.e. in the form 'topic://fred', rather than the form 'queue://AQUEUE' used for point to point operation. To use publish/subscribe it is simply necessary to specify the correct broker name on the SAMConnect "connect" call and the desired topic in the destination argument to the SAMConnect "send" and "receive" calls. The PHP interface is otherwise identical to the point to point model.

By default, SAM creates non-durable subscriptions when using publish/subscribe. This means that if a client application is inactive when messages are published to a topic, then it will not receive them when it subsequently restarted. SAM does also allow durable subscriptions to be made to topics when using WPM or WebSphere MQ publish/subscribe. The purpose of these subscriptions is to allow data to be received by a client application even if that client was not active at the time the data was published.

Durable subscriptions are specified by using the SAMConnect "subscribe" call. This method takes the destination topic as an input parameter and returns a subscription identifier that may be used on subsequent "receive" calls. When the subscription is no longer required the SAMConnection "unsubscribe" method should be used to delete the subscription.

Example 9. Creating a durable subscription to a topic

&#60;?php

$subName = $conn-&#62;subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?&#62;

Example 10. Subscribing to a topic using a WebSphere Platform Messaging (WPM) server

&#60;?php
$conn = new SAMConnection();
// Note: For pub/sub on WPM, when connecting the name of a messaging engine
//   to hold the durable subscription (SAM_WPM_DUR_SUB_HOME) must be specified.
$conn-&#62;connect(SAM_WMQ, array(SAM_ENDPOINTS =&#62; 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS =&#62; 'Bus1',
                              SAM_TARGETCHAIN =&#62; 'InboundBasicMessaging'
                              SAM_WPM_DUR_SUB_HOME =&#62; 'MyMachineNode01.server1-Bus1'));

$subName = $conn-&#62;subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?&#62;

Example 11. Receiving published data using a durable subscription

&#60;?php

$msg = $conn-&#62;receive($subName);
if ($msg) {
   echo "Received a message OK";
} else {
   echo "The receive failed";
}

?&#62;

Example 12. Deleting a durable subscription to a topic

&#60;?php

if (!$conn-&#62;unsubscribe($subName)) {
   echo "Unsubscribe failed";
}

?&#62;

Error handling

All SAMConnection methods that provide access to messaging operations return FALSE if an error occurred in processing the request. In addition the SAMConnection object has two properties, "errno" and "error", that provide respectively the error number and text description of the last error to occur on the connection.

Example 13. Handling an error from a method that returns no result

&#60;?php
   if (!$conn-&#62;commit()) {
     // The commit failed!
     echo "Commit failed ($conn-&#62;errno) $conn-&#62;error";
   }
?&#62;

Example 14. Handling an error from a method that returns a result

&#60;?php
$correlid = $conn-&#62;send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn-&#62;errno) $conn-&#62;error";
} else {
  ...
}
?&#62;

Predefined Classes

SAMConnection

Object representing a connection to a Messaging Server

Constructor

  • new SAMConnection - construct a new connection object to allow connection to a messaging infrastructure.

Methods

  • commit - a method that commits (successfully completes) an in-flight unit of work.

  • connect - a method that connects a PHP script to a messaging server.

  • disconnect - a method that disconnects a PHP script from a messaging server.

  • isConnected - a method that checks whether a PHP script is connected to a messaging server.

  • peek - a method that receives a message from a queue without removing it from the queue.

  • peekAll - a method that receives one or messages from a queue without removing them from the queue.

  • receive - a method that receives a message from a queue or subscription.

  • remove - a method that removes a message from a queue.

  • rollback - a method that cancels (rolls back) an in-flight unit of work.

  • send - a method that sends a message to a queue or posts to a topic

  • setDebug - a method that switches additional debugging output on or off

  • subscribe - a method that creates a subscription to one or more topics

  • unsubscribe - a method that destroys a subscription to one or more topics

Properties

  • errno - the numeric error code for the last encountered error on this connection. This property is set to 0 if the last operation was successful.

  • error - the text description for the last encountered error on this connection

SAMMessage

Object representing a message to be sent or received

Constructor

  • new SAMMessage - construct a new message.

Properties

  • body - the body of the message.

  • header - the header properties of the message.

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.

SAM_AUTO (string)

Automatic behaviour

SAM_BOOLEAN (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_BUS (string)

Connect attribute used to set the name of the enterprise service bus to connect to.

SAM_BYTE (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_BYTES (string)

Message body type descriptor.

SAM_CORRELID (string)

Attribute used on receive, send and remove requests to identify specific messages.

SAM_DELIVERYMODE (string)

Message header property.

SAM_DOUBLE (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_ENDPOINTS (string)

Connect attribute used to define the possible endpoints to connect to.

SAM_FLOAT (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_HOST (string)

Connect attribute used to set the hostname of the required messaging server.

SAM_INT (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_LONG (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_MANUAL (string)

Manual (script controlled) behaviour

SAM_MESSAGEID (string)

Attribute used on receive and remove requests to identify specific messages.

SAM_MQTT (string)

Connect protocol definition for selecting the MQTT (MQ Telemetry Transport) protocol.

SAM_MQTT_CLEANSTART (bool)

Optional connect option to indicate to an MQTT server that all previous connection data for this client should be removed and that subscriptions should be deleted when the client disconnects explicitly or unexpectedly.

SAM_NON_PERSISTENT (string)

Connect attribute value used to request messages are not made persistent on the messaging server.

SAM_PASSWORD (string)

Connect attribute used to define the password to be used for the user account being used to connect to a messaging server that requires authorisation for connections.

SAM_PERSISTENT (string)

Connect attribute value used to request messages are made persistent on the messaging server to protect against loss of messages in the event of failure.

SAM_PORT (string)

Connect attribute used to set the port number on which to communicate with the messaging server.

SAM_PRIORITY (string)

Option name used on send requests to specify a delivery priority value.

SAM_REPLY_TO (string)

Message propery used to specify the queue identity on to which the script expects response or reply messages to be posted.

SAM_RTT (string)

Connect protocol definition for selecting the IBM Realtime Transport protocol for communication with a business integration messaging server.

SAM_STRING (string)

Type specifier used when setting properties on SAM_Message objects.

SAM_TARGETCHAIN (string)

Connection attribute used to set the required target chain identifier.

SAM_TEXT (string)

Message body type descriptor.

SAM_TIMETOLIVE (string)

Message send option name used to specify the length of time a message should be retained in milliseconds.

SAM_TRANSACTIONS (string)

Connection attribute used to set required transactional behaviour. May be set to SAM_AUTO (default) or SAM_MANUAL.

SAM_USERID (string)

Connect attribute used to define the account to being used to connect to a messaging server that requires authorisation for connections.

SAM_WAIT (string)

Receive property used to specify the wait timeout to be used when receiving a message from a queue or subscription.

SAM_WMQ (string)

Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with the desired messaging server.

SAM_WMQ_BINDINGS (string)

Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a local messaging server.

SAM_WMQ_CLIENT (string)

Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a remote messaging server.

SAM_WMQ_TARGET_CLIENT (string)

Option name used on send requests to specify the target client mode. This can either be default to 'jms' or 'mq'. The default is 'jms' which means an RFH2 header is sent with the message whereas the 'mq' setting means no RFH2 is included.

SAM_WPM (string)

Connect protocol definition for selecting the IBM WebSphere Platform Messaging protocol for communication with a WebSphere Application Server messaging server.

Table of Contents
SAMConnection->commit() -- Commits (completes) the current unit of work.
SAMConnection->connect() -- Establishes a connection to a Messaging Server
SAMConnection->__construct() -- Creates a new connection to a Messaging Server
SAMConnection->disconnect() -- Disconnects from a Messaging Server
SAMConnection->errno -- Contains the unique numeric error code of the last executed SAM operation.
SAMConnection->error -- Contains the text description of the last failed SAM operation.
SAMConnection->isConnected() -- Queries whether a connection is established to a Messaging Server
SAMConnection->peek() -- Read a message from a queue without removing it from the queue.
SAMConnection->peekAll() -- Read one or more messages from a queue without removing it from the queue.
SAMConnection->receive() -- Receive a message from a queue or subscription.
SAMConnection->remove() -- Remove a message from a queue.
SAMConnection->rollback() -- Cancels (rolls back) an in-flight unit of work.
SAMConnection->send() -- Send a message to a queue or publish an item to a topic.
SAMConnection::setDebug() -- Turn on or off additional debugging output.
SAMConnection->subscribe() -- Create a subscription to a specified topic.
SAMConnection->unsubscribe() -- Cancel a subscription to a specified topic.
SAMMessage->body -- The body of the message.
SAMMessage->__construct() -- Creates a new Message object
SAMMessage->header -- The header properties of the message.

Prev | Home | Next
runkit_superglobals | Up | SAMConnection->commit()


Satellite CORBA client extension [deprecated]

PHP Manual
Prev Next

CXXXIX. Satellite CORBA client extension [deprecated]

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.

Note: This extension is not available on Windows platforms.

Satellite is deprecated. It is suggested that you use Universe (http://universe-phpext.sourceforge.net/) and not Satellite.

The Satellite extension is used for accessing CORBA objects. You will need to set the idl_directory= entry in php.ini to a path where you store all IDL files you use.

See the Satellite README file for details about installing Satellite.

Table of Contents
OrbitEnum -- Use CORBA enums
OrbitObject -- Access CORBA objects
OrbitStruct -- Use CORBA structs
satellite_caught_exception -- See if an exception was caught from the previous function
satellite_exception_id -- Get the repository id for the latest exception.
satellite_exception_value -- Get the exception struct for the latest exception
satellite_get_repository_id -- NOT IMPLEMENTED
satellite_load_idl -- Instruct the type manager to load an IDL file
satellite_object_to_string -- Convert an object to its string representation

Prev | Home | Next
SAMMessage->header | Up | OrbitEnum


SCA Functions

PHP Manual
Prev Next

CXL. SCA 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.

SCA for PHP makes it possible for a PHP programmer to write reusable components, which can be called in a variety of ways, with an identical interface and with a minimum of fuss. At present components can call each other either locally or via Web services, but in the future it is expected that other ways will be possible. It provides the programmer with a way of doing this which will look as natural as possible in PHP.

SCA components use phpDocumentor-style (see http://www.phpdoc.org/) annotations to declare dependencies on other SCA components or Web services. The SCA for PHP runtime resolves these dependencies at runtime on behalf of the components, and thus allows the PHP programmer to focus on the business logic rather than on locating and obtaining references to dependencies.

The SCA for PHP programming model can be extended to support a number of service types, such as REST and Atompub. However, Web services (more accurately, WSDL defined, SOAP/HTTP services), are the only type currently specified.

Components also use annotations to define the interface which they expose as a service. The SCA for PHP runtime will automatically generate WSDL from these annotations, so that an SCA component is easily exposed as a web service. These annotations are a natural extension to those provided by phpDocumentor. Deploying a Web service can be as simple as placing a PHP component under the document root of a web server.

Components also use annotations to specify data structures (expressed using XML schema complex types) which are then handled using Service Data Objects (SDOs).

A PHP script which is not an SCA component and which contains no annotations can use the services of an SCA component. A PHP script or component can make calls to a web service that is not an SCA component, but using the same system of calls or annotations to obtain a reference.

First we show a single SCA component, ConvertedStockQuote which illustrates many of the features of SCA for PHP. It has one method, getQuote(), which given a stock "ticker" obtains a price quote for that stock, converted to a given currency. We shall be using this example as a basis for explaining the SCA for PHP throughout the rest of this document.

Example 1. A sample SCA component

&#60;?php

include "SCA/SCA.php";

/**
 * Calculate a stock price for a given ticker symbol in a given currency.
 *
 * @service
 * @binding.ws
 */
class ConvertedStockQuote {

    /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;

    /**
     * The stock quote service to use.
     *
     * @reference
     * @binding.wsdl ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;

    /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this-&#62;stock_quote-&#62;getQuote($ticker);
        $rate   = $this-&#62;exchange_rate-&#62;getRate($currency);
        return  $rate * $quote;
    }
}
?&#62;

In this example, we see that an SCA component is implemented by a script containing a PHP class and includes SCA.php. The class contains a mixture of business logic and references to other components or services. In the illustrated getQuote() method there is only business logic, but it relies on the instance variables $stock_quote and $exchange_rate having been initialized. These refer to two other components and will be initialized by the SCA runtime with proxies for these two services, whenever this component executes. The annotations for these two services show one to be a local component, which will be called within the same PHP runtime, and one to be a remote component which will be called via a SOAP request. This component also exposes the getQuote() method both locally and as a web service, so it in turn can be called either locally or remotely.

Requirements

If you want to use SCA to consume or produce Web services then you need PHP 5.2.0 or later, built with the soap extension enabled. If you just want to use local components, and do not wish to use the Web service bindings, then this version of SCA for PHP will also run with PHP 5.1.6.

Installation

SCA is packaged along with SDO in one combined package on PECL. See http://www.php.net/sdo#sdo.installation for installing the SCA_SDO package from PECL. The SCA code must be on the include path of your PHP installation, for example if it is installed as /usr/local/lib/php/SCA, the include_path directive must include /usr/local/lib/php

Examples

The examples in the subsequent sections illustrate the following aspects of PHP for SCA:

  • How PHP annotations are used to define PHP classes as SCA components, and how annotations are used to define the services.

  • How an SCA component can be exposed as a Web service

  • How an SCA component can consume a Web service, whether provided by another SCA component or by some other service which knows nothing of SCA

  • How an SCA component can call another SCA component locally (within the same process and on the same call stack)

  • How a client script which is not an SCA component can use the getService call to obtain a proxy for an SCA component.

  • How data structures such as Addresses, or Puchase Orders, are represented as Service Data Objects, and handled.

  • How SCA components are deployed, and in particular how and when WSDL is generated for a service.

  • How parameters are always passed by value (and not by reference) between components, even when the calls are local. This ensures that the semantics of a call do not change depending on the location of a component.

  • How positional parameters to a service are supported, even when the underlying WSDL is document literal wrapped, and naturally supports only named parameters.

  • How business and runtime exceptions are handled.

The structure of a Service Component

A service component is implemented by a class. To identify it as a service component, it contains an @service annotation. The SCA runtime will use the file name of the script to determine the component name, by convention. The class and script file must therefore share the same name.

PHP SCA components always expose a service, and there is no way for a component to be invoked other than to be called as a result of a Web service request, or called directly from another component or from a script. For this reason a valid PHP SCA component will always contain an @service annotation and at least one public method.

Each SCA Component requires that the SCA.php script is included. As well as containing the definition of the SCA class, this script contains executable PHP code that will run whenever the script is called, and which will be responsible for making the component behave as needed.

Caution

It is very important that if your file contains other includes, they come before the include for SCA.php. If there are includes after the include for SCA.php, they will not have been processed when the SCA runtime runs your class.

The example below illustrates this overall structure

Example 2. The structure of an SCA for PHP component

&#60;?php

// any includes

include "SCA/SCA.php

/**
 * @service
 */

class ConvertedStockQuote {

       // instance variables, business logic, including at least one public method

}
?&#62;

Obtaining a proxy for another Service Component

One SCA component can call the service provided by another SCA component. The service a component provides is made up of all of its public methods. SCA for PHP currently provides two ways for one component to call another: either locally (i.e. within the same PHP run-time, and on the same call stack) or remotely if the called component exposes a Web service binding.

In order for one component to call another, the calling component needs a proxy for the called component. This proxy is usually provided as an instance variable in the calling component, though proxies can also be obtained with the SCA::getService() call, as we shall see later. When a component is constructed, proxies are constructed for any instance variable which refer to another component, and these proxies are "injected" into the instance variables. Proxies are always used, whether the component is local or remote, in order to provide identical calling behavior between remote and local calls (for example, local calls are made to always pass data by-value). The proxies know how to locate the required component and to pass the calls made on to them.

Instance variables which are intended to hold proxies for services are indicated by the two PHPDocumentor-style annotations, @reference and @binding. Both annotations are placed in the documentation section for a class instance variable, as shown by the code below.

The @reference annotation before an instance variable indicates that that instance variable is to be initialized with a proxy to a component.

The @binding annotation has two forms @binding.php and @@binding.ws, and indicates that the proxy is either for a local component or for a Web service respectively. For both @binding.php and @binding.ws, the annotation gives a target URI.

At the moment, with the annotation-based method of specifying dependencies, the only way to alter the intended target of a reference is to alter the annotation within the component.

In our ConvertedStockQuote example, the $exchange_rate instance variable will be initialized with a proxy to the local ExchangeRate component whenever an instance of the ConvertedStockQuote is constructed.

Example 3. Obtaining a proxy for a local PHP class

&#60;?php
   /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;
?&#62;

For @binding.php, the URI identifies the location of the script containing the implementation of the component. The component will be called locally. The service provided is the set of public methods of the component. The URI must be a simple pathname, either absolute or relative. The component will be loaded with the PHP include directive, after testing to see if it is already loaded with class_exists(). If the URI is a relative path, it is resolved relative to the component containing the annotation. Note that this is different from the normal PHP behaviour where scripts would be looked for along the PHP include_path, This is intended to provide some location-independence for cross-component references.

If this ExchangeRate service were remote and to be called as a Web service, only the @binding line changes. Instead of giving the location of a PHP class, it gives the location of the WSDL describing the web service. In our example component, this is illustrated by the second reference:

Example 4. Obtaining a proxy for a web service

&#60;?php
/**
     * The stock quote service to use.
     *
     * @reference
     * @binding.wsdl ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;
?&#62;

The StockQuote component will be called via a Web service request. In this case the URI for the WSDL can be a simple pathname, or may contain a PHP wrapper and begin, for example, with file:// or http://. In the event that it is a simple pathname, it can be absolute or relative, and if relative will be resolved relative to the component containing the annotation. Note that this is like the behaviour for @binding.php, and different from the normal PHP behaviour where the file would be looked for relative to the PHP current working directory, which would usually be the location of the first script to be called. This behaviour is intended to give consistency across the different bindings and to provide some location-independence for references between components.

Calling another Service Component

The ConvertedStockQuote example also calls the proxies for the two components to which it refers.

Example 5. Calling services

&#60;?php
$quote  = $this-&#62;stock_quote-&#62;getQuote($ticker);
$rate   = $this-&#62;exchange_rate-&#62;getRate($currency);
?&#62;

The call to the StockQuote service is a call to a local service; the call to the ExchangeRate service is a call to a remote service. Note that the way the call is made looks the same regardless of whether the call is to a local service or a remote one.

The proxies which have been injected ensure that the way calls to components look and behave are the same way regardless of whether they are to a local or remote service, so that components are not sensitive to whether a call is to a local or a remote service. For example, the proxy for a local service takes copies of the arguments and passes only those copies, to ensure that calls are made to be pass-by-value, as they would be for a remote call. Also, the proxy for a remote service takes the arguments from a positional parameter list and ensures they are packaged properly in a SOAP request and converted back to a positional parameter list at the far end.

In the example above, the $ticker and $currency are clearly PHP scalar types. Components can pass the PHP scalar types string, integer, float and boolean, but data structures on service calls are always passed as Service Data Objects (SDOs). A later section describes how a component can create an SDO to pass on a local or Web service call, or how a component can create an SDO to return. The PHP SDO project documentation describes how to work with the SDO APIs (see the SDO pages.

Locating and calling services from a script which is not an SCA Component

SCA components obtain proxies for other components or services as instance variables annotated with @reference, but this is not possible for a script that is not itself also a component. A client script which is not a component must use the SCA::getService() static method to obtain a proxy for a service, whether local or remote. The getService() method takes a URI as the argument. Typically this is the location of a local PHP script containing a component, or of a wsdl file, and is used in exactly the same way as the targets of the @binding annotations described in the previous section: that is, relative URIs are resolved against the location of the client script and not against the PHP include_path or current working directory.

For example, a script that needed to obtain proxies for the ExchangeRate and StockQuote services but was not a component would use the getService() method as follows:

Example 6. Obtaining a proxy using getService

&#60;?php
$exchange_rate = SCA::getService('../ExchangeRate/ExchangeRate.php');
$stock_quote   = SCA::getService('../StockQuote/StockQuote.wsdl');
?&#62;

Methods on services can then be called on the returned proxy, just as they can in a component.

Example 7. Making calls on the proxy

&#60;?php
$quote  = $stock_quote-&#62;getQuote($ticker);
$rate   = $exchange_rate-&#62;getRate($currency);
?&#62;

Exposing a Service Component as a Web service

SCA for PHP can generate WSDL from the annotations within a service component, so that it can be easily deployed and exposed as a Web service. To provide SCA with the information it needs to generate the WSDL, it is necessary to add the annotation @binding.ws under the @service annotation and to specify the parameters and return values of the methods using the @param and @return annotations. These annotations will be read when WSDL is generated, and the order and types of the parameters determine the contents of the <schema> section of the WSDL.

SCA for PHP always generates document/literal wrapped WSDL for components that are exposing a Web service. Note that this does not stop components from consuming Web services which are not SCA components and which are documented with WSDL written in a different style.

The scalar types which can be used in the @param annotation are the four common PHP scalar types: boolean, integer, float and string. These are simply mapped to the XML schema types of the same name in the WSDL. The example below, which is a trivial implementation of the StockQuote service that the ConvertedStockQuote component calls, illustrates string and float types.

Example 8. StockQuote Service

&#60;?php

include "SCA/SCA.php";

/**
 * Scaffold implementation for a remote StockQuote Web service.
 *
 * @service
 * @binding.ws
 *
 */
class StockQuote {

    /**
     * Get a stock quote for a given ticker symbol.
     *
     * @param string $ticker The ticker symbol.
     * @return float The stock quote.
     */
    function getQuote($ticker) {
        return 80.9;
  }
}
?&#62;

WSDL much like the following (though with a service location other than 'localhost', probably) would be generated from this service:

Example 9. Generated WSDL

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xsi:type="tDefinitions"
    xmlns:tns2="http://StockQuote" xmlns:tns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns3="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://StockQuote">
  <types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://StockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

  <message name="getQuoteRequest">
    <part name="getQuoteRequest" element="tns2:getQuote"/>
  </message>
  <message name="getQuoteResponse">
    <part name="return" element="tns2:getQuoteResponse"/>
  </message>
  <portType name="StockQuotePortType">
    <operation name="getQuote">
      <input message="tns2:getQuoteRequest"/>
      <output message="tns2:getQuoteResponse"/>
    </operation>
  </portType>
  <binding name="StockQuoteBinding" type="tns2:StockQuotePortType">
    <operation name="getQuote">
      <input>
        <tns3:body xsi:type="tBody" use="literal"/>
      </input>
      <output>
        <tns3:body xsi:type="tBody" use="literal"/>
      </output>
      <tns3:operation xsi:type="tOperation" soapAction=""/>
    </operation>
    <tns3:binding xsi:type="tBinding" transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  </binding>
  <service name="StockQuoteService">
    <port name="StockQuotePort" binding="tns2:StockQuoteBinding">
      <tns3:address xsi:type="tAddress" location="http://localhost/StockQuote/StockQuote.php"/>
    </port>
  </service>
</definitions>

<!-- this line identifies this file as WSDL generated by SCA for PHP. Do not remove -->

Deploying an SCA component

There are no special steps needed to deploy a PHP SCA component. It is sufficient to place the component PHP script in its proper place under the web server document root, just like any other PHP script. It is the SCA::initComponent() executable line within each component that will be executed whenever the script is called, and which will be responsible for making the component respond appropriately to Web service calls, local calls, or requests for WSDL.

Obtaining the WSDL for an SCA component offering a Service as a Web service

SCA components that expose a Web service interface (i.e. have an @binding.ws annotation) will return their WSDL definition in response to an HTTP request with a get parameter of "wsdl". The usual way to obtain this is with "?wsdl" on the end of a URL. The example below uses file_get_contents() to obtain WSDL from a service and writes it to a temporary file before then obtaining a proxy for the service in the usual way. You could of course also obtain the WSDL in a browser, or by some other means, and save the file yourself.

Example 10. Generated WSDL

<?php
$wsdl 	= file_get_contents('http://www.example.com/Services/Example.php?wsdl');
file_put_contents("service.wsdl",$wsdl); //write the wsdl to a file
$service = SCA::getService('service.wsdl');
?>

NOTE: If the wsdl requires imported xsds, these will need to be fetched separately.

Understanding how the WSDL is generated

SCA for PHP generates WSDL for components which contain an @binding.ws annotation after the @service annotation. To generate WSDL, the SCA runtime reflects on the component and examines the @param and @return annotations for each public method, as well as any @types annotations within the component. The information from the @param and @return annotations is used to build the <types> section of the WSDL. Any @types annotations which specify a separate schema file will result in an <import> element for that schema within the WSDL.

Location attribute of the <service> element

At the bottom of the WSDL is the <service> element which uses the location attribute to identify the URL of the service. For example this might look as follows:

Example 11. location attribute

<service name="ConvertedStockQuote"
...
location="http://localhost/ConvertedStockQuote/ConvertedStockQuote.php"/>

Note that this location is relative to the document root of the web server, and cannot be worked out in advance. It can only be worked out once the component is in its proper place under a running web server, when the hostname and port can be known and placed in the WSDL. Detail from the URL that requests the WSDL is used, so for example if the WSDL is generated in response to a request to http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php?wsdl, a location of http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php is what will be inserted into the location attribute in the WSDL.

Document/literal wrapped WSDL and positional parameters

SCA for PHP generates WSDL in the document/literal wrapped style. This style encloses the parameters and return types of a method in 'wrappers' which are named after the corresponding method. The <types> element at the top of the WSDL defines each of these wrappers. If we consider the getQuote() method of the ConvertedStockQuote example:

Example 12. method with two arguments

&#60;?php
   /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this-&#62;stock_quote-&#62;getQuote($ticker);
        $rate   = $this-&#62;exchange_rate-&#62;getRate($currency);
        return  $rate * $quote;
    }
?&#62;

The WSDL generated to define this method will name both the method and the parameters, and give an XML schema type for the parameters. The types section of the WSDL looks like this:

Example 13. types section illustrating named parameters

<types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://ConvertedStockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
            <xs:element name="currency" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

The SCA run-time has special processing to handle how positional parameter lists in the interface are converted to XML containing named parameters in the soap request, and then back to positional parameter lists again. To see why this matters, consider how a PHP script which used a different interface to make a SOAP call would need to construct the parameter list. A PHP script using the PHP SoapClient, for example, would need to pass the SoapClient a single parameter giving the values for "ticker" and "currency", perhaps as an associative array. To insist that SCA components construct parameter lists to make Web service calls in this way would be to make local and remote calls look different, so a different approach is needed.

When SCA generates WSDL for an SCA component it includes a comment in the WSDL which marks that WSDL as being the interface for an SCA component. In this case, when one SCA component calls another through a Web service, the SCA runtime on the calling end takes the positional parameter list from the call and assigns the values one by one to the named elements in the soap message. For example a call to the getQuote() method defined above that passes the values 'IBM' and 'USD' and looks like this:

$quote = $remote_service-&#62;getQuote('IBM','USD');

will result in a soap message containing the following:

&#60;getQuote&#62;
  &#60;ticker&#62;IBM&#60;/ticker&#62;
  &#60;currency&#62;USD&#60;/currency&#62;
&#60;/getQuote&#62;

On the service-providing end, the SCA run-time takes the parameters one by one from the soap message and forms a positional parameter list from them, re-forming the argument list ('IBM','USD').

Caution

At both ends the SCA runtime relies on the order in which the parameters appear in the soap message being the same as that in the target method's parameter list. This is ultimately determined by the order of the @param annotations: this determines the order in which the parameters appear in the WSDL and thereby the order in which they appear in the soap message. Therefore it is essential that the order of the @param annotations matches that of the parameters in the method's parameter list.

Working with Data Structures

SCA components can pass and return the four PHP scalar types boolean, integer, real and string, but to pass or return data structures, SCA components use Service Data Objects (SDOs). SDOs are described in much more detail in the SDO pages of this manual. Readers familiar with SDOs will know that they are suitable for representing the sort of structured and semi-structured data that is frequently modeled in XML, and that they serialize very naturally for passing between remote components, or in Web services. SDOs are presently the only supported way to pass and return data structures. It is not possible to pass or return PHP objects, or PHP arrays.

The SCA runtime always assures data is passed by-value, even for local calls. To do this, the SCA runtime copies any SDOs in the parameter list before passing them on, just as it does for scalar types.

How data structures are defined to SCA components

Currently the only mechanism for specifying the location of a data structure definition is by specifying the types in an XML schema file. However, in the future it may be possible to define types in other ways, such as based on PHP classes or interfaces, or based on definitions expressed as associative arrays.

To illustrate the use of SDOs we introduce a new component. The PortfolioMangement service below returns an SDO representing a stock portfolio for a given customer.

Example 14. A Component that uses Data Structures

&#60;?php

include 'SCA/SCA.php';

/**
 * Manage the portfolio for a customer.
 *
 * @service
 * @binding.ws
 *
 * @types http://www.example.org/Portfolio PortfolioTypes.xsd
 *
 */
class PortfolioManagement {

    /**
     * Get the stock portfolio for a given customer.
     *
     * @param integer $customer_id The id for the customer
     * @return Portfolio http://www.example.org/Portfolio The stock portfolio (symbols and quantities)
     */
    function getPortfolio($customer_id) {
        // Pretend we just got this from a database
        $portfolio = SCA::createDataObject('http://www.example.org/Portfolio', 'Portfolio');
        $holding = $portfolio-&#62;createDataObject('holding');
        $holding-&#62;ticker = 'AAPL';
        $holding-&#62;number = 100.5;
        $holding = $portfolio-&#62;createDataObject('holding');
        $holding-&#62;ticker = 'INTL';
        $holding-&#62;number = 100.5;
        $holding = $portfolio-&#62;createDataObject('holding');
        $holding-&#62;ticker = 'IBM';
        $holding-&#62;number = 100.5;
        return $portfolio;
    }

}
?&#62;

The @types annotation:

&#60;?php
@types http://www.example.org/Portfolio PortfolioTypes.xsd
?&#62;

indicates that types in the namespace http://www.example.org/Portfolio will be found in the schema file located by the URI PortfolioTypes.xsd. The generated WSDL would reproduce this information with an import statement as follows:

<xs:import schemaLocation="PortfolioTypes.xsd"
                      namespace="http://www.example.org/Portfolio"/>

so the URI, absolute or relative, must be one that can be resolved when included in the schemaLocation attribute.

Creating SDOs

Readers familiar with SDOs will know that they are always created according to a description of the permitted structure (sometimes referred to as the 'schema' or 'model') and that, rather than creating them directly using 'new', some form of data factory is needed. Often, an existing data object can be used as the data factory, but sometimes, and especially in order to get the first data object, something else must act as the data factory.

In SCA, either the SCA runtime class or the proxies for services, whether local or remote, can act as the data factories for SDOs. The choice of which to use, and when, is described in the next two sections.

We switch to a new example in order to illustrate the creation of SDOs, both to pass to a service, and to be returned from a service.

Creating an SDO to pass to a service

A caller of a service which requires a data structure to be passed in to it uses the proxy to the service as the data factory for the corresponding SDOs. For example, suppose a component makes use of a proxy for a service provided by a local AddressBook component.

&#60;?php
/**
 * @reference
 * @binding.local AddressBook.php
 */
$address_book;
?&#62;

The AddressBook component that it wishes to call is defined as follows:

&#60;?php
/**
* @service
* @binding.ws
* @types http://addressbook ../AddressBook/AddressBook.xsd
*/
class AddressBook {

    /**
     * @param personType $person http://addressbook (a person object)
     * @return addressType http://addressbook (the address object for the person object)
     */
    function lookupAddress($person)  {
              ...
    }
}
?&#62;

The AddressBook component provides a service method called lookupAddress() which uses types from the http://addressbook namespace. The lookupAddress method takes a personType data structure and returns an addressType. Both types are defined in the schema file addressbook.xsd.

Once the component that wishes to use the AddressBook component has been constructed, so that the $address_book instance variable contains a proxy for the service, the calling component can use the proxy in $address_book to create the person SDO, as shown below:

&#60;?php
$william_shakespeare        = $address_book-&#62;createDataObject('http://addressbook','personType');
$william_shakespeare -&#62;name = "William Shakespeare";
$address                    = $address_book-&#62;lookupAddress($william_shakespeare);
?&#62;

Note, the use of the proxy as the means to create the SDO is not limited to SCA components. If a service is being called from a general PHP script, and the proxy was obtained with getService() then the same approach is used.

&#60;?php
$address_book = SCA::getService('AddressBook.php');
$william_shakespeare = $address_book-&#62;createDataObject('http://addressbook','personType');
?&#62;

Creating an SDO to return from a component

A component that needs to create a data object for return to a caller will not have a proxy to use as a data object, In this case it uses the createDataObject() static method on SCA.php. Hence if the AddressBook component described above needed to create an object of type addressType within the namespace http://addressbook, it might do so as follows:

&#60;?php
$address = SCA::createDataObject('http://addressbook','addressType');
?&#62;

Error handling

This section describes how errors are handled. There are two types of errors:

  • SCA runtime exceptions are those that signal problems in the management of the execution of components, and in the interaction with remote services. These might occur due to network or configuration problems.

  • Business exceptions are those that are defined by the programmer. They extend the PHP Exception class, and are thrown and caught deliberately as part of the business logic.

Handling of Runtime exceptions

There are two types of SCA runtime exception:

  • SCA_RuntimeException - signals a problem found by or perhaps occurring within the SCA runtime. This can be thrown for a variety of reasons, many of which can occur regardless of whether a connection is being made to a local or a remote service: an error in one of the annotations within a component, a missing WSDL or php file, and so on. In the case of Web services, an SCA_RuntimeException can also be thrown if a SoapFault is received from a remote Web service and the fault code in the SoapFault indicates that a retry is unlikely to be successful.

  • SCA_ServiceUnavailableException - this is a subclass of SCA_RuntimeException and signals a problem in connecting to or using a remote service, but one which might succeed if retried. In the case of Web services, this exception is thrown if a SoapFault is received with a fault code that indicates that a retry might be successful.

Handling of Business exceptions

Business exceptions may be defined and thrown by a component in the normal way, regardless of whether the component has been called locally or remotely. The SCA runtime does not catch business exceptions that have been thrown by a component called locally, so they will be returned to a caller in the normal way. If a component has been called via a Web service, on the other hand, the SCA runtime on the service providing end does catch business exceptions, and will ensure these are passed back to the calling end and re-thrown. Assuming that the calling end has a definition of the exception (that is, is able to include a file containing the PHP class defining the exception) the re-thrown exception will contain the same details as the original, so that the getLine() and getFile() methods for example will contain the location where the exception was thrown within the business logic. The exception will be passed in the detail field of a soap fault with a fault code of "Client".

Predefined Classes

Most of the interface to SCA is through the annotations within SCA components so there are few public classes and methods. The only SCA classes that scripts or components can call are the SCA class itself, and the proxy classes SCA_LocalProxy and SCA_SoapProxy.

SCA

Much of the work of the SCA class is performed when the file SCA.php is included within an SCA component. However, a PHP script may include SCA.php and call the getService() method on the SCA class in order to obtain a proxy for a service. A component will not need to do this as proxies are obtained instead by defining an instance variable with the @reference annotation.

Components that need to create an SDO to return to a caller will need a data factory to call. For this purpose the SCA class supports the createDataObject() method, which will create an SDO according to the model defined by the component's @types annotations. The arguments to createDataObject() are the same as those to SDO's XML Data Access Service.

Methods

  • getService - obtain a proxy for a service

  • createDataObject - create an SDO

SCA_LocalProxy

When getService() is called with the target of a local PHP component, a local proxy is returned. A local proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.php anotation. When the script or component makes calls on the local proxy, they are passed on to the target component itself.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_LocalProxy class supports the createDataObject method, which will create an SDO according to the model defined by the components' @types annotations. The arguments to the createDataObject are the same as those to SDO's XML Data Access Service.

Methods

  • createDataObject - create an SDO

SCA_SoapProxy

When getService() is called with the target of a WSDL file, a SOAP proxy is returned. A SOAP proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.ws anotations. When the script or component makes calls on the SOAP proxy, they are formed into Web service SOAP requests and passed on to the target component, with the help of the PHP Soap extension.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_SoapProxy class supports the createDataObject method, which will create an SDO according to the model defined within the target WSDL. The arguments to the createDataObject are the same as those to SDO's XML Data Access Service.

Methods

  • createDataObject - create an SDO

Table of Contents
SCA_LocalProxy::createDataObject -- create an SDO
SCA_SoapProxy::createDataObject -- create an SDO
SCA::createDataObject -- create an SDO
SCA::getService -- Obtain a proxy for a service

Prev | Home | Next
satellite_object_to_string | Up | SCA_LocalProxy::createDataObject


SDO Functions

PHP Manual
Prev Next

CXLI. SDO Functions

Introduction

Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.

Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source, typically the same one.

See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).

This extension is derived from concepts taken from the Service Data Objects specification. It includes a version of the Apache Tuscany SDO for C++ project.

The Structure of a Service Data Object

A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment relationships between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment relationship to the Departments.

An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor.

As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").

Each of these properties of a data object - containment relationships, non-containment references, or primitive properties - may be many-valued or single-valued. In the above examples, Departments is many-valued and the Company name is single-valued.

In PHP, each SDO data object is represented as a PHP object. The properties of the data object can be accessed using either object syntax or associative array syntax. We'll see some examples of this later.

Requirements

The SDO extension requires PHP 5.1 or higher. It also requires the libxml2 library. Normally libxml2 will already be installed, but if not, it can be downloaded from http://www.xmlsoft.org/ .

Installation

Note: Earlier versions of the SDO extension required a separate shared library for the XML DAS. This is now obsolete and any references to php_sdo_das_xml.dll or sdo_das_xml.so should be removed from your php.ini .

Unix systems

  1. You can download and install the latest stable release of all three SDO components - the SDO core, the XML DAS and the Relational DAS - with the command:

    pecl install sdo

    This command will build the SDO shared library as well as installing the PHP files that make the Relational DAS.

    If you want to use the latest beta version, then instead run:

    pecl install sdo-beta

  2. The pecl command automatically installs the SDO module into your PHP extensions directory. To enable the SDO extension you must add the following line to php.ini :

    extension=sdo.so

    For more information about building PECL packages, consult the PECL installation section of the manual.

Windows

  1. The latest SDO DLL can be downloaded from php_sdo.dll .

    Note that currently the pecl4win site does not provide this binary at the current release level; you can only download the latest level.

  2. The pecl command automatically installs the SDO module into your PHP extensions directory. To enable the SDO extension you must add the following line to php.ini :

    extension=php_sdo.dll

  3. The Relational DAS can be downloaded and installed with the command:

    pecl install -B sdo

    The Relational DAS is written in PHP. You may need to update your include_path in php.ini to point to the directory that contains sdo/DAS/Relational .

Building SDO on Linux

This section describes how to build the SDO core and XML DAS on Linux. You would only need to know how to do this if you wish to build a recent version that you have checked out of CVS.

  1. Change to the main extension directory: cd < wherever your sdo code is >

  2. Run phpize , which will set up the environment to compile SDO.

  3. Next, run ./configure; make; make install . Please note, you may need to login as root to install the extension.

  4. Make sure that the module is loaded by PHP, by adding extension=sdo.so to your php.ini file.

Data Access Services

The table below lists the currently provided SDO Data Access Services:

DAS Name | Description
SDO_DAS_XML | An XML Data Access Service supporting reading/writing SDOs as XML documents.
SDO_DAS_Relational | A PDO-based Data Access Service supporting reading/writing SDO to relational databases. Implements an optimistic concurrency policy for updates.

Limitations

Implementation Limitations

The following are limitations in the current SDO implementation:

  1. There is no support for multi-byte character sets. This will be considered, depending on community requirements, in the Unicode-enabled version of PHP. See Unicode Functions.

SDO Limitations

The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.

  1. Bi-directional relationships.

  2. Type and property alias names.

  3. Read-only properties.

  4. The Helper classes defined in SDO 2.0 are not directly implemented. However equivalent function is provided in a more natural way for PHP. For example the function of CopyHelper::copy() is provided by applying the PHP clone keyword to a data object.

Examples

The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.

The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.

<?xml version="1.0" encoding="UTF-8" ?>
<company xmlns="companyNS" name="MegaCorp"
  employeeOfTheMonth="E0003">
  <departments name="Advanced Technologies" location="NY" number="123">
    <employees name="John Jones" SN="E0001"/>
    <employees name="Jane Doe" SN="E0003"/>
    <employees name="Al Smith" SN="E0004" manager="true"/>
  </departments>
</company>

The root element of the schema is a company. The company contains departments, and each department contains employees. Each element has a number of attributes to store things like name, serial number, and so on. Finally, the company also has an IDREF attribute which identifies one of the employees as the 'employeeOfTheMonth'.

<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:sdo="commonj.sdo"
  xmlns:sdoxml="commonj.sdo/xml"
  xmlns:company="companyNS"
  targetNamespace="companyNS">
  <xsd:element name="company" type="company:CompanyType"/>
  <xsd:complexType name="CompanyType">
    <xsd:sequence>
      <xsd:element name="departments" type="company:DepartmentType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF"
      sdoxml:propertyType="company:EmployeeType"/>
  </xsd:complexType>
  <xsd:complexType name="DepartmentType">
    <xsd:sequence>
      <xsd:element name="employees" type="company:EmployeeType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="location" type="xsd:string"/>
    <xsd:attribute name="number" type="xsd:int"/>
  </xsd:complexType>
  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="SN" type="xsd:ID"/>
    <xsd:attribute name="manager" type="xsd:boolean"/>
  </xsd:complexType>
</xsd:schema>

The XML Data Access Service maps the schema to an SDO. Attributes such as "name" become primitive properties, the sequence of employees becomes a many-valued containment relationship, and so on. Note that the containment relationships are expressed as one complex type within another, whereas non-containment references are expressed in terms of ID and IDREF, with a special sdoxml:propertyType attribute specifying the type of the non-containment reference.

Setting and Getting Property Values

The following examples assume $company is the root of a tree of data objects created from the schema and instance document shown above.

Example 1. Access via property name

Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'.

&#60;?php
  $company-&#62;name = 'Acme';
?&#62;

Example 2. Access via property name as array index

We can also access properties using associative array syntax. The simplest form of this uses the property name as the array index. For example, the following sets the company name and gets the employeeOfTheMonth.

&#60;?php
  $company['name'] = 'UltraCorp';
  $eotm = $company['employeeOfTheMonth'];
?&#62;

Example 3. Data Object iteration

We can iterate over the properties of a data object using foreach. The following iterates over the properties of the employee of the month.

&#60;?php
  $eotm = $company-&#62;employeeOfTheMonth;
  foreach ($eotm as $name =&#62; $value) {
      echo "$name: $value\n";
  }
?&#62;

which will output:

name: Jane Doe
SN: E0003

The 'manager' property is not output, because it has not been set.

Example 4. Access many-valued property by name

Many-valued data object properties can also be accessed using the object property name syntax. The following gets the list of departments.

&#60;?php
  $departments = $company-&#62;departments;
?&#62;

Example 5. Many-valued element access

We can access individual elements of many-valued properties using array syntax. The following accesses the first department in the company.

&#60;?php
  $ad_tech_dept = $company-&#62;departments[0];
?&#62;

Example 6. Many-valued property iteration

Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.

&#60;?php
  foreach ($company-&#62;departments as $department) {
    // ...
  }
?&#62;

Each iteration will assign the next department in the list to the variable $department.

Example 7. Chained property access

We can chain property references on a single line. The following sets and gets the name of the first department.

&#60;?php
  $company-&#62;departments[0]-&#62;name = 'Emerging Technologies';
  $dept_name = $company-&#62;departments[0]-&#62;name;
?&#62;

Using the associative array syntax, this is equivalent to

&#60;?php
  $company['departments'][0]['name'] = 'Emerging Technologies';
  $dept_name = $company['departments'][0]['name'];
?&#62;

In either case, the dept_name variable is set to 'Emerging Technologies'.

Example 8. XPath navigation

The associative array index can be an XPath-like expression. Valid expressions are defined by an augmented sub-set of XPath.

Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The standard syntax is:

&#60;?php
  $jane_doe = $company["departments[1]/employees[2]"];
?&#62;

and the SDO XPath extension syntax is:

&#60;?php
  $jane_doe = $company["departments.0/employees.1"];
?&#62;

Both these examples get the second employee from the first department.

Example 9. XPath querying

We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.

&#60;?php
 $ad_tech_mgr =
  $company["departments[name='Advanced Technologies']/employees[manager=true]"];
?&#62;

Example 10. Creating child data objects

A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.

&#60;?php
  $ad_tech_dept = $company["departments[name='Advanced Technologies']"];
  $new_hire = $ad_tech_dept-&#62;createDataObject('employees');
  $new_hire-&#62;name = 'John Johnson';
  $new_hire-&#62;SN = 'E0005';
  $new_hire-&#62;manager = false;
?&#62;

Example 11. Unset a primitive property

We can use the isset() and unset() functions to test and remove items from the data object.

The following clears the name of the first department.

&#60;?php
  unset($company-&#62;departments[0]-&#62;name);
?&#62;

Example 12. Unset a data object

unset can also be used to remove a data object from the tree. The following example shows John Jones leaving the company.

&#60;?php
  unset($company-&#62;departments[0]-&#62;employees[0]);
?&#62;

Example 13. Unset a referenced data object

The following removes the 'employeeOfTheMonth' from the company. If this were a containment relationship then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.

&#60;?php
  if (isset($company-&#62;employeeOfTheMonth)) {
    unset($company-&#62;employeeOfTheMonth);
  }
?&#62;

Example 14. Access via property index

Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following sets the company name to 'Acme', with the same result as Access via property name

&#60;?php
  $company[1] = 'Acme';
?&#62;

Using the index directly in this way is likely to be fragile. Normally the property name syntax should be preferred, but the property index may be required in special cases.

Working with Sequenced Data Objects

Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved ( <A/><B/><A/>). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.

The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.

The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

When loaded, the letter data object will have the sequence and property indices shown in the table below:

Sequence Index | Property Index:Name | Value
0 | 0:date | March 1, 2005
1 | - | Mutual of Omaha
2 | - | Wild Kingdom, USA
3 | - | Dear
4 | 1:firstName | Casy
5 | 2:lastName | Crocodile
6 | - | Please buy more shark repellent.
7 | - | Your premium is past due.

To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.

Example 15. Getting the SDO_Sequence interface

We obtain a data object's sequence using the getSequence() method. The follow gets the sequence for the letter data object.

&#60;?php
  $letter_seq = $letter-&#62;getSequence();
?&#62;

All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.

Example 16. Get/set sequence values

We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').

&#60;?php
  $letter_seq[4] = 'Snappy';
  $text = $letter_seq[count($letter_seq) - 1];
?&#62;

Example 17. Sequence iteration

We can iterate through the individual sequence values using foreach. The following runs through the individual values in sequence order.

&#60;?php
  foreach ($letter-&#62;getSequence() as $value) {
    // ...
  }
?&#62;

Example 18. Sequence versus Data Object

Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.

&#60;?php
  $letter[2] = 'Smith';
  $last_name = $letter_seq[5];
?&#62;

Example 19. Adding to a sequence

We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.

&#60;?php
  // Append a firstName value to the sequence
  // value: 'Smith'
  // sequence index: NULL (append)
  // propertyIdentifier: 1 (firtName property index)
  $letter_seq-&#62;insert('Smith', NULL, 1);

  // Append a lastName value to the sequence
  // value: 'Jones'
  // sequence index: NULL (append)
  // propertyIdentifier: 'lastName' (lastName property name)
  $letter_seq-&#62;insert('Jones', NULL, 'lastName');

  // Append unstructured text
  // value: 'Cancel Subscription.'
  // sequence index: absent (append)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq-&#62;insert('Cancel Subscription.');

  // Insert new unstructured text.  Subsequent sequence values
  // are shifted up.
  // value: 'Care of:'
  // sequence index: 1 (insert as second element)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq-&#62;insert('Care of:', 1);
?&#62;

Example 20. Removing from a sequence

We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.

&#60;?php
  if (isset($letter_seq[0])) {
    unset($letter_seq[0]);
  }
?&#62;

Reflecting on Service Data Objects

SDOs have a knowledge of the structure they have been created to represent (the model). For example, a Company SDO created using the Company XML schema above would only be permitted to contain DepartmentType data objects which in turn could only contain EmployeeType data objects.

Sometimes it is useful to be able to access this model information at runtime. For example, this could be used to automatically generate a user interface for populating a data object. The model information is accessed using reflection.

Example 21. Reflecting on a Data Object

The following example shows how we can reflect on an empty Employee data object.

&#60;?php
  // Create the employee data object (e.g. from an XML Data Access Service)
  $employee = ...;
  $reflection = new SDO_Model_ReflectionDataObject($employee);
  print($reflection);
?&#62;

The above example will output:

object(SDO_Model_ReflectionDataObject)#4 { - ROOT OBJECT - Type {
companyNS:EmployeeType[3] { commonj.sdo:String $name;
commonj.sdo:String $SN; commonj.sdo:Boolean $manager; } }

Using print on the SDO_Model_ReflectionDataObject writes out the data object's model. We can see from the output how the type companyNS:EmployeeType has three properties and we can see the names of the properties along with their types. Note, the primitive types are listed as SDO types (e.g. commonj.sdo namespace, String type). It is worth noting that this is the SDO model and when these are surfaced to an application they can be treated as the PHP equivalent types (e.g. string and boolean).

Example 22. Accessing the type information

We can query the type information of a data object using reflection. The following example checks the type corresponds to a data object rather than a primitive and then iterates through the properties of the type, writing out the name of each property ($type and $property are SDO_Model_Type and SDO_Model_Property objects, respectively).

&#60;?php
    // Create the employee data object (e.g. from an XML Data Access Service)
    $employee = ...;
    $reflection = new SDO_Model_ReflectionDataObject($employee);
    $type = $reflection-&#62;getType();
    if (! $type-&#62;isDataType()) {
        foreach ($type-&#62;getProperties() as $property) {
            print $property-&#62;getName() . "\n";
        }
    }
?&#62;

The above example will output:

name
SN
manager

Predefined Classes

SDO consists of three sets of interfaces. The first set covers those interfaces for use by typical SDO applications. These are identified by the package prefix 'SDO_'. The second set is those used to reflect on, and work with, the model of a data object. These are identified by the package prefix 'SDO_Model_'. Finally, the third set are those use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_Model_' and 'SDO_DAS_' interfaces.

SDO Application Programmer Interface

SDO_DataObject

The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.

Methods

  • getSequence - get the sequence for the data object

  • createDataObject - create a child data object

  • clear - unset the properties of a data object

  • getContainer - get the container (also known as 'parent') of this data object

  • getTypeName - get the name of the type for this data object

  • getTypeNamespaceURI - get the namespace URI of the type for this data object

SDO_Sequence

The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.

Methods

  • getProperty - get the property for a given sequence index

  • move - move an element from one property index to another

  • insert - insert a new value into the sequence

SDO_List

The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.

Methods

  • insert - insert a new value into the list

SDO_DataFactory

The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.

Methods

  • create - create a new data object

SDO_Exception

An SDO_Exception is thrown when the caller's request cannot be completed. The subclasses of SDO_Exception are:

  • SDO_PropertyNotSetException - the property specified exists but has not been set or does not have a default value

  • SDO_PropertyNotFoundException - the property specified is not part of the data object's type

  • SDO_TypeNotFoundException - the specified namespace URI or type name is unknown

  • SDO_InvalidConversionException - conversion between the types of the assignment is not possible

  • SDO_IndexOutOfBoundsException - the numeric index into a data object, sequence or list is not in the valid range

  • SDO_UnsupportedOperationException - the request cannot be completed because it is not allowed, for example an attempt to set a read-only property.

Methods

One method is added to those inherited from the built in Exception class:

  • getCause - get the cause of this SDO_Exception

SDO Reflection Application Programmer Interfaces

SDO_Model_ReflectionDataObject

The main interface used to reflect on a data object instance to obtain its model type and property information. It is designed to follow the reflection pattern introduced in PHP 5.

Constructor

  • __construct - construct a new SDO_Model_ReflectionDataObject.

Methods

  • export - get a string describing the data object.

  • getType - get the SDO_Model_Type for the data object.

  • getInstanceProperties - get the instance properties of the data object.

  • getContainmentProperty - get the property which defines the containment relationship to the data object.

SDO_Model_Type

The interface through which a data object's type information can be retrieved. This interface can be used to find out the type name and namespace URI of the type, whether the type allow open content, and so on.

Methods

  • getName - get the name of the type.

  • getNamespaceURI - get the namespace URI of the type.

  • isInstance - test for a data object being an instance of the type.

  • getProperties - get the properties of the type.

  • getProperty - get a property of the type.

  • isDataType - test to see if this type is a primitive scalar type.

  • isSequencedType - test to see if this is a sequenced type.

  • isOpenType - test to see if this is an open type.

  • isAbstractType - test to see if this is an abstract type.

  • getBaseType - get the base type of this type (if one exists).

SDO_Model_Property

The interface through which a data object's property information can be retrieved. This interface can be used to find out the type of a property, whether a property has a default value, whether the property is contained or reference by its parent, its cardinality, and so on.

Methods

  • getName - get the name of the property.

  • getType - get the type of the property.

  • isMany - test to see if the property is many-valued.

  • isContainment - test to see if the property describes a containment relationship.

  • getContainingType - get the type which contains this property.

  • getDefault - get the default value for a property.

SDO Data Access Service Developer Interfaces

SDO_DAS_DataObject

The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary. The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.

Methods

  • getChangeSummary - get the change summary for a data object

SDO_DAS_ChangeSummary

The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.

If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.

Methods

  • beginLogging - begin logging changes made to a data object

  • endLogging - end logging changes made to a data object

  • isLogging - test to see if change logging is on

  • getChangedDataObjects - get a list of the data objects which have been changed

  • getChangeType - get the type of change which has been made to a data object

  • getOldValues - get a list of old values for a data object

  • getOldContainer - get the old container data object for a deleted data object

SDO_DAS_Setting

The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues() .

Methods

  • getPropertyIndex - get the property index for the changed property

  • getPropertyName - get the property name for the changed property

  • getValue - get the old value for the changed property

  • getListIndex - get the list index for the old value if it was part of a many-valued property

  • isSet - test to see if the property was set prior to being modified

SDO_DAS_DataFactory

The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.

Methods

  • getDataFactory - static methods for getting a concrete data factory instance

  • addType - add a new type to the SDO model

  • addPropertyToType - add a new property to a type definition in the SDO model

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.

SDO_DAS_ChangeSummary::NONE=0 (integer)

Represents a change type of 'none'.

SDO_DAS_ChangeSummary::MODIFICATION=1 (integer)

Represents a change type of 'modification'.

SDO_DAS_ChangeSummary::ADDITION=2 (integer)

Represents a change type of 'addition'.

SDO_DAS_ChangeSummary::DELETION=3 (integer)

Represents a change type of 'deletion'.

Table of Contents
SDO_DAS_ChangeSummary::beginLogging -- Begin change logging
SDO_DAS_ChangeSummary::endLogging -- End change logging
SDO_DAS_ChangeSummary::getChangeType -- Get the type of change made to an SDO_DataObject
SDO_DAS_ChangeSummary::getChangedDataObjects -- Get the changed data objects from a change summary
SDO_DAS_ChangeSummary::getOldContainer -- Get the old container for a deleted SDO_DataObject
SDO_DAS_ChangeSummary::getOldValues -- Get the old values for a given changed SDO_DataObject
SDO_DAS_ChangeSummary::isLogging -- Test to see whether change logging is switched on
SDO_DAS_DataFactory::addPropertyToType -- Adds a property to a type
SDO_DAS_DataFactory::addType -- Add a new type to a model
SDO_DAS_DataFactory::getDataFactory -- Get a data factory instance
SDO_DAS_DataObject::getChangeSummary -- Get a data object's change summary
SDO_DAS_Setting::getListIndex -- Get the list index for a changed many-valued property
SDO_DAS_Setting::getPropertyIndex -- Get the property index for a changed property
SDO_DAS_Setting::getPropertyName -- Get the property name for a changed property
SDO_DAS_Setting::getValue -- Get the old value for the changed property
SDO_DAS_Setting::isSet -- Test whether a property was set prior to being modified
SDO_DataFactory::create -- Create an SDO_DataObject
SDO_DataObject::clear -- Clear an SDO_DataObject's properties
SDO_DataObject::createDataObject -- Create a child SDO_DataObject
SDO_DataObject::getContainer -- Get a data object's container
SDO_DataObject::getSequence -- Get the sequence for a data object
SDO_DataObject::getTypeName -- Return the name of the type for a data object.
SDO_DataObject::getTypeNamespaceURI -- Return the namespace URI of the type for a data object.
SDO_Exception::getCause -- Get the cause of the exception.
SDO_List::insert -- Insert into a list
SDO_Model_Property::getContainingType -- Get the SDO_Model_Type which contains this property
SDO_Model_Property::getDefault -- Get the default value for the property
SDO_Model_Property::getName -- Get the name of the SDO_Model_Property
SDO_Model_Property::getType -- Get the SDO_Model_Type of the property
SDO_Model_Property::isContainment -- Test to see if the property defines a containment relationship
SDO_Model_Property::isMany -- Test to see if the property is many-valued
SDO_Model_ReflectionDataObject::__construct -- Construct an SDO_Model_ReflectionDataObject
SDO_Model_ReflectionDataObject::export -- Get a string describing the SDO_DataObject.
SDO_Model_ReflectionDataObject::getContainmentProperty -- Get the property which defines the containment relationship to the data object
SDO_Model_ReflectionDataObject::getInstanceProperties -- Get the instance properties of the SDO_DataObject
SDO_Model_ReflectionDataObject::getType -- Get the SDO_Model_Type for the SDO_DataObject
SDO_Model_Type::getBaseType -- Get the base type for this type
SDO_Model_Type::getName -- Get the name of the type
SDO_Model_Type::getNamespaceURI -- Get the namespace URI of the type
SDO_Model_Type::getProperties -- Get the SDO_Model_Property objects defined for the type
SDO_Model_Type::getProperty -- Get an SDO_Model_Property of the type
SDO_Model_Type::isAbstractType -- Test to see if this SDO_Model_Type is an abstract data type
SDO_Model_Type::isDataType -- Test to see if this SDO_Model_Type is a primitive data type
SDO_Model_Type::isInstance -- Test for an SDO_DataObject being an instance of this SDO_Model_Type
SDO_Model_Type::isOpenType -- Test to see if this type is an open type
SDO_Model_Type::isSequencedType -- Test to see if this is a sequenced type
SDO_Sequence::getProperty -- Return the property for the specified sequence index.
SDO_Sequence::insert -- Insert into a sequence
SDO_Sequence::move -- Move an item to another sequence position

Prev | Home | Next
SCA::getService | Up | SDO_DAS_ChangeSummary::beginLogging


SDO XML Data Access Service Functions

PHP Manual
Prev Next

CXLII. SDO XML Data Access Service 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.

In order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO.

The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. SDOs are always created and maintained according to a model which defines type names and what property names each type may have. For data which is from XML, this SDO model is built from a schema file written in XML schema language (an xsd file). This schema file is usually passed to the create method when the XMLDAS is initialised. The SDO 2.0 specification defines the mapping between XML types and SDO types. There are a number of small limitations in the PHP support - not everything which is in the specification can be done - and these limitations are summarised in a later section.

Requirements

The SDO XML Data Access Service requires PHP 5.1 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.

Installation

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.

Examples

Several of the following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

Example 1. Loading, altering, and saving an XML document

The following example shows how an XML document can be loaded from a file, altered, and written back.

&#60;?php
/**
 * Load, update, and save an XML document
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas-&#62;loadFile("letter.xml");
   $root_data_object = $document-&#62;getRootDataObject();
   $root_data_object-&#62;date = "September 03, 2004";
   $root_data_object-&#62;firstName = "Anantoju";
   $root_data_object-&#62;lastName = "Madhu";
   $xmldas-&#62;saveFile($document, "letter-out.xml");
   echo "New file has been written:\n";
   print file_get_contents("letter-out.xml");
} catch (SDO_Exception $e) {
   print($e-&#62;getMessage());
}
?&#62;

An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFile() method. There is also a loadString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveFile() method to write the changed document back to the file system. The saveFile method has an optional extra integer argument which if specified will cause the XML DAS to format the XML, using the integer as the amount to indent by at each change in level on the document.

This will write the following to letter-out.xml.

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <date>September 03, 2004</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Anantoju</firstName>
  <lastName>Madhu</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</FormLetter>

Example 2. Creating a new XML document

The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.

&#60;?php
/**
 * Create an XML document from scratch
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   try {
       $doc = $xmldas-&#62;createDocument();
       $rdo = $doc-&#62;getRootDataObject();
       $seq = $rdo-&#62;getSequence();
       $seq-&#62;insert("April 09, 2005", NULL, 'date');
       $seq-&#62;insert("Acme Inc. ", NULL, NULL);
       $seq-&#62;insert("United Kingdom. ");
       $seq-&#62;insert("Dear", NULL, NULL);
       $seq-&#62;insert("Tarun", NULL, "firstName");
       $seq-&#62;insert("Nayaraaa", NULL, "lastName");
       $rdo-&#62;lastName = "Nayar";
       $seq-&#62;insert("Please note that your order number ");
       $seq-&#62;insert(12345);
       $seq-&#62;insert(" has been dispatched today. Thanks for your business with us.");
       print($xmldas-&#62;saveString($doc));
   } catch (SDO_Exception $e) {
       print($e);
   }
} catch (SDO_Exception $e) {
   print("Problem creating an XML document: " . $e-&#62;getMessage());
}
?&#62;

The createDocument() method on the XML DAS returns a document object with a single root data object corresponding to an empty document element. The element name of the document element is known from the schema file. If there is any ambiguity about what the document element is, as there can be when more than one schema has been loaded into the same XML DAS, the element name and the namespace URI can be passed to the createDocument() method.

This will emit the following output (line breaks have been inserted for readability):

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>April 09, 2005</date>
Acme Inc. United Kingdom.
Dear
<firstName>Tarun</firstName>
<lastName>Nayar</lastName>
Please note that your order number 12345 has been
dispatched today. Thanks for your business with us.
</FormLetter>

Example 3. Setting XML document properties

This third example shows you how to set the XML version and encoding on the document object. These will be used when the XML is written out. If no XML declaration is wanted at all (perhaps you want to generate the XML as a string to embed in something) then you can use the setXMLDeclaration() method to suppress it.

&#60;?php
/**
 * Illustrate the calls that control the XML declaration
 */
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas-&#62;loadFile("letter.xml");
   $document-&#62;setXMLVersion("1.1");
   $document-&#62;setEncoding("ISO-8859-1");
   print($xmldas-&#62;saveString($document));
?&#62;

The XML version and encoding are set in the XML declaration at the top of the XML document.

<?xml version="1.1" encoding="ISO-8859-1"?>
.../...

Example 4. Using an open type

This fourth example illustrates the use of an SDO open type and the use of the createDataObject() method. For this example we use the following two schema:

<schema
  xmlns="http://www.w3.org/2001/XMLSchema">

  <element name="jungle">
    <complexType>
      <sequence>
        <any minOccurs="0" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>

</schema>

Note the presence of the any element in the definition. This first schema defines the jungle complex type as containing a sequence of any other type. The other types that the example will use are defined in a second schema file:

<schema xmlns= "http://www.w3.org/2001/XMLSchema">

   <complexType name="snakeType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "length" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="bearType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "weight" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="pantherType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "colour" type="string" />
     </sequence>
   </complexType>

</schema>

Here is the example PHP code that uses these two schema files:

&#60;?php

/**
 * Illustrate open types and the use of the addTypes() method
 */

$xmldas = SDO_DAS_XML::create();
$xmldas-&#62;addTypes("jungle.xsd"); // this is an open type i.e. the xsd specifies it can contain "any" type
$xmldas-&#62;addTypes('animalTypes.xsd');

$baloo             = $xmldas-&#62;createDataObject('','bearType');
$baloo-&#62;name     = "Baloo";
$baloo-&#62;weight     = 800;

$bagheera         = $xmldas-&#62;createDataObject('','pantherType');
$bagheera-&#62;name = "Bagheera";
$bagheera-&#62;colour = 'inky black';

$kaa             = $xmldas-&#62;createDataObject('','snakeType');
$kaa-&#62;name         = "Kaa";
$kaa-&#62;length     = 25;

$document         = $xmldas-&#62;createDocument();
$do             = $document-&#62;getRootDataObject();
$do-&#62;bear         = $baloo;
$do-&#62;panther     = $bagheera;
$do-&#62;snake         = $kaa;

print($xmldas-&#62;saveString($document,2));

?&#62;

These two schema files are loaded into the XML DAS with first the create() and addTypes() methods. The createDataObject() method is used to create three separate data objects. In each case the namespaceURI and typename of the type are passed to the createDataObject() method: in this example the namespace URI is blank because no namespace is used in the schema. Once the three data objects - representing a bear, a panther and a snake - have been created, a document object is created with the createDocument() method. In this case there is no ambiguity about what the document element of the document should be - as the second schema file only defines complex types, the document element can only be the global jungle element defined in the first schema. This document will have a single root data object corresponding to an empty document element jungle. As this is an open type, properties can be added at will. When the first assignment is made to $do->bear, a property bear is added to the root data object: likewise for the next two assignments. When the document is written out by the saveString() method, the resulting document is:

<?xml version="1.0" encoding="UTF-8"?>
<jungle xsi:type="jungle" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bear xsi:type="bearType">
    <name>Baloo</name>
    <weight>800</weight>
  </bear>
  <panther xsi:type="pantherType">
    <name>Bagheera</name>
    <colour>inky black</colour>
  </panther>
  <snake xsi:type="snakeType">
    <name>Kaa</name>
    <length>25</length>
  </snake>
</jungle>

Example 5. Finding out what you can from the document

This example is intended to illustrate how you can find the element name and namespace of the document element from the XML Document object, and the SDO type and namespace from the root data object of the XML data object, and how they relate to one another. This can be difficult to understand because there are four method calls: two can be made against the Document object, and two that can be made against any data object including the root data object. Because of the rules that define how the SDO model is derived from the XML model, when the data object concerned is the root object that represents the document object for the document, only three possible values can come back from these four method calls.

The two method calls that can be made against the document are getRootElementName() and getRootEelementURI(). These return the element name and namespace of the document element, respectively.

The two method calls that can be made against any data object are getTypeName() and getTypeNamespaceURI(). These return the SDO type name and type namespace of the data object, respectively.

Always, calling getRootElementURI() on the document object will return the same value as calling getNamespaceURI() on the root data object. Essentially, the information is all derived from the first few lines of the schema file, where there are three distinct pieces of information. For illustration, here again are the first few lines of the letter.xsd that we used above.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:letter="http://letterSchema"
            targetNamespace="http://letterSchema">

  <xsd:element name="letters" type="letter:FormLetter"/>

  <xsd:complexType name="FormLetter" mixed="true">
    .../...

The three important values are:

  • letters, the name of the document element

  • FormLetter, the name of the complex type of the document element. This is also the name of the SDO type of the root data object.

  • http://letterSchema, the namespace to which the document element belongs. This is also the namespaceURI of the SDO type of the root data object.

It is part of the XML-SDO mapping rules that when the SDO model is built from the schema file, the typename and namespaceURI of the SDO types for the root element are taken from those of the complex type of the document element, where it exists. Hence in this example the typename of the root data object is FormLetter. In the event that there is no separate complex type definition for the document element, when the the type is defined inline and is anonymous, the SDO type name will be the same as the element name.

The following program loads the letter document and checks the return values from each of the four calls.

&#60;?php
/**
 * Finding out what you can about the document and document element
 * This can be quite hard to understand because there are four calls
 * Two calls are made against the document
 * Two calls are made against the root data object and its model
 * Because of the SDO-XML mapping rules and how the SDO model is derived
 * from the XML model, only three possible values can come back from these four calls.
 * Always, $document-&#62;getRootElementURI() == (type of root data object)-&#62;namespaceURI
 * Essentially, it all comes form the first few lines of the xsd:
 * &#60;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 *   xmlns:letter="http://letterSchema"
 *   targetNamespace="http://letterSchema"&#62;
 *   &#60;xsd:element name="letters" type="letter:FormLetter"/&#62;
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
$document = $xmldas-&#62;loadFile("letter.xml");
$root_do = $document-&#62;getRootDataObject();

/**
 * The "root element name" is the element name of the document element
 * in this case 'letters'
 * This matches the 'name' attribute of the document element in the xsd and matches
 * the element name from the xml
 */
echo "The document element name is " . $document-&#62;getRootElementName() . "\n";
assert($document-&#62;getRootElementName() == 'letters'); // a property of the document

/**
 * The "root element URI" is the namespace part of the element name of the document element
 * in this case 'http://letterSchema' since 'letters' is in that namespace
 * This is taken from the xsd and matches the namespace picked up from the xml
 */
echo "The document element is in the namespace " . $document-&#62;getRootElementURI() . "\n";
assert($document-&#62;getRootElementURI() == 'http://letterSchema'); // a property of the document

/**
 * The type name is taken from the SDO model
 * The XML-SDO mapping rules make this either:
 *   The name of the complexType if there is one (in this case there is)
 *   The document element name if there no complexType
 * This is taken from the xsd
 */
echo "The type name of the root data object is " . $root_do-&#62;getTypeName() . "\n";
assert($root_do-&#62;getTypeName() == 'FormLetter');

/**
 * The type's namespaceURI is taken from the SDO model
 * The XML-SDO mapping rules ensure that this will always be the same as
 * the namepace URI of the document element
 */
echo "The namespaceURI of the root data object is " . $root_do-&#62;getTypeNamespaceURI() . "\n";
assert($root_do-&#62;getTypeNamespaceURI() == 'http://letterSchema');

?&#62;

The output from this program is as follows:

The document element name is letters
The document element is in the namespace http://letterSchema
The type name of the root data object is FormLetter
The namespaceURI of the root data object is http://letterSchema

Example 6. Printing the SDO model

The XML DAS provides a simple means to see what types and properties have been loaded. The php "print" or "echo" instruction will print out the types and properties.

&#60;?php
/**
 * Illustrate printing out the model
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
print $xmldas;

?&#62;

The output from this program is as follows:

object(SDO_XML_DAS)#1 {
18 types have been defined. The types and their properties are::
1. commonj.sdo:BigDecimal
2. commonj.sdo:BigInteger
3. commonj.sdo:Boolean
4. commonj.sdo:Byte
5. commonj.sdo:Bytes
6. commonj.sdo:ChangeSummary
7. commonj.sdo:Character
8. commonj.sdo:DataObject
9. commonj.sdo:Date
10. commonj.sdo:Double
11. commonj.sdo:Float
12. commonj.sdo:Integer
13. commonj.sdo:Long
14. commonj.sdo:Short
15. commonj.sdo:String
16. commonj.sdo:URI
17. http://letterSchema:FormLetter
    - date (commonj.sdo:String)
    - firstName (commonj.sdo:String)
    - lastName (commonj.sdo:String)
18. http://letterSchema:RootType
    - letters (http://letterSchema:FormLetter)

Predefined Classes

The XML DAS provides two main classes. The first is SDO_DAS_XML which is the main class used to fetch the data from the XML source and used to write the data back. The second is the SDO_DAS_XML_Document class, which represents the data in the XML document.

There are also some exception classes which can be thrown if errors are found when looking for or parsing the xsd or xml files.

SDO_DAS_XML

This is the main class of the XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files,

Methods

  • create This is a static method available in the SDO_DAS_XML class. Used to construct an SDO_DAS_XML object.

  • addTypes Works in much the same way as create() but used to add the contents of a second or subsequent schema file to an XML DAS that has already been created.

  • createDataObject Can be used to construct an SDO data object of a given type.

  • createDocument Can be used to construct an XML Document object from scratch.

  • loadFile Loads the xml instance document from a file. This file can be at local file system or it can be on a remote host.

  • loadString same as the above method. Loads the xml instance which is available as string.

  • saveFile save SDO_DAS_XML_Document object as a xml file.

  • saveString save SDO_DAS_XML_Document object as a xml string.

SDO_DAS_XML_Document

This class can be used to get to the name and namespace of the document element, and to get to the root data object of the document. Lastly, it can also be used to set the XML version and encoding of a document on output.

Methods

  • getRootDataObject gets the root DataObject.

  • getRootElementName gets the root DataObject's name.

  • getRootElementURI gets the root DataObject's URI.

  • setEncoding sets the encoding string with the given value.

  • setXMLDeclaraion to set/unset the xml declaration.

  • setXMLVersion sets the xml version with the given value.

SDO_DAS_XML_ParserException

Is a subclass of SDO_Exception. Thrown for any parser errors while loading the xsd/xml file.

SDO_DAS_XML_FileException

Is a subclass of SDO_Exception. Thrown by any of the methods that load data from a file, when the file cannot be found.

Limitations compared with SDO 2.0 specification

The SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Service. The XML DAS implements the mapping described in the SDO 2.0 specification with some restrictions. A detailed list is of the limitations is:

XML Simple Types

  1. Simple Type with sdoJava:instanceClass - no PHP equivalent provided.

  2. Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.

  3. Simple Type with list of itemType.

  4. Simple Type with union.

XML Complex Types

  1. Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.

XSD Attribute

  1. Attribute with sdo:aliasName - no PHP support for SDO property aliases.

  2. Attribute with default value - no PHP support for SDO property defaults.

  3. Attribute with fixed value - no PHP support for SDO read-only properties or default values.

  4. Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".

  5. Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

XSD Elements

  1. Element with sdo:aliasName - no PHP support for SDO property aliases.

  2. Element with substitution group.

XSD Elements with Simple Type

  1. Element of SimpleType with default - no PHP support for SDO defaults

  2. Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.

  3. Element of SimpleType with sdo:string - no support for sdo:string="true".

  4. Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."

  5. Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

Table of Contents
SDO_DAS_XML_Document::getRootDataObject -- Returns the root SDO_DataObject
SDO_DAS_XML_Document::getRootElementName -- Returns root element's name
SDO_DAS_XML_Document::getRootElementURI -- Returns root element's URI string
SDO_DAS_XML_Document::setEncoding -- Sets the given string as encoding
SDO_DAS_XML_Document::setXMLDeclaration -- Sets the xml declaration
SDO_DAS_XML_Document::setXMLVersion -- Sets the given string as xml version
SDO_DAS_XML::addTypes -- To load a second or subsequent schema file to a SDO_DAS_XML object
SDO_DAS_XML::create -- To create SDO_DAS_XML object for a given schema file
SDO_DAS_XML::createDataObject -- Creates SDO_DataObject for a given namespace URI and type name
SDO_DAS_XML::createDocument -- Creates an XML Document object from scratch, without the need to load a document from a file or string.
SDO_DAS_XML::loadFile -- Returns SDO_DAS_XML_Document object for a given path to xml instance document
SDO_DAS_XML::loadString -- Returns SDO_DAS_XML_Document for a given xml instance string
SDO_DAS_XML::saveFile -- Saves the SDO_DAS_XML_Document object to a file
SDO_DAS_XML::saveString -- Saves the SDO_DAS_XML_Document object to a string

Prev | Home | Next
SDO_Sequence::move | Up | SDO_DAS_XML_Document::getRootDataObject


SDO Relational Data Access Service Functions

PHP Manual
Prev Next

CXLIII. SDO Relational Data Access Service 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.

In order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.

The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment relationships and so on. You specify this information as metadata when you construct the Relational DAS.

Overview of Operation

  1. The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.

  2. The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.

    The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment relationships. There may also be SDO non-containment references within the data.

    Once the query has been executed and the data graph constructed, there is no need for either that instance of the the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.

  3. Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.

  4. Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.

There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.

Installation

The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.

In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path .

Your application will of course need to include the Relational DAS with a statement like this:

&#60;?php
require_once 'SDO/DAS/Relational.php';
?&#62;

Requirements

The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0.

The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations

  • MySQL 4.1.14, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0.

  • MySQL 4.1.13, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql . You will need to configure PHP with the --with-pdo-mysql option.

  • DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0.

  • DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.

The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.

Limitations

There are the following limitations in the current release of the Relational DAS:

  • No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.

  • Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment relationships and single-valued non-containment references. In SDO, whether a property describes a single- or multi-valued relationship, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.

  • No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.

  • Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.

Examples

This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the Service Data Objects specification or the Examples section of the documentation for the SDO extension.

The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.

The examples below and others can all be found in the Scenarios directory in the Relational DAS package.

The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.

These examples all differ from the expected use of SDO in two important respects.

First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialised and deserialised into the PHP session one or more times as the application interacts with an end user.

Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.

Specifying the metadata

This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.

When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalised into a graph.

Database metadata

The first argument to the constructor describes the target relational database.

Each table is described by an associative array with up to four keys.

Key | Value
name | The name of the table.
columns | An array listing the names of the columns, in any order.
PK | The name of the column containing the primary key.
FK | An array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified.

&#60;?php
/*****************************************************************
* METADATA DEFINING THE DATABASE
******************************************************************/
$company_table = array (
    'name' =&#62; 'company',
    'columns' =&#62; array('id', 'name',  'employee_of_the_month'),
    'PK' =&#62; 'id',
    'FK' =&#62; array (
        'from' =&#62; 'employee_of_the_month',
        'to' =&#62; 'employee',
        ),
    );
$department_table = array (
    'name' =&#62; 'department',
    'columns' =&#62; array('id', 'name', 'location', 'number', 'co_id'),
    'PK' =&#62; 'id',
    'FK' =&#62; array (
        'from' =&#62; 'co_id',
        'to' =&#62; 'company',
        )
    );
$employee_table = array (
    'name' =&#62; 'employee',
    'columns' =&#62; array('id', 'name', 'SN', 'manager', 'dept_id'),
    'PK' =&#62; 'id',
    'FK' =&#62; array (
        'from' =&#62; 'dept_id',
        'to' =&#62; 'department',
        )
    );
$database_metadata = array($company_table, $department_table, $employee_table);
?&#62;

This metadata corresponds to a relational database that might have been defined to MySQL as:

create table company (
   id integer auto_increment,
   name char(20),
   employee_of_the_month integer,
   primary key(id)
 );
 create table department (
   id integer auto_increment,
   name char(20),
   location char(10),
   number integer(3),
   co_id integer,
   primary key(id)
 );
 create table employee (
   id integer auto_increment,
   name char(20),
   SN char(4),
   manager tinyint(1),
   dept_id integer,
   primary key(id)
 );

or to DB2 as:

create table company ( \
    id integer not null generated by default as identity,  \
    name varchar(20), \
    employee_of_the_month integer, \
    primary key(id) )
create table department ( \
    id integer not null generated by default as identity, \
    name varchar(20), \
    location varchar(10), \
    number integer, \
    co_id integer, \
    primary key(id) )
create table employee ( \
    id integer not null generated by default as identity, \
    name varchar(20), \
    SN char(4), \
    manager smallint, \
    dept_id integer, \
    primary key(id) )

Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.

There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.

There are a few simple rules to be followed when constructing the database metadata:

  • All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.

  • It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.

  • In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.

Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.

What the Relational DAS does with the metadata

The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.

All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.

Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment relationships below.

Specifying the application root type

The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.

Specifying the SDO containment relationships

The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.

The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO property defining a multi-valued containment relationship in the SDO model.

&#60;?php
$department_containment = array( 'parent' =&#62; 'company', 'child' =&#62; 'department');
$employee_containment = array( 'parent' =&#62; 'department', 'child' =&#62; 'employee');

$SDO_containment_metadata = array($department_containment, $employee_containment);
?&#62;

Foreign keys in the database metadata are interpreted as properties with either multi-valued containment relationships or single-valued non-containment references, depending on whether they have a corresponding SDO containment relationship specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment relationships. Each containment relationship mentioned in the SDO containment relationships metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment relationships do not appear in the data objects, instead each is represented by a containment relationship from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.

The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment relationships metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment relationships, and to assign the object to it. This is illustrated in the later examples below.

One-table examples

The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.

For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.

Example 1. Creating a data object

The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object.

Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'.

When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name) VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
 * Obtain a root object and create a company object underneath.
 * Make a simple change to the data object.
 ***************************************************************/
$root = $das  -&#62; createRootDataObject();
$acme = $root -&#62; createDataObject('company');

$acme-&#62;name = "Acme";

/**************************************************************
 * Get a database connection and write the object to the database
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das -&#62; applyChanges($dbh, $root);
?&#62;

Example 2. Retrieving a data object

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das-&#62;executeQuery($dbh,
           'select name, id from company where name="Acme"',
            array('company.name', 'company.id') );

/**************************************************************
 * Echo name and id
 ***************************************************************/
foreach ($root['company'] as $company) {
    echo "Company obtained from the database has name = " .
    $company['name'] . " and id " . $company['id'] . "\n";
}
?&#62;

Example 3. Updating a data object

This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time.

In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das-&#62;executeQuery($dbh,
    'select name, id from company where name="Acme" or name="emcA"',
    array('company.name', 'company.id') );

/**************************************************************
 * Alter the name of just the first company
 ***************************************************************/
$company = $root['company'][0];
echo "obtained a company with name of " . $company-&#62;name . "\n";
$company-&#62;name = strrev($company-&#62;name);

/**************************************************************
 * Write the change back
 ***************************************************************/
$das-&#62;applyChanges($dbh,$root);
?&#62;

Example 4. Deleting a data object

Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset.

In this example they are all deleted in one go by unsetting the containing property (the property defining the containment relationship). It is also possible to delete them individually.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das-&#62;executeQuery($dbh,
    'select name, id from company where name="Acme" or name="emcA"',
    array('company.name', 'company.id') );

/**************************************************************
 * Delete any companies found from the data graph
 ***************************************************************/
unset($root['company']);

/**************************************************************
 * Write the change(s) back
 ***************************************************************/
$das-&#62;applyChanges($dbh,$root);
?&#62;

Two-table examples

The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.

In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.

You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.

Example 5. One company, one department - Create

As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object.

When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the two tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh-&#62;prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt-&#62;execute();
$pdo_stmt = $dbh-&#62;prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt-&#62;execute();

/**************************************************************
* Create a company with name Acme and one department, the Shoe department
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das -&#62; createRootDataObject();

$acme = $root -&#62; createDataObject('company');
$acme -&#62; name = "Acme";

$shoe = $acme-&#62;createDataObject('department');
$shoe-&#62;name = 'Shoe';

$das -&#62; applyChanges($dbh, $root);

?&#62;

Example 6. One company, one department - Retrieve and Update

In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set.

Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object.

In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath.

In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Retrieve the company and Shoe department, then delete Shoe and add IT
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das-&#62;executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];            // get the first company - will be 'Acme'
$shoe = $acme['department'][0];         // get the first department underneath - will be 'Shoe'

unset($acme['department'][0]);

$it = $acme-&#62;createDataObject('department');
$it-&#62;name = 'IT';

$das -&#62; applyChanges($dbh, $root);
?&#62;

Example 7. One company, two departments - Retrieve and Delete

In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it.

Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing property which in this case is the company property on the special root object. You must use:

&#60;?php
unset($root['company'][0]);
?&#62;
and not:
&#60;?php
unset($acme); //WRONG
?&#62;
Simply unsetting $acme would destroy the variable but leave the data in the data graph untouched.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Retrieve the company and IT department, then delete the whole company
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das-&#62;executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];
$it = $acme['department'][0];

unset($root['company'][0]);

$das -&#62; applyChanges($dbh, $root);

?&#62;

Three-table example

The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.

Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.

Example 8. One company, one department, one employee - Create

In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known.

Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment relationships.

When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment relationships, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the the company record is updated with the employee's primary key.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the three tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh-&#62;prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt-&#62;execute();
$pdo_stmt = $dbh-&#62;prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt-&#62;execute();
$pdo_stmt = $dbh-&#62;prepare('DELETE FROM EMPLOYEE;');
$rows_affected = $pdo_stmt-&#62;execute();

/*************************************************************************************
* Create a tiny but complete company.
* The company name is Acme.
* There is one department, Shoe.
* There is one employee, Sue.
* The employee of the month is Sue.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root             = $das  -&#62; createRootDataObject();
$acme             = $root -&#62; createDataObject('company');
$acme -&#62; name     = "Acme";
$shoe             = $acme -&#62; createDataObject('department');
$shoe -&#62; name     = 'Shoe';
$shoe -&#62; location = 'A-block';
$sue             = $shoe -&#62; createDataObject('employee');
$sue -&#62; name     = 'Sue';
$acme -&#62; employee_of_the_month = $sue;

$das -&#62; applyChanges($dbh, $root);

echo "Wrote back Acme with one department and one employee\n";
?&#62;

Example 9. One company, one department, one employee - Retrieve and update

The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example.

The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
 * Find the company again and change various aspects.
 * Change the name of the company, department and employee.
 * Add a second department and a new employee.
 * Change the employee of the month.
 *************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das-&#62;executeQuery($dbh,
    "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
    "from company c, department d, employee e " .
    "where e.dept_id = d.id and d.co_id = c.id and c.name='Acme'",
     array('company.id','company.name','company.employee_of_the_month',
     'department.id','department.name','employee.id','employee.name'));
$acme     = $root['company'][0];

$shoe    = $acme-&#62;department[0];
$sue    = $shoe -&#62; employee[0];

$it     = $acme-&#62;createDataObject('department');
$it-&#62;name = 'IT';
$it-&#62;location = 'G-block';
$billy     = $it-&#62;createDataObject('employee');
$billy-&#62;name = 'Billy';

$acme-&#62;name = 'MegaCorp';
$shoe-&#62;name = 'Footwear';
$sue-&#62;name = 'Susan';

$acme-&#62;employee_of_the_month = $billy;
$das -&#62; applyChanges($dbh, $root);
echo "Wrote back company with extra department and employee and all the names changed (Megacorp/Footwear/Susan)\n";

?&#62;

Example 10. One company, two departments, two employees - Retrieve and delete

The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.

&#60;?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
 * Now read it one more time and delete it.
 * You can delete part, apply the changes, then carry on working with the same graph but
 * care is needed to keep closure - you cannot delete the employee who is eotm without
 * reassigning. For safety here we delete the company all in one go.
 *************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das-&#62;executeQuery($dbh,
    "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
    "from company c, department d, employee e " .
    "where e.dept_id = d.id and d.co_id = c.id and c.name='MegaCorp';",
     array('company.id','company.name','company.employee_of_the_month',
     'department.id','department.name','employee.id','employee.name'));
$megacorp = $root['company'][0];

unset($root['company']);
$das -&#62; applyChanges($dbh, $root);

echo "Deleted the company, departments and employees all in one go.\n";

?&#62;

Tracing

You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.

Predefined Classes

The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.

SDO_DAS_Relational

The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.

Methods

  • __construct - construct the Relational DAS with a model derived from the passed metadata

  • createRootDataObject - obtain an otherwise empty data graph containing just the special root object

  • executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph

  • executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency

SDO_DAS_Relational_Exception

Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.

Table of Contents
SDO_DAS_Relational::applyChanges -- Applies the changes made to a data graph back to the database.
SDO_DAS_Relational::__construct -- Creates an instance of a Relational Data Access Service
SDO_DAS_Relational::createRootDataObject -- Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
SDO_DAS_Relational::executePreparedQuery -- Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
SDO_DAS_Relational::executeQuery -- Executes a given SQL query against a relational database and returns the results as a normalised data graph.

Prev | Home | Next
SDO_DAS_XML::saveString | Up | SDO_DAS_Relational::applyChanges


PostgreSQL Session Save Handler

PHP Manual
Prev Next

CXLVI. PostgreSQL Session Save Handler

Introduction

Note: This extension is not available on Windows platforms.

This module provides an additional session save handler for the session module using PostgreSQL as a storage system. A user-level session storage function may also be used - session_set_save_handler(), but this module is written in C and therefore could be twice as fast, compared to a session save handler written in PHP.

Session PgSQL is designed to scale any size of web sites and offers some advanced features:

session tables are created automatically
automatic session table vacuum
better garbage collection
multiple PostgreSQL servers support
automatic database server failover (switching)
automatic database server load balancing if there are multiple PostgreSQL servers.
short circuit UPDATE

Requirements

You need at least PHP >= 4.3.0, and PostgreSQL >=7.2.0 as database server. libpq that comes with PostgreSQL 7.2.0 or later (and header files to build) and libmm (and header files).

Installation

Short installation note:

  • Untar the tar.gz archive into php4/ext (Latest official releases can be found at SourceForge PHP Form Extension Project)

  • If the new directory is now called something like session_pgsql. You should name it to session_pgsql (except you only want to build it as self-contained php-module).

  • Run ./buildconf in php4

  • Run configure --with-session-pgsql (and your other options)

  • make; make install

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PostgreSQL session save handler is still under development. Refer to the README file in the source distribution for configuration details.

Table definitions

Session table definition

CREATE TABLE php_session (
  sess_id            text,
  sess_name          text,
  sess_data          text,
  sess_created       integer,
  sess_modified      integer,
  sess_expire        integer,
  sess_addr_created  text,
  sess_addr_modified text,
  sess_counter       integer,
  sess_error         integer,
  sess_warning       integer,
  sess_notice        integer,
  sess_err_message   text,
  sess_custom        text
);

CREATE INDEX php_session_idx ON php_session USING BTREE (sess_id);

Warning

If you use HASH for INDEX, you'll have a deadlock problem when the server load is very high. Even if it's unlikely to have a deadlock under normal operation, it can occur. Do not use HASH for INDEX.

You may change the session table as long as all fields are defined.

Application variables table definition

CREATE TABLE php_app_vars (
  app_modified       integer,
  app_name           text,
  app_vars           text
);

Contact Information

I have at the moment not very much time to further develop this extension. I will implement more and more features in the near future.

If you have comments, bug fixes, enhancements or want to help developing this, you can drop me a mail at yohgaki@php.net. Any help is very welcome.

Table of Contents
session_pgsql_add_error -- Increments error counts and sets last error message
session_pgsql_get_error -- Returns number of errors and last error message
session_pgsql_get_field -- Get custom field value
session_pgsql_reset -- Reset connection to session database servers
session_pgsql_set_field -- Set custom field value
session_pgsql_status -- Get current save handler status

Prev | Home | Next
sesam_settransaction | Up | session_pgsql_add_error


Statistics Functions

PHP Manual
Prev Next

CLVII. Statistics Functions

Introduction

This is the statistics extension. It contains few dozens of functions useful for statistical computations. It is a wrapper around 2 scientific libraries, namely DCDFLIB (Library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters) by B. Brown & J. Lavato and RANDLIB by Barry Brown, James Lavato & Kathy Russell. Includes CD and PD functions.

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/stats.

You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.

Requirements

No external libraries are needed. The extension comes bundled with the libraries used.

Table of Contents
stats_absolute_deviation -- Returns the absolute deviation of an array of values
stats_cdf_beta -- CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
stats_cdf_binomial -- Calculates any one parameter of the binomial distribution given values for the others.
stats_cdf_cauchy -- Not documented
stats_cdf_chisquare -- Calculates any one parameter of the chi-square distribution given values for the others.
stats_cdf_exponential -- Not documented
stats_cdf_f -- Calculates any one parameter of the F distribution given values for the others.
stats_cdf_gamma -- Calculates any one parameter of the gamma distribution given values for the others.
stats_cdf_laplace -- Not documented
stats_cdf_logistic -- Not documented
stats_cdf_negative_binomial -- Calculates any one parameter of the negative binomial distribution given values for the others.
stats_cdf_noncentral_chisquare -- Calculates any one parameter of the non-central chi-square distribution given values for the others.
stats_cdf_noncentral_f -- Calculates any one parameter of the Non-central F distribution given values for the others.
stats_cdf_poisson -- Calculates any one parameter of the Poisson distribution given values for the others.
stats_cdf_t -- Calculates any one parameter of the T distribution given values for the others.
stats_cdf_uniform -- Not documented
stats_cdf_weibull -- Not documented
stats_covariance -- Computes the covariance of two data sets
stats_den_uniform -- Not documented
stats_dens_beta -- Not documented
stats_dens_cauchy -- Not documented
stats_dens_chisquare -- Not documented
stats_dens_exponential -- Not documented
stats_dens_f --
stats_dens_gamma -- Not documented
stats_dens_laplace -- Not documented
stats_dens_logistic -- Not documented
stats_dens_negative_binomial -- Not documented
stats_dens_normal -- Not documented
stats_dens_pmf_binomial -- Not documented
stats_dens_pmf_hypergeometric --
stats_dens_pmf_poisson -- Not documented
stats_dens_t -- Not documented
stats_dens_weibull -- Not documented
stats_harmonic_mean -- Returns the harmonic mean of an array of values
stats_kurtosis -- Computes the kurtosis of the data in the array
stats_rand_gen_beta -- Generates beta random deviate
stats_rand_gen_chisquare -- Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
stats_rand_gen_exponential -- Generates a single random deviate from an exponential distribution with mean "av"
stats_rand_gen_f -- Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates
stats_rand_gen_funiform -- Generates uniform float between low (exclusive) and high (exclusive)
stats_rand_gen_gamma -- Generates random deviates from a gamma distribution
stats_rand_gen_ibinomial_negative -- Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
stats_rand_gen_ibinomial -- Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
stats_rand_gen_int -- Generates random integer between 1 and 2147483562
stats_rand_gen_ipoisson -- Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
stats_rand_gen_iuniform -- Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
stats_rand_gen_noncenral_chisquare -- Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
stats_rand_gen_noncentral_f -- Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
stats_rand_gen_noncentral_t -- Generates a single random deviate from a noncentral T distribution
stats_rand_gen_normal -- Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
stats_rand_gen_t -- Generates a single random deviate from a T distribution
stats_rand_get_seeds -- Not documented
stats_rand_phrase_to_seeds -- generate two seeds for the RGN random number generator
stats_rand_ranf -- Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
stats_rand_setall -- Not documented
stats_skew -- Computes the skewness of the data in the array
stats_standard_deviation -- Returns the standard deviation
stats_stat_binomial_coef -- Not documented
stats_stat_correlation -- Not documented
stats_stat_gennch -- Not documented
stats_stat_independent_t -- Not documented
stats_stat_innerproduct --
stats_stat_noncentral_t -- Calculates any one parameter of the noncentral t distribution give values for the others.
stats_stat_paired_t -- Not documented
stats_stat_percentile -- Not documented
stats_stat_powersum -- Not documented
stats_variance -- Returns the population variance

Prev | Home | Next
ssh2_tunnel | Up | stats_absolute_deviation


Swish-e bindings

PHP Manual
Prev Next

CLXI. Swish-e bindings

Introduction

The swish extension provides the bindings for Swish-e API. Swish-e stands for "Simple Web Indexing System for Humans - Enhanced" and is an open source system for indexing and search. Swish-e itself is licensed under GPL license, but uses a clause that allows applications to link against the library if every copy of the combined work is accompanied by the URL to Swish-e source code. Here it is: http://swish-e.org.

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

PECL/swish 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/swish.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Examples

Example 1. Basic search query

&#60;?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish-&#62;query("test OR text");

    echo "Found ", $results-&#62;hits, " results\n";
    while ($result = $results-&#62;nextResult()) {
        var_dump($result);
        break; //break after the first result
    }

} catch (SwishException $e) {
    echo "Error: ", $e-&#62;getMessage(), "\n";
}

?&#62;

The above example will output something similar to:

Found 9 results
object(SwishResult)#3 (8) {
  ["swishreccount"]=>
  int(1)
  ["swishrank"]=>
  int(1000)
  ["swishfilenum"]=>
  int(10)
  ["swishdbfile"]=>
  string(13) "index.swish-e"
  ["swishdocpath"]=>
  string(23) "README.SUBMITTING_PATCH"
  ["swishtitle"]=>
  NULL
  ["swishdocsize"]=>
  int(4557)
  ["swishlastmodified"]=>
  int(1072136752)
}

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.

Swish::META_TYPE_UNDEF (integer)

Swish::META_TYPE_STRING (integer)

Swish::META_TYPE_ULONG (integer)

Swish::META_TYPE_DATE (integer)

Swish::IN_FILE_BIT (integer)

Swish::IN_TITLE_BIT (integer)

Swish::IN_HEAD_BIT (integer)

Swish::IN_BODY_BIT (integer)

Swish::IN_COMMENTS_BIT (integer)

Swish::IN_HEADER_BIT (integer)

Swish::IN_EMPHASIZED_BIT (integer)

Swish::IN_META_BIT (integer)

Swish::IN_FILE (integer)

Swish::IN_TITLE (integer)

Swish::IN_HEAD (integer)

Swish::IN_BODY (integer)

Swish::IN_COMMENTS (integer)

Swish::IN_HEADER (integer)

Swish::IN_EMPHASIZED (integer)

Swish::IN_META (integer)

Swish::IN_ALL (integer)

Predefined Classes

Predefined Classes

Swish

Properties

  • indexes - the array of indexes used and their properties. Certain list of properties depends on Swish-e version.

Methods

  • Swish::__construct - constructs new Swish object. Throws SwishException on error.

  • Swish->prepare - prepares and returns SwishSearch object. Throws SwishException on error.

  • Swish->query - executes the query and returns SwishResults object. Throws SwishException on error.

  • Swish->getMetaList - returns an array of meta entries for the given index file.

  • Swish->getPropertyList - returns an array of properties for the given index file.

SwishSearch

Methods

  • SwishSearch->setStructure - sets the structure flag in the search object. This flag is used to limit search to certain parts of HTML documents.

  • SwishSearch->setPhraseDelimiter - sets the phrase delimiter character. The default delimiter is double-quotes.

  • SwishSearch->setSort - sets the sort order of the results.

  • SwishSearch->setLimit - sets the limits for the search. Throws SwishException on error.

  • SwishSearch->resetLimit - resets the limits.

  • SwishSearch->execute - executes the query and returns SwishResults object. Throws SwishException on error.

SwishResults

Properties

  • hits - the number of results in this SwishResults object.

  • indexes - the array of indexes used in the search.

Methods

  • SwishResults->nextResult - returns next SwishResult object or FALSE if no more results are available.

  • SwishResults->seekResult - sets the current seek position in the SwishResults object. Throws SwishException on error.

  • SwishResults->getParsedWords - returns an array of words in the query with stopwords removed.

  • SwishResults->getRemovedStopwords - returns an array of removed stopwords.

SwishResult

Properties

  • Properties list depends on Swish-e version, see examples.

Methods

  • SwishResult->getMetaList - returns an array of meta entries for the index used in this result.

  • SwishResult->stem - stems the word and returns result as an array of strings. Throws SwishException on error.

SwishException

SwishException extends the build in Exception class and possesses the same set of properties and methods. See the Section called Extending Exceptions in Chapter 20 for more details.

Table of Contents
Swish::__construct -- Construct a Swish object
Swish->getMetaList -- Get the list of meta entries for the index
Swish->getPropertyList -- Get the list of properties for the index
Swish->prepare -- Prepare a search query
Swish->query -- Execute a query and return results object
SwishResult->getMetaList -- Get a list of meta entries
SwishResult->stem -- Stems the given word
SwishResults->getParsedWords -- Get an array of parsed words
SwishResults->getRemovedStopwords -- Get an array of stopwords removed from the query
SwishResults->nextResult -- Get the next search result
SwishResults->seekResult -- Set current seek pointer to the given position
SwishSearch->execute -- Execute the search and get the results
SwishSearch->resetLimit -- Reset the search limits
SwishSearch->setLimit -- Set the search limits
SwishSearch->setPhraseDelimiter -- Set the phrase delimiter
SwishSearch->setSort -- Set the sort order
SwishSearch->setStructure -- Set the structure flag in the search object

Prev | Home | Next
swf_viewport | Up | Swish::__construct


Unicode Functions

PHP Manual
Prev Next

CLXVI. Unicode Functions

Introduction

Unicode Support.

Warning

This extension is still in development and it isn't available to public yet.

Requirements

ICU 3.4 or later is required.

Installation

First you should download and install ICU:

Example 1. install ICU on Unix

./configure --disable-threads --enable-extras --enable-icuio --enable-layout
make && make install

Then checkout latest PHP and configure it --with-icu-dir=<dir> option, where <dir> was the dir to where you installed ICU. You don't need to explicitly use this option if you install ICU to a standard location.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Unicode Configuration Options

Name | Default | Changeable | Changelog
unicode.fallback_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_mode | "2" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_subst_char | "3f" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.http_input_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.output_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.runtime_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.script_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.semantics | off | PHP_INI_PERDIR | Available since PHP 6.0.0.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

Here's a short explanation of the configuration directives.

unicode.output_encoding string

Default encoding for output.

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.

constant | value | description
U_INVALID_STOP | 0 | stop at first invalid character
U_INVALID_SKIP | 1 | skip invalid characters
U_INVALID_SUBSTITUTE | 2 | replace invalid characters
U_INVALID_ESCAPE | 3 | escape invalid characters

Table of Contents
i18n_loc_get_default -- Get the default Locale
i18n_loc_set_default -- Set the default Locale
unicode_encode -- Set encoding of a unicode string
unicode_semantics -- Check whether unicode semantics is enabled

Prev | Home | Next
token_name | Up | i18n_loc_get_default


win32ps Functions

PHP Manual
Prev Next

CLXXIII. win32ps Functions

Introduction

The win32ps extension is a Windows specific extension that allows PHP retrieve statistics about process and memory utilization.

Requirements

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of Windows derived from Windows NT should be compatible.

Installation

Installing from PECL

  1. You can download php_win32ps.dll from pecl4win.php.net.

  2. Copy the php_win32ps.dll into your extension_dir.

  3. Load the extension from your php.ini

    extension=php_win32ps.dll

Examples

Example 1. Statistics about the current PHP process

&#60;?php
print_r(win32_ps_stat_proc());
/*
    Array
    (
        [pid] =&#62; 936
        [exe] =&#62; D:\Daten\Source\php-5.1\Debug_TS\php.exe
        [mem] =&#62; Array
            (
                [page_fault_count] =&#62; 2062
                [peak_working_set_size] =&#62; 8396800
                [working_set_size] =&#62; 8396800
                [quota_peak_paged_pool_usage] =&#62; 32080
                [quota_paged_pool_usage] =&#62; 31876
                [quota_peak_non_paged_pool_usage] =&#62; 4240
                [quota_non_paged_pool_usage] =&#62; 3888
                [pagefile_usage] =&#62; 5865472
                [peak_pagefile_usage] =&#62; 5865472
            )

        [tms] =&#62; Array
            (
                [created] =&#62; 0.093
                [kernel] =&#62; 0.015
                [user] =&#62; 0.062
            )

    )
*/
?&#62;

Example 2. Statistics about global memory utilization

&#60;?php
print_r(win32_ps_stat_mem());
/*
    Array
    (
        [load] =&#62; 37
        [unit] =&#62; 1024
        [total_phys] =&#62; 1048096
        [avail_phys] =&#62; 649960
        [total_pagefile] =&#62; 2521368
        [avail_pagefile] =&#62; 2237940
        [total_virtual] =&#62; 2097024
        [avail_virtual] =&#62; 2057848
    )
*/
?&#62;

Table of Contents
win32_ps_list_procs -- List running processes
win32_ps_stat_mem -- Stat memory utilization
win32_ps_stat_proc -- Stat process

Prev | Home | Next
wddx_unserialize | Up | win32_ps_list_procs


win32service Functions

PHP Manual
Prev Next

CLXXIV. win32service Functions

Introduction

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.

Requirements

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of windows derived from Windows NT should be compatible.

Installation

Installing from PECL

  1. You can download php_win32service.dll from http://snaps.php.net/win32/. Choose the PECL_X_X folder that matches you PHP version.

  2. Copy the php_win32service.dll into your extension_dir.

  3. Load the extension from your php.ini

    extension=php_win32service.dll

Examples

Example 1. Registering a PHP script to run as a service

&#60;?php
win32_create_service(array(
        'service' =&#62; 'dummyphp',                 # the name of your service
        'display' =&#62; 'sample dummy PHP service', # description
        'params' =&#62; 'c:\path\to\script.php run', # path to the script and parameters
    ));
?&#62;

Example 2. Unregistering a service

&#60;?php
win32_delete_service('dummyphp');
?&#62;

Example 3. Running as a service

&#60;?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?&#62;

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.

WIN32_SERVICE_CONTROL_CONTINUE (integer)

WIN32_SERVICE_CONTROL_INTERROGATE (integer)

WIN32_SERVICE_CONTROL_PAUSE (integer)

WIN32_SERVICE_CONTROL_STOP (integer)

WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE (integer)

WIN32_SERVICE_CONTROL_POWEREVENT (integer)

WIN32_SERVICE_CONTROL_SESSIONCHANGE (integer)

WIN32_ERROR_CALL_NOT_IMPLEMENTED (integer)

WIN32_NO_ERROR (integer)

WIN32_SERVICE_RUNNING (integer)

WIN32_SERVICE_STOPPED (integer)

WIN32_SERVICE_STOP_PENDING (integer)

WIN32_SERVICE_WIN32_OWN_PROCESS (integer)

WIN32_SERVICE_INTERACTIVE_PROCESS (integer)

WIN32_SERVICE_STOPPED (integer)

WIN32_SERVICE_START_PENDING (integer)

WIN32_SERVICE_STOP_PENDING (integer)

WIN32_SERVICE_RUNNING (integer)

WIN32_SERVICE_CONTINUE_PENDING (integer)

WIN32_SERVICE_PAUSE_PENDING (integer)

WIN32_SERVICE_PAUSED (integer)

WIN32_SERVICE_ACCEPT_NETBINDCHANGE (integer)

WIN32_SERVICE_ACCEPT_PARAMCHANGE (integer)

WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE (integer)

WIN32_SERVICE_ACCEPT_SHUTDOWN (integer)

WIN32_SERVICE_ACCEPT_STOP (integer)

WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE (integer)

WIN32_SERVICE_ACCEPT_POWEREVENT (integer)

WIN32_SERVICE_ACCEPT_SESSIONCHANGE (integer)

WIN32_SERVICE_FILE_SYSTEM_DRIVER (integer)

WIN32_SERVICE_KERNEL_DRIVER (integer)

WIN32_SERVICE_WIN32_SHARE_PROCESS (integer)

WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS (integer)

Table of Contents
win32_create_service -- Creates a new service entry in the SCM database
win32_delete_service -- Deletes a service entry from the SCM database
win32_get_last_control_message -- Returns the last control message that was sent to this service
win32_query_service_status -- Queries the status of a service
win32_set_service_status -- Update the service status
win32_start_service_ctrl_dispatcher -- Registers the script with the SCM, so that it can act as the service with the given name
win32_start_service -- Starts a service
win32_stop_service -- Stops a service

Prev | Home | Next
win32_ps_stat_proc | Up | win32_create_service


XMLReader functions

PHP Manual
Prev Next

CLXXIX. XMLReader functions

Introduction

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Installation

The XMLReader extension is available in PECL for PHP 5.0 and is included and enabled in PHP 5.1 by default. It can be enabled by adding the argument --enable-xmlreader (or --with-xmlreader before 5.1) to your configure line. The libxml extension is required.

Predefined Classes

XMLReader

Methods

  • XMLReader::close - Close the XMLReader input

  • XMLReader::expand - Export current node to a DOM node

  • XMLReader::getAttribute - Get value of attribute by name

  • XMLReader::getAttributeNo - Get value of attribute by position

  • XMLReader::getAttributeNs - Get value of attribute by name and URI

  • XMLReader::getParserProperty - Indicates if parser property is set or not

  • XMLReader::isValid - Indicates if document is valid

  • XMLReader::lookupNamespace - Get URI for prefix in scope of node

  • XMLReader::moveToAttribute - Positions reader on named attribute

  • XMLReader::moveToAttributeNo - Positions reader on attribute by index

  • XMLReader::moveToAttributeNs - Position reader on attribute by name and URI

  • XMLReader::moveToElement - Move to parent element of current attribute node

  • XMLReader::moveToFirstAttribute - Move to first attribute of node

  • XMLReader::moveToNextAttribute - Move to next attribute of node

  • XMLReader::next - Move to next element skipping children

  • XMLReader::open - Set URI to be parsed

  • XMLReader::read - Move to next node in stream

  • XMLReader::setParserProperty - Set parser property

  • XMLReader::setRelaxNGSchema - Set URI of RelaxNG schema to validate against

  • XMLReader::setRelaxNGSchemaSource - Set string containing RelaxNG schema to validate against

  • XMLReader::XML - Set string of data to be parsed

Properties

Table 1.

Name | Type | Read-only | Description
attributeCount | int | yes | The number of attributes on the node
baseURI | string | yes | The base URI of the node
depth | int | yes | Depth of the node in the tree starting at 0
hasAttributes | bool | yes | Indicates if node has attributes
hasValue | bool | yes | Indicates if node has a text value
isDefault | bool | yes | Indicates if attribute is defaulted from DTD
isEmptyElement | bool | yes | Indicates if node is an empty element tag
localName | string | yes | The local name of the node
name | string | yes | The qualified name of the node
namespaceURI | string | yes | The URI of the namespace associated with the node
nodeType | int | yes | The node type for the node
prefix | string | yes | The prefix of the namespace associated with the node
value | string | yes | The text value of the node
xmlLang | string | yes | The xml:lang scope which the node resides

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.

Warning

XMLReader uses class constants since PHP 5.1. Prior releases use global constants in the form XMLREADER_ELEMENT.

Table 2. XMLReader Node Types

Constant | Value | Description
XMLReader::NONE (integer) | 0 | No node type
XMLReader::ELEMENT (integer) | 1 | Start element
XMLReader::ATTRIBUTE (integer) | 2 | Attribute node
XMLReader::TEXT (integer) | 3 | Text node
XMLReader::CDATA (integer) | 4 | CDATA node
XMLReader::ENTITY_REF (integer) | 5 | Entity Reference node
XMLReader::ENTITY (integer) | 6 | Entity Declaration node
XMLReader::PI (integer) | 7 | Processing Instruction node
XMLReader::COMMENT (integer) | 8 | Comment node
XMLReader::DOC (integer) | 9 | Document node
XMLReader::DOC_TYPE (integer) | 10 | Document Type node
XMLReader::DOC_FRAGMENT (integer) | 11 | Document Fragment node
XMLReader::NOTATION (integer) | 12 | Notation node
XMLReader::WHITESPACE (integer) | 13 | Whitespace node
XMLReader::SIGNIFICANT_WHITESPACE (integer) | 14 | Significant Whitespace node
XMLReader::END_ELEMENT (integer) | 15 | End Element
XMLReader::END_ENTITY (integer) | 16 | End Entity
XMLReader::XML_DECLARATION (integer) | 17 | XML Declaration node

Table 3. XMLReader Parser Options

Constant | Value | Description
XMLReader::LOADDTD (integer) | 1 | Load DTD but do not validate
XMLReader::DEFAULTATTRS (integer) | 2 | Load DTD and default attributes but do not validate
XMLReader::VALIDATE (integer) | 3 | Load DTD and validate while parsing
XMLReader::SUBST_ENTITIES (integer) | 4 | Substitute entities and expand references
Table of Contents
XMLReader::close -- Close the XMLReader input
XMLReader::expand -- Returns a copy of the current node as a DOM object
XMLReader::getAttribute -- Get the value of a named attribute
XMLReader::getAttributeNo -- Get the value of an attribute by index
XMLReader::getAttributeNs -- Get the value of an attribute by localname and URI
XMLReader::getParserProperty -- Indicates if specified property has been set
XMLReader::isValid -- Indicates if the parsed document is valid
XMLReader::lookupNamespace -- Lookup namespace for a prefix
XMLReader::moveToAttribute -- Move cursor to a named attribute
XMLReader::moveToAttributeNo -- Move cursor to an attribute by index
XMLReader::moveToAttributeNs -- Move cursor to a named attribute
XMLReader::moveToElement -- Position cursor on the parent Element of current Attribute
XMLReader::moveToFirstAttribute -- Position cursor on the first Attribute
XMLReader::moveToNextAttribute -- Position cursor on the next Attribute
XMLReader::next -- Move cursor to next node skipping all subtrees
XMLReader::open -- Set the URI containing the XML to parse
XMLReader::read -- Move to next node in document
XMLReader::setParserProperty -- Set or Unset parser options
XMLReader::setRelaxNGSchema -- Set the filename or URI for a RelaxNG Schema
XMLReader::setRelaxNGSchemaSource -- Set the data containing a RelaxNG Schema
XMLReader::XML -- Set the data containing the XML to parse

Prev | Home | Next
xmlrpc_set_type | Up | XMLReader::close


XMLWriter Functions

PHP Manual
Prev Next

CLXXX. XMLWriter Functions

Introduction

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object oriented style or a procedural one. Every method documented describes the alternative procedural call.

Predefined Classes

XMLWriter

Methods

  • XMLWriter::endAttribute - End attribute

  • XMLWriter::endCData - End current CDATA

  • XMLWriter::endComment - Create end comment

  • XMLWriter::endDocument - End current document

  • XMLWriter::endDTDAttlist - End current DTD AttList

  • XMLWriter::endDTDElement - End current DTD element

  • XMLWriter::endDTDEntity - End current DTD Entity

  • XMLWriter::endDTD - End current DTD

  • XMLWriter::endElement - End current element

  • XMLWriter::endPI - End current PI

  • XMLWriter::flush - Flush current buffer

  • XMLWriter::fullEndElement - End current element

  • XMLWriter::openMemory - Create new xmlwriter using memory for string output

  • XMLWriter::openURI - Create new xmlwriter using source uri for output

  • XMLWriter::outputMemory - Returns current buffer

  • XMLWriter::setIndentString - Set string used for indenting

  • XMLWriter::setIndent - Toggle indentation on/off

  • XMLWriter::startAttributeNS - Create start namespaced attribute

  • XMLWriter::startAttribute - Create start attribute

  • XMLWriter::startCData - Create start CDATA tag

  • XMLWriter::startComment - Create start comment

  • XMLWriter::startDocument - Create document tag

  • XMLWriter::startDTDAttlist - Create start DTD AttList

  • XMLWriter::startDTDElement - Create start DTD element

  • XMLWriter::startDTDEntity - Create start DTD Entity

  • XMLWriter::startDTD - Create start DTD tag

  • XMLWriter::startElementNS - Create start namespaced element tag

  • XMLWriter::startElement - Create start element tag

  • XMLWriter::startPI - Create start PI tag

  • XMLWriter::text - Write text

  • XMLWriter::writeAttributeNS - Write full namespaced attribute

  • XMLWriter::writeAttribute - Write full attribute

  • XMLWriter::writeCData - Write full CDATA tag

  • XMLWriter::writeComment - Write full comment tag

  • XMLWriter::writeDTDAttlist - Write full DTD AttList tag

  • XMLWriter::writeDTDElement - Write full DTD element tag

  • XMLWriter::writeDTDEntity - Write full DTD Entity tag

  • XMLWriter::writeDTD - Write full DTD tag

  • XMLWriter::writeElementNS - Write full namesapced element tag

  • XMLWriter::writeElement - Write full element tag

  • XMLWriter::writePI - Writes a PI

  • XMLWriter::writeRaw - Write a raw XML text

Resource Types

There is one resource used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

Predefined Constants

This extension has no constants defined.

Table of Contents
XMLWriter::endAttribute -- End attribute
XMLWriter::endCData -- End current CDATA
XMLWriter::endComment -- Create end comment
XMLWriter::endDocument -- End current document
XMLWriter::endDTDAttlist -- End current DTD AttList
XMLWriter::endDTDElement -- End current DTD element
XMLWriter::endDTDEntity -- End current DTD Entity
XMLWriter::endDTD -- End current DTD
XMLWriter::endElement -- End current element
XMLWriter::endPI -- End current PI
XMLWriter::flush -- Flush current buffer
XMLWriter::fullEndElement -- End current element
XMLWriter::openMemory -- Create new xmlwriter using memory for string output
XMLWriter::openURI -- Create new xmlwriter using source uri for output
XMLWriter::outputMemory -- Returns current buffer
XMLWriter::setIndentString -- Set string used for indenting
XMLWriter::setIndent -- Toggle indentation on/off
XMLWriter::startAttributeNS -- Create start namespaced attribute
XMLWriter::startAttribute -- Create start attribute
XMLWriter::startCData -- Create start CDATA tag
XMLWriter::startComment -- Create start comment
XMLWriter::startDocument -- Create document tag
XMLWriter::startDTDAttlist -- Create start DTD AttList
XMLWriter::startDTDElement -- Create start DTD element
XMLWriter::startDTDEntity -- Create start DTD Entity
XMLWriter::startDTD -- Create start DTD tag
XMLWriter::startElementNS -- Create start namespaced element tag
XMLWriter::startElement -- Create start element tag
XMLWriter::startPI -- Create start PI tag
XMLWriter::text -- Write text
XMLWriter::writeAttributeNS -- Write full namespaced attribute
XMLWriter::writeAttribute -- Write full attribute
XMLWriter::writeCData -- Write full CDATA tag
XMLWriter::writeComment -- Write full comment tag
XMLWriter::writeDTDAttlist -- Write full DTD AttList tag
XMLWriter::writeDTDElement -- Write full DTD element tag
XMLWriter::writeDTDEntity -- Write full DTD Entity tag
XMLWriter::writeDTD -- Write full DTD tag
XMLWriter::writeElementNS -- Write full namesapced element tag
XMLWriter::writeElement -- Write full element tag
XMLWriter::writePI -- Writes a PI
XMLWriter::writeRaw -- Write a raw XML text

Prev | Home | Next
XMLReader::XML | Up | XMLWriter::endAttribute


Runkit_Sandbox

(no version information, might be only in CVS)

Runkit_Sandbox -- Runkit Sandbox Class -- PHP Virtual Machine

Description

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Constructor

void Runkit_Sandbox::__construct ( [array options] )

options is an associative array containing any combination of the special ini options listed below.

safe_mode

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.

safe_mode_gid

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.

safe_mode_include_dir

If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.

open_basedir

open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.

allow_url_fopen

Like safe_mode, this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE

disable_functions

Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.

disable_classes

Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.

runkit.superglobal

Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Example 1. Instantiating a restricted sandbox

&#60;?php
$options = array(
  'safe_mode'=&#62;true,
  'open_basedir'=&#62;'/var/www/users/jdoe/',
  'allow_url_fopen'=&#62;'false',
  'disable_functions'=&#62;'exec,shell_exec,passthru,system',
  'disable_classes'=&#62;'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox-&#62;ini_set('html_errors',true);
?&#62;

Accessing Variables

All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.

Example 2. Working with variables in a sandbox

&#60;?php
$sandbox = new Runkit_Sandbox();

$sandbox-&#62;foo = 'bar';
$sandbox-&#62;eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox-&#62;bar}\n";
if (isset($sandbox-&#62;foo)) unset($sandbox-&#62;foo);
$sandbox-&#62;eval('var_dump(isset($foo));');
?&#62;

The above example will output:

bar
barbaz
bool(false)

Calling PHP Functions

Any function defined within the sandbox may be called as
a method on the sandbox object.  This also includes a few
pseudo-function language constructs:  eval(),
include(), include_once(),
require(), require_once(),
echo(), print(),
die(), and exit().

Example 3. Calling sandbox functions

&#60;?php
$sandbox = new Runkit_Sandbox();

echo $sandbox-&#62;str_replace('a','f','abc');
?&#62;

The above example will output:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Example 4. Passing arguments to sandbox functions

&#60;?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox-&#62;foo = 'baz';
echo $sandbox-&#62;str_replace('a',$foo,'a');
echo $sandbox-&#62;str_replace('a',$sandbox-&#62;foo,'a');
?&#62;

The above example will output:

bar
baz

Changing Sandbox Settings

As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.

Table 1. Sandbox Settings / Status Indicators

Setting | Type | Purpose | Default
active | Boolean (Read Only) | TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. | TRUE (Initial)
output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None
parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE
parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE
parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE
parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE
parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE
parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE
parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE
parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE
parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global)
parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |

Prev | Home | Next
runkit Functions | Up | Runkit_Sandbox_Parent


Runkit_Sandbox_Parent

(no version information, might be only in CVS)

Runkit_Sandbox_Parent -- Runkit Anti-Sandbox Class

Description

void Runkit_Sandbox_Parent::__construct ( void )

Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Example 1. Working with variables in a sandbox

&#60;?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?&#62;

Accessing the Parent's Variables

Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.

Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.

Example 2. Accessing parental variables

&#60;?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php-&#62;eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function one() {
    $test = "one()";
    two();
}

function two() {
    $test = "two()";
    three();
}

function three() {
    $test = "three()";
    $GLOBALS['php']-&#62;eval('var_dump($PARENT-&#62;test);');
}
?&#62;

The above example will output:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.

Prev | Home | Next
Runkit_Sandbox | Up | runkit_class_adopt


Streams Common API Reference

Table of Contents
php_stream_stat_path -- Gets the status for a file or URL
php_stream_stat -- Gets the status for the underlying storage associated with a stream
php_stream_open_wrapper -- Opens a stream on a file or URL
php_stream_read -- Read a number of bytes from a stream into a buffer
php_stream_write -- Write a number of bytes from a buffer to a stream
php_stream_eof -- Check for an end-of-file condition on a stream
php_stream_getc -- Read a single byte from a stream
php_stream_gets -- Read a line of data from a stream into a buffer
php_stream_close -- Close a stream
php_stream_flush -- Flush stream buffers to storage
php_stream_seek -- Reposition a stream
php_stream_tell -- Determine the position of a stream
php_stream_copy_to_stream -- Copy data from one stream to another
php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer
php_stream_make_seekable -- Convert a stream into a stream is seekable
php_stream_cast -- Convert a stream into another form, such as a FILE* or socket
php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket
php_stream_is_persistent -- Determines if a stream is a persistent stream
php_stream_is -- Determines if a stream is of a particular type
php_stream_passthru -- Outputs all remaining data from a stream
php_register_url_stream_wrapper -- Registers a wrapper with the Streams API
php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API
php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context
php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*
php_stream_filter_register_factory -- Registers a filter factory with the Streams API
php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

Prev | Home | Next
Streams as Resources | Up | php_stream_stat_path


Stream open options

Stream open options -- Affects the operation of stream factory functions

Description

One or more of these values can be combined using the OR operator.

IGNORE_PATH

This is the default option for streams; it requests that the include_path is not to be searched for the requested file.

USE_PATH

Requests that the include_path is to be searched for the requested file.

IGNORE_URL

Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.

IGNORE_URL_WIN

On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.

ENFORCE_SAFE_MODE

Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.

REPORT_ERRORS

If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.

STREAM_MUST_SEEK

This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

Note: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST

If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires.

The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream.

Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.

Prev | Home | Next
Streams Constants | Up | PDO Driver How-To


php_register_url_stream_wrapper

php_register_url_stream_wrapper -- Registers a wrapper with the Streams API

Description

int php_register_url_stream_wrapper ( char * protocol, php_stream_wrapper * wrapper, TSRMLS_DC )

php_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.

Note: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.

Prev | Home | Next
php_stream_passthru | Up | php_unregister_url_stream_wrapper


php_stream_can_cast

php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket

Description

int php_stream_can_cast ( php_stream * stream, int castas )

This function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.

Note: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.

Note: You must explicitly compare the return value of this function with one of the constants, as described in php_stream_cast().

See also php_stream_cast() and php_stream_is().

Prev | Home | Next
php_stream_cast | Up | php_stream_is_persistent


php_stream_cast

php_stream_cast -- Convert a stream into another form, such as a FILE* or socket

Description

int php_stream_cast ( php_stream * stream, int castas, void ** ret, int flags )

php_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.

Note: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.

Table 44-1. Resource types for castas

Value | Meaning
PHP_STREAM_AS_STDIO | Requests an ANSI FILE* that represents the stream
PHP_STREAM_AS_FD | Requests a POSIX file descriptor that represents the stream
PHP_STREAM_AS_SOCKETD | Requests a network socket descriptor that represents the stream

In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:

Table 44-2. Resource types for castas

Value | Meaning
PHP_STREAM_CAST_TRY_HARD | Tries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds
PHP_STREAM_CAST_RELEASE | Informs the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used.

Note: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desirable, you should query the stream to see if it naturally supports FILE* by using php_stream_is()

Note: If you ask a socket based stream for a FILE*, the streams API will use fdopen() to create it for you. Be warned that doing so may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls.

See also php_stream_is() and php_stream_can_cast().

Prev | Home | Next
php_stream_make_seekable | Up | php_stream_can_cast


php_stream_close

php_stream_close -- Close a stream

Description

int php_stream_close ( php_stream * stream )

php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.

php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.

Prev | Home | Next
php_stream_gets | Up | php_stream_flush


php_stream_closedir

php_stream_closedir -- Close a directory stream and release resources

Description

int php_stream_closedir ( php_stream * dirstream )

php_stream_closedir() closes a directory stream and releases resources associated with it. Returns 0 on success, but -1 on failure.

Prev | Home | Next
php_stream_rewinddir | Up | Streams File API Reference


php_stream_copy_to_mem

php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer

Description

size_t php_stream_copy_to_mem ( php_stream * src, char ** buf, size_t maxlen, int persistent )

php_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.

The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Note: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

Prev | Home | Next
php_stream_copy_to_stream | Up | php_stream_make_seekable


php_stream_copy_to_stream

php_stream_copy_to_stream -- Copy data from one stream to another

Description

size_t php_stream_copy_to_stream ( php_stream * src, php_stream * dest, size_t maxlen )

php_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Note: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

Prev | Home | Next
php_stream_tell | Up | php_stream_copy_to_mem


php_stream_eof

php_stream_eof -- Check for an end-of-file condition on a stream

Description

int php_stream_eof ( php_stream * stream )

php_stream_eof() checks for an end-of-file condition on stream.

php_stream_eof() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.

Prev | Home | Next
php_stream_write | Up | php_stream_getc


php_stream_filter_register_factory

php_stream_filter_register_factory -- Registers a filter factory with the Streams API

Description

int php_stream_filter_register_factory ( const char * filterpattern, php_stream_filter_factory * factory )

Use this function to register a filter factory with the name given by filterpattern. filterpattern can be either a normal string name (i.e. myfilter) or a global pattern (i.e. myfilterclass.*) to allow a single filter to perform different operations depending on the exact name of the filter invoked (i.e. myfilterclass.foo, myfilterclass.bar, etc...)

Note: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.

Prev | Home | Next
php_stream_open_wrapper_as_file | Up | php_stream_filter_unregister_factory


php_stream_filter_unregister_factory

php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

Description

int php_stream_filter_unregister_factory ( const char * filterpattern )

Deregisters the filterfactory specified by the filterpattern making it no longer available for use.

Note: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.

Prev | Home | Next
php_stream_filter_register_factory | Up | Streams Dir API Reference


php_stream_flush

php_stream_flush -- Flush stream buffers to storage

Description

int php_stream_flush ( php_stream * stream )

php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.

php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.

Prev | Home | Next
php_stream_close | Up | php_stream_seek


php_stream_fopen_from_file

php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream

Description

php_stream * php_stream_fopen_from_file ( FILE * file, char * mode )

php_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.

Prev | Home | Next
Streams File API Reference | Up | php_stream_fopen_tmpfile


php_stream_fopen_temporary_file

php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

Description

php_stream * php_stream_fopen_temporary_file ( const char * dir, const char * pfx, char ** opened )

php_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.

Prev | Home | Next
php_stream_fopen_tmpfile | Up | Streams Socket API Reference


php_stream_fopen_tmpfile

php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream

Description

php_stream * php_stream_fopen_tmpfile ( void )

php_stream_fopen_tmpfile() returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates.

Prev | Home | Next
php_stream_fopen_from_file | Up | php_stream_fopen_temporary_file


php_stream_getc

php_stream_getc -- Read a single byte from a stream

Description

int php_stream_getc ( php_stream * stream )

php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.

php_stream_getc() may block in the same way as php_stream_read() blocks.

The internal position of the stream is advanced by 1 if successful.

Prev | Home | Next
php_stream_eof | Up | php_stream_gets


php_stream_gets

php_stream_gets -- Read a line of data from a stream into a buffer

Description

char * php_stream_gets ( php_stream * stream, char * buf, size_t maxlen )

php_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.

php_stream_read() returns buf when successful or NULL otherwise.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

This function may block in the same way as php_stream_read().

Prev | Home | Next
php_stream_getc | Up | php_stream_close


php_stream_is

php_stream_is -- Determines if a stream is of a particular type

Description

int php_stream_is ( php_stream * stream, int istype )

php_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.

Table 44-1. Values for istype

Value | Meaning
PHP_STREAM_IS_STDIO | The stream is implemented using the stdio implementation
PHP_STREAM_IS_SOCKET | The stream is implemented using the network socket implementation
PHP_STREAM_IS_USERSPACE | The stream is implemented using the userspace object implementation
PHP_STREAM_IS_MEMORY | The stream is implemented using the grow-on-demand memory stream implementation

Note: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.

Note: This function is implemented as a simple (and fast) pointer comparison, and does not change the stream state in any way.

See also php_stream_cast() and php_stream_can_cast().

Prev | Home | Next
php_stream_is_persistent | Up | php_stream_passthru


php_stream_is_persistent

php_stream_is_persistent -- Determines if a stream is a persistent stream

Description

int php_stream_is_persistent ( php_stream * stream )

php_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.

Prev | Home | Next
php_stream_can_cast | Up | php_stream_is


php_stream_make_seekable

php_stream_make_seekable -- Convert a stream into a stream is seekable

Description

int php_stream_make_seekable ( php_stream * origstream, php_stream ** newstream, int flags )

php_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.

flags allows you to specify your preference for the seekable stream that is returned: use PHP_STREAM_NO_PREFERENCE to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use PHP_STREAM_PREFER_STDIO to use "regular" temporary file backed storage.

Table 44-1. php_stream_make_seekable() return values

Value | Meaning
PHP_STREAM_UNCHANGED | Original stream was seekable anyway. newstream is set to the value of origstream.
PHP_STREAM_RELEASED | Original stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore.
PHP_STREAM_FAILED | An error occurred while attempting conversion. newstream is set to NULL; origstream is still valid.
PHP_STREAM_CRITICAL | An error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream.

Note: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.

Note: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.

Note: If origstream is network based, this function will block until the whole contents have been downloaded.

Note: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!

Note: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.

Prev | Home | Next
php_stream_copy_to_mem | Up | php_stream_cast


php_stream_open_wrapper

php_stream_open_wrapper -- Opens a stream on a file or URL

Description

php_stream * php_stream_open_wrapper ( char * path, char * mode, int options, char ** opened )

php_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.

The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.

Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under Unix based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.

r

Open text file for reading. The stream is positioned at the beginning of the file.

r+

Open text file for reading and writing. The stream is positioned at the beginning of the file.

w

Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+

Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

a

Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

a+

Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.

options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.

If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.

Note: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.

Prev | Home | Next
php_stream_stat | Up | php_stream_read


php_stream_open_wrapper_as_file

php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*

Description

FILE * php_stream_open_wrapper_as_file ( char * path, char * mode, int options, char ** opened )

php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.

Prev | Home | Next
php_stream_open_wrapper_ex | Up | php_stream_filter_register_factory


php_stream_open_wrapper_ex

php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context

Description

php_stream * php_stream_open_wrapper_ex ( char * path, char * mode, int options, char ** opened, php_stream_context * context )

php_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see Stream Contexts.

Prev | Home | Next
php_unregister_url_stream_wrapper | Up | php_stream_open_wrapper_as_file


php_stream_opendir

php_stream_opendir -- Open a directory for file enumeration

Description

php_stream * php_stream_opendir ( char * path, php_stream_context * context )

php_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.

Prev | Home | Next
Streams Dir API Reference | Up | php_stream_readdir


php_stream_passthru

php_stream_passthru -- Outputs all remaining data from a stream

Description

size_t php_stream_passthru ( php_stream * stream )

php_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.

Prev | Home | Next
php_stream_is | Up | php_register_url_stream_wrapper


php_stream_read

php_stream_read -- Read a number of bytes from a stream into a buffer

Description

size_t php_stream_read ( php_stream * stream, char * buf, size_t count )

php_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.

php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.

Prev | Home | Next
php_stream_open_wrapper | Up | php_stream_write


php_stream_readdir

php_stream_readdir -- Fetch the next directory entry from an opened dir

Description

php_stream_dirent * php_stream_readdir ( php_stream * dirstream, php_stream_dirent * ent )

php_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL. See php_stream_dirent for more details about the information returned for each directory entry.

Prev | Home | Next
php_stream_opendir | Up | php_stream_rewinddir


php_stream_rewinddir

php_stream_rewinddir -- Rewind a directory stream to the first entry

Description

int php_stream_rewinddir ( php_stream * dirstream )

php_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.

Prev | Home | Next
php_stream_readdir | Up | php_stream_closedir


php_stream_seek

php_stream_seek -- Reposition a stream

Description

int php_stream_seek ( php_stream * stream, off_t offset, int whence )

php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.

php_stream_seek() returns 0 on success, but -1 if there was an error.

Note: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.

The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.

Prev | Home | Next
php_stream_flush | Up | php_stream_tell


php_stream_sock_open_from_socket

php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream

Description

php_stream * php_stream_sock_open_from_socket ( int socket, int persistent )

php_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

Prev | Home | Next
Streams Socket API Reference | Up | php_stream_sock_open_host


php_stream_sock_open_host

php_stream_sock_open_host -- Open a connection to a host and return a stream

Description

php_stream * php_stream_sock_open_host ( const char * host, unsigned short port, int socktype, struct timeval * timeout, int persistent )

php_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).

persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.

Note: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.

The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.

The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.

Prev | Home | Next
php_stream_sock_open_from_socket | Up | php_stream_sock_open_unix


php_stream_sock_open_unix

php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

Description

php_stream * php_stream_sock_open_unix ( const char * path, int pathlen, int persistent, struct timeval * timeout )

php_stream_sock_open_unix() attempts to open the Unix domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.

Note: This function will not work under Windows, which does not implement Unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.

Note: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.

Prev | Home | Next
php_stream_sock_open_host | Up | Streams Structures


php_stream_stat

php_stream_stat -- Gets the status for the underlying storage associated with a stream

Description

int php_stream_stat ( php_stream * stream, php_stream_statbuf * ssb )

php_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

Prev | Home | Next
php_stream_stat_path | Up | php_stream_open_wrapper


php_stream_stat_path

php_stream_stat_path -- Gets the status for a file or URL

Description

int php_stream_stat_path ( char * path, php_stream_statbuf * ssb )

php_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

Prev | Home | Next
Streams Common API Reference | Up | php_stream_stat


php_stream_tell

php_stream_tell -- Determine the position of a stream

Description

off_t php_stream_tell ( php_stream * stream )

php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.

Prev | Home | Next
php_stream_seek | Up | php_stream_copy_to_stream


php_stream_write

php_stream_write -- Write a number of bytes from a buffer to a stream

Description

size_t php_stream_write ( php_stream * stream, const char * buf, size_t count )

php_stream_write() writes count bytes of data from buf into stream.

php_stream_write() returns the number of bytes that were written successfully. If there was an error, the number of bytes written will be less than count.

The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point.

Prev | Home | Next
php_stream_read | Up | php_stream_eof


php_unregister_url_stream_wrapper

php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API

Description

int php_unregister_url_stream_wrapper ( char * protocol, TSRMLS_DC )

php_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.

Prev | Home | Next
php_register_url_stream_wrapper | Up | php_stream_open_wrapper_ex


struct php_stream_dirent

struct php_stream_dirent -- Holds information about a single file during dir scanning

Description

php_stream_dirent
     char d_name[MAXPATHLEN]

d_name holds the name of the file, relative to the directory being scanned.

Prev | Home | Next
struct php_stream_statbuf | Up | struct php_stream_ops


struct php_stream_filter

struct php_stream_filter -- Holds filter properties and pointer to operations

Description

struct _php_stream_filter {
            php_stream_filter_ops *fops;
            void *abstract; /* for use by filter implementation */
            php_stream_filter *next;
            php_stream_filter *prev;
            int is_persistent;

            /* link into stream and chain */
            php_stream_filter_chain *chain;

            /* buffered buckets */
            php_stream_bucket_brigade buffer;
        } php_stream_filter;

Prev | Home | Next
struct php_stream_wrapper_ops | Up | struct php_stream_filter_ops


struct php_stream_filter_ops

struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

Description

typedef struct _php_stream_filter_ops {
            php_stream_filter_status_t (*filter)(
                    php_stream *stream,
                    php_stream_filter *thisfilter,
                    php_stream_bucket_brigade *buckets_in,
                    php_stream_bucket_brigade *buckets_out,
                    size_t *bytes_consumed,
                    int flags
                    TSRMLS_DC);

            void (*dtor)(php_stream_filter *thisfilter TSRMLS_DC);

            const char *label;
} php_stream_filter_ops;

Prev | Home | Next
struct php_stream_filter | Up | Streams Constants


struct php_stream_ops

struct php_stream_ops -- Holds member functions for a stream implementation

Description

typedef struct _php_stream_ops {
             /* all streams MUST implement these operations */
             size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC);
             size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC);
             int (*close)(php_stream *stream, int close_handle TSRMLS_DC);
             int (*flush)(php_stream *stream TSRMLS_DC);

             const char *label; /* name describing this class of stream */

             /* these operations are optional, and may be set to NULL if the stream does not
              * support a particular operation */
            int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC);
            char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC);
            int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC);
            int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC);
        } php_stream_ops;

Prev | Home | Next
struct php_stream_dirent | Up | struct php_stream_wrapper


struct php_stream_statbuf

struct php_stream_statbuf -- Holds information about a file or URL

Description

php_stream_statbuf
     struct stat sb

sb is a regular, system defined, struct stat.

Prev | Home | Next
Streams Structures | Up | struct php_stream_dirent


struct php_stream_wrapper

struct php_stream_wrapper -- Holds wrapper properties and pointer to operations

Description

struct _php_stream_wrapper  {
            php_stream_wrapper_ops *wops;   /* operations the wrapper can perform */
            void *abstract;                 /* context for the wrapper */
            int is_url;                     /* so that PG(allow_url_fopen) can be respected */

            /* support for wrappers to return (multiple) error messages to the stream opener */
            int err_count;
            char **err_stack;
        } php_stream_wrapper;

Prev | Home | Next
struct php_stream_ops | Up | struct php_stream_wrapper_ops


struct php_stream_wrapper_ops

struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation

Description

typedef struct _php_stream_wrapper_ops {
            /* open/create a wrapped stream */
            php_stream *(*stream_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);
            /* close/destroy a wrapped stream */
            int (*stream_closer)(php_stream_wrapper *wrapper, php_stream *stream TSRMLS_DC);
            /* stat a wrapped stream */
            int (*stream_stat)(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb TSR$
            /* stat a URL */
            int (*url_stat)(php_stream_wrapper *wrapper, char *url, php_stream_statbuf *ssb TSRMLS_DC);
            /* open a "directory" stream */
            php_stream *(*dir_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);

            const char *label;

            /* Delete/Unlink a file */
            int (*unlink)(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC);
        } php_stream_wrapper_ops;

Prev | Home | Next
struct php_stream_wrapper | Up | struct php_stream_filter


List of Supported Timezones

PHP Manual
Prev Next

Appendix H. List of Supported Timezones

Table of Contents
List of timezones in the group Africa
List of timezones in the group America
List of timezones in the group Antarctica
List of timezones in the group Arctic
List of timezones in the group Asia
List of timezones in the group Atlantic
List of timezones in the group Australia
List of timezones in the group Europe
List of timezones in the group Indian
List of timezones in the group Pacific
List of timezones in the group Others

Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set().

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.

List of timezones in the group Africa

Table H-1. Africa

Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers | Africa/Asmera
Africa/Bamako | Africa/Bangui | Africa/Banjul | Africa/Bissau | Africa/Blantyre
Africa/Brazzaville | Africa/Bujumbura | Africa/Cairo | Africa/Casablanca | Africa/Ceuta
Africa/Conakry | Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti | Africa/Douala
Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare | Africa/Johannesburg
Africa/Kampala | Africa/Khartoum | Africa/Kigali | Africa/Kinshasa | Africa/Lagos
Africa/Libreville | Africa/Lome | Africa/Luanda | Africa/Lubumbashi | Africa/Lusaka
Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane | Africa/Mogadishu
Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena | Africa/Niamey | Africa/Nouakchott
Africa/Ouagadougou | Africa/Porto-Novo | Africa/Sao_Tome | Africa/Timbuktu | Africa/Tripoli
Africa/Tunis | Africa/Windhoek |  |  |

Prev | Home | Next
Description of core php.ini directives | Up | List of timezones in the group America


List of timezones in the group America

Table H-2. America

America/Adak | America/Anchorage | America/Anguilla | America/Antigua | America/Araguaina
America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/ComodRivadavia | America/Argentina/Cordoba | America/Argentina/Jujuy
America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos | America/Argentina/San_Juan | America/Argentina/Tucuman
America/Argentina/Ushuaia | America/Aruba | America/Asuncion | America/Atikokan | America/Atka
America/Bahia | America/Barbados | America/Belem | America/Belize | America/Blanc-Sablon
America/Boa_Vista | America/Bogota | America/Boise | America/Buenos_Aires | America/Cambridge_Bay
America/Campo_Grande | America/Cancun | America/Caracas | America/Catamarca | America/Cayenne
America/Cayman | America/Chicago | America/Chihuahua | America/Coral_Harbour | America/Cordoba
America/Costa_Rica | America/Cuiaba | America/Curacao | America/Danmarkshavn | America/Dawson
America/Dawson_Creek | America/Denver | America/Detroit | America/Dominica | America/Edmonton
America/Eirunepe | America/El_Salvador | America/Ensenada | America/Fort_Wayne | America/Fortaleza
America/Glace_Bay | America/Godthab | America/Goose_Bay | America/Grand_Turk | America/Grenada
America/Guadeloupe | America/Guatemala | America/Guayaquil | America/Guyana | America/Halifax
America/Havana | America/Hermosillo | America/Indiana/Indianapolis | America/Indiana/Knox | America/Indiana/Marengo
America/Indiana/Petersburg | America/Indiana/Vevay | America/Indiana/Vincennes | America/Indianapolis | America/Inuvik
America/Iqaluit | America/Jamaica | America/Jujuy | America/Juneau | America/Kentucky/Louisville
America/Kentucky/Monticello | America/Knox_IN | America/La_Paz | America/Lima | America/Los_Angeles
America/Louisville | America/Maceio | America/Managua | America/Manaus | America/Martinique
America/Mazatlan | America/Mendoza | America/Menominee | America/Merida | America/Mexico_City
America/Miquelon | America/Moncton | America/Monterrey | America/Montevideo | America/Montreal
America/Montserrat | America/Nassau | America/New_York | America/Nipigon | America/Nome
America/Noronha | America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Panama | America/Pangnirtung
America/Paramaribo | America/Phoenix | America/Port-au-Prince | America/Port_of_Spain | America/Porto_Acre
America/Porto_Velho | America/Puerto_Rico | America/Rainy_River | America/Rankin_Inlet | America/Recife
America/Regina | America/Rio_Branco | America/Rosario | America/Santiago | America/Santo_Domingo
America/Sao_Paulo | America/Scoresbysund | America/Shiprock | America/St_Johns | America/St_Kitts
America/St_Lucia | America/St_Thomas | America/St_Vincent | America/Swift_Current | America/Tegucigalpa
America/Thule | America/Thunder_Bay | America/Tijuana | America/Toronto | America/Tortola
America/Vancouver | America/Virgin | America/Whitehorse | America/Winnipeg | America/Yakutat
America/Yellowknife |  |  |  |

Prev | Home | Next
List of Supported Timezones | Up | List of timezones in the group Antarctica


List of timezones in the group Antarctica

Table H-3. Antarctica

Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Mawson | Antarctica/McMurdo
Antarctica/Palmer | Antarctica/Rothera | Antarctica/South_Pole | Antarctica/Syowa | Antarctica/Vostok

Prev | Home | Next
List of timezones in the group America | Up | List of timezones in the group Arctic


List of timezones in the group Arctic

Table H-4. Arctic

Arctic/Longyearbyen

Prev | Home | Next
List of timezones in the group Antarctica | Up | List of timezones in the group Asia


List of timezones in the group Asia

Table H-5. Asia

Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr | Asia/Aqtau
Asia/Aqtobe | Asia/Ashgabat | Asia/Ashkhabad | Asia/Baghdad | Asia/Bahrain
Asia/Baku | Asia/Bangkok | Asia/Beirut | Asia/Bishkek | Asia/Brunei
Asia/Calcutta | Asia/Choibalsan | Asia/Chongqing | Asia/Chungking | Asia/Colombo
Asia/Dacca | Asia/Damascus | Asia/Dhaka | Asia/Dili | Asia/Dubai
Asia/Dushanbe | Asia/Gaza | Asia/Harbin | Asia/Hong_Kong | Asia/Hovd
Asia/Irkutsk | Asia/Istanbul | Asia/Jakarta | Asia/Jayapura | Asia/Jerusalem
Asia/Kabul | Asia/Kamchatka | Asia/Karachi | Asia/Kashgar | Asia/Katmandu
Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait | Asia/Macao
Asia/Macau | Asia/Magadan | Asia/Makassar | Asia/Manila | Asia/Muscat
Asia/Nicosia | Asia/Novosibirsk | Asia/Omsk | Asia/Oral | Asia/Phnom_Penh
Asia/Pontianak | Asia/Pyongyang | Asia/Qatar | Asia/Qyzylorda | Asia/Rangoon
Asia/Riyadh | Asia/Saigon | Asia/Sakhalin | Asia/Samarkand | Asia/Seoul
Asia/Shanghai | Asia/Singapore | Asia/Taipei | Asia/Tashkent | Asia/Tbilisi
Asia/Tehran | Asia/Tel_Aviv | Asia/Thimbu | Asia/Thimphu | Asia/Tokyo
Asia/Ujung_Pandang | Asia/Ulaanbaatar | Asia/Ulan_Bator | Asia/Urumqi | Asia/Vientiane
Asia/Vladivostok | Asia/Yakutsk | Asia/Yekaterinburg | Asia/Yerevan |

Prev | Home | Next
List of timezones in the group Arctic | Up | List of timezones in the group Atlantic


List of timezones in the group Atlantic

Table H-6. Atlantic

Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde | Atlantic/Faeroe
Atlantic/Jan_Mayen | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia | Atlantic/St_Helena
Atlantic/Stanley |  |  |  |

Prev | Home | Next
List of timezones in the group Asia | Up | List of timezones in the group Australia


List of timezones in the group Australia

Table H-7. Australia

Australia/ACT | Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Canberra
Australia/Currie | Australia/Darwin | Australia/Hobart | Australia/LHI | Australia/Lindeman
Australia/Lord_Howe | Australia/Melbourne | Australia/North | Australia/NSW | Australia/Perth
Australia/Queensland | Australia/South | Australia/Sydney | Australia/Tasmania | Australia/Victoria
Australia/West | Australia/Yancowinna |  |  |

Prev | Home | Next
List of timezones in the group Atlantic | Up | List of timezones in the group Europe


List of timezones in the group Europe

Table H-8. Europe

Europe/Amsterdam | Europe/Andorra | Europe/Athens | Europe/Belfast | Europe/Belgrade
Europe/Berlin | Europe/Bratislava | Europe/Brussels | Europe/Bucharest | Europe/Budapest
Europe/Chisinau | Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey
Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey | Europe/Kaliningrad
Europe/Kiev | Europe/Lisbon | Europe/Ljubljana | Europe/London | Europe/Luxembourg
Europe/Madrid | Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Nicosia | Europe/Oslo | Europe/Paris | Europe/Prague
Europe/Riga | Europe/Rome | Europe/Samara | Europe/San_Marino | Europe/Sarajevo
Europe/Simferopol | Europe/Skopje | Europe/Sofia | Europe/Stockholm | Europe/Tallinn
Europe/Tirane | Europe/Tiraspol | Europe/Uzhgorod | Europe/Vaduz | Europe/Vatican
Europe/Vienna | Europe/Vilnius | Europe/Volgograd | Europe/Warsaw | Europe/Zagreb
Europe/Zaporozhye | Europe/Zurich |  |  |

Prev | Home | Next
List of timezones in the group Australia | Up | List of timezones in the group Indian


List of timezones in the group Indian

Table H-9. Indian

Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos | Indian/Comoro
Indian/Kerguelen | Indian/Mahe | Indian/Maldives | Indian/Mauritius | Indian/Mayotte
Indian/Reunion |  |  |  |

Prev | Home | Next
List of timezones in the group Europe | Up | List of timezones in the group Pacific


List of timezones in the group Others

Table H-11. Others

Brazil/Acre | Brazil/DeNoronha | Brazil/East | Brazil/West | Canada/Atlantic
Canada/Central | Canada/East-Saskatchewan | Canada/Eastern | Canada/Mountain | Canada/Newfoundland
Canada/Pacific | Canada/Saskatchewan | Canada/Yukon | CET | Chile/Continental
Chile/EasterIsland | CST6CDT | Cuba | EET | Egypt
Eire | EST | EST5EDT | Etc/GMT | Etc/GMT+0
Etc/GMT+1 | Etc/GMT+10 | Etc/GMT+11 | Etc/GMT+12 | Etc/GMT+2
Etc/GMT+3 | Etc/GMT+4 | Etc/GMT+5 | Etc/GMT+6 | Etc/GMT+7
Etc/GMT+8 | Etc/GMT+9 | Etc/GMT-0 | Etc/GMT-1 | Etc/GMT-10
Etc/GMT-11 | Etc/GMT-12 | Etc/GMT-13 | Etc/GMT-14 | Etc/GMT-2
Etc/GMT-3 | Etc/GMT-4 | Etc/GMT-5 | Etc/GMT-6 | Etc/GMT-7
Etc/GMT-8 | Etc/GMT-9 | Etc/GMT0 | Etc/Greenwich | Etc/UCT
Etc/Universal | Etc/UTC | Etc/Zulu | Factory | GB
GB-Eire | GMT | GMT+0 | GMT-0 | GMT0
Greenwich | Hongkong | HST | Iceland | Iran
Israel | Jamaica | Japan | Kwajalein | Libya
MET | Mexico/BajaNorte | Mexico/BajaSur | Mexico/General | MST
MST7MDT | Navajo | NZ | NZ-CHAT | Poland
Portugal | PRC | PST8PDT | ROC | ROK
Singapore | Turkey | UCT | Universal | US/Alaska
US/Aleutian | US/Arizona | US/Central | US/East-Indiana | US/Eastern
US/Hawaii | US/Indiana-Starke | US/Michigan | US/Mountain | US/Pacific
US/Pacific-New | US/Samoa | UTC | W-SU | WET
Zulu |  |  |  |

Note: Please do not use any of the timezones listed here, they only exist for backward compatible reasons.

Prev | Home | Next
List of timezones in the group Pacific | Up | Extension Categorization


List of timezones in the group Pacific

Table H-10. Pacific

Pacific/Apia | Pacific/Auckland | Pacific/Chatham | Pacific/Easter | Pacific/Efate
Pacific/Enderbury | Pacific/Fakaofo | Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos
Pacific/Gambier | Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu | Pacific/Johnston
Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro | Pacific/Marquesas
Pacific/Midway | Pacific/Nauru | Pacific/Niue | Pacific/Norfolk | Pacific/Noumea
Pacific/Pago_Pago | Pacific/Palau | Pacific/Pitcairn | Pacific/Ponape | Pacific/Port_Moresby
Pacific/Rarotonga | Pacific/Saipan | Pacific/Samoa | Pacific/Tahiti | Pacific/Tarawa
Pacific/Tongatapu | Pacific/Truk | Pacific/Wake | Pacific/Wallis | Pacific/Yap

Prev | Home | Next
List of timezones in the group Indian | Up | List of timezones in the group Others


TSRM API

PHP Manual
Prev Next

Chapter 47. TSRM API

Table of Contents
API Function and Macro reference (work in progress)

API Function and Macro reference (work in progress)

Table of Contents
ts_allocate_id -- ...
ts_free_id -- ...
ts_free_thread -- ...
ts_resource_ex -- ...
ts_resource -- ...
tsrm_error_set -- ...
tsrm_error -- ...
tsrm_free_interpreter_context -- ...
tsrm_mutex_alloc -- ...
tsrm_mutex_free -- ...
tsrm_mutex_lock -- ...
tsrm_mutex_unlock -- ...
tsrm_new_interpreter_context -- ...
tsrm_set_interpreter_context -- ...
tsrm_set_new_thread_begin_handler -- ...
tsrm_set_new_thread_end_handler -- ...
tsrm_shutdown -- ...
tsrm_startup -- ...
tsrm_thread_id -- ...
virtual_access -- Check users permissions for a file
virtual_chdir_file -- ...
virtual_chdir -- ...
virtual_chmod -- ...
virtual_chown -- ...
virtual_creat -- ...
virtual_cwd_shutdown -- ...
virtual_cwd_startup -- ...
virtual_file_ex -- ...
virtual_filepath_ex -- ...
virtual_filepath -- ...
virtual_fopen -- ...
virtual_getcwd_ex -- ...
virtual_getcwd -- ...
virtual_lstat -- ...
virtual_mkdir -- ...
virtual_open -- ...
virtual_opendir -- ...
virtual_popen -- ...
virtual_realpath -- ...
virtual_rename -- ...
virtual_rmdir -- ...
virtual_stat -- ...
virtual_unlink -- ...
virtual_utime -- ...
VCWD_ACCESS -- Check users permissions for a file
VCWD_CHDIR_FILE -- ...
VCWD_CHDIR -- ...
VCWD_CHMOD -- ...
VCWD_CHOWN -- ...
VCWD_CREAT -- ...
VCWD_FOPEN -- ...
VCWD_GETCWD -- ...
VCWD_GETWD -- ...
VCWD_LCHOWN -- ...
VCWD_LSTAT -- ...
VCWD_MKDIR -- ...
VCWD_OPEN_MODE -- ...
VCWD_OPEN -- ...
VCWD_OPENDIR -- ...
VCWD_POPEN -- ...
VCWD_REALPATH -- ...
VCWD_RENAME -- ...
VCWD_RMDIR -- ...
VCWD_STAT -- ...
VCWD_UNLINK -- ...
VCWD_UTIME -- ...

Prev | Home | Next
ZEND_WRONG_PARAM_COUNT | Up | ts_allocate_id


Userland Naming Guide

PHP Manual
Prev Next

Appendix R. Userland Naming Guide

Table of Contents
Global Namespace
Rules
Tips

The following is a guide for how to best choose names for identifiers in userland PHP code. When choosing names for any code that creates symbols in the global namespace, it is important to take into account the following guidelines to prevent future versions of PHP from clashing with your symbols.

Global Namespace

Here is an overview of code constructs that go into the global namespace:

  • functions

  • classes

  • interfaces

  • constants (not class constants)

  • variables defined outside of functions/methods

Prev | Home | Next
List of Parser Tokens | Up | Rules


Rules

The following list gives an overview of which rights the PHP project reserves for itself, when choosing names for new internal identifiers. The definitive guide is the official CODING STANDARDS:

  • PHP owns the top-level namespace but tries to find decent descriptive names and avoid any obvious clashes.

  • Function names use underscores between words, while class names use the lower bumpy camel rule (there are some exceptions for older classes and functions).

  • PHP will prefix any global symbols of an extension with the name of the extension. (In the past, there have been numerous exceptions to this rule.) Examples:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (example of a past mistake)

    • new SplFileObject()

  • Iterators and Exceptions are however simply postfixed with "Iterator" and "Exception." Examples:

    • ArrayIterator

    • LogicException

  • PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality. Examples:

    • __get()

    • __autoload()

Prev | Home | Next
Userland Naming Guide | Up | Tips


Tips

In order to write future-proof code, it is recommended that you prefix (or suffix) anything that goes into the global namespace with an uncommon 3-4 letter prefix (or suffix) separated with an underscore. It is recommended that in order to prevent namespace clashes with other userland code that projects research existing prefixes (or suffixes) used in other projects and advertise their chosen prefix (or suffix) appropriately. Examples:

  • MyPx_someFunc()

  • Foo_Date

  • $asdf_dbh

Prev | Home | Next
Rules | Up | About the manual


Data (RFC 2397)

The data: (RFC 2397) stream wrapper is available since PHP 5.2.0.

Example M-4. Print data:// contents

&#60;?php
// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?&#62;

Example M-5. Fetch the media type

&#60;?php
$fp   = fopen('data://text/plain;base64,', 'r');
$meta = stream_get_meta_data($fp);

// prints "text/plain"
echo $meta['mediatype'];
?&#62;

Table M-8. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | No
Restricted by allow_url_include | Yes
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Prev | Home | Next
Compression Streams | Up | Secure Shell 2


Process Interaction Streams

expect:// PHP 4.3.0 and up (PECL)

  • expect://command

This wrapper is not enabled by default: In order to use the expect:// wrapper you must install the Expect extension available from PECL.

Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.

Table M-13. Wrapper Summary

Attribute | Supported
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Prev | Home | Next
Audio Streams | Up | List of Available Filters


Socket

This section contains the context options supported by the wrappers that work over sockets, like tcp, http or ftp.

As of PHP 5.1.0 only one option is supported, bindto, which can be used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port (you can set the IP or the port number to 0 if you want to let the system choose them for you).

Note: As FTP creates two socket connections during normal operation, you cannot specify the port number in the bindto option. So, the only supported syntax is ip:0 for the FTP wrapper.

Example M-1. Some examples of how to use the bindto option

&#60;?php
// connect to the internet using the '192.168.0.100' IP
$opts = array('socket' =&#62;
            array('bindto' =&#62; '192.168.0.100:0'));

// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array('socket' =&#62;
            array('bindto' =&#62; '192.168.0.100:7000'));

// connect to the internet using port '7000'
$opts = array('socket' =&#62;
            array('bindto' =&#62; '0:7000'));

// create the context...
$context = stream_context_create($opts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);

?&#62;

Prev | Home | Next
List of Supported Protocols/Wrappers | Up | HTTP and HTTPS


ZEND_WRONG_PARAM_COUNT_WITH_RETVAL

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL -- Generate standard error message and return custom value

Description

#include <zend_API.h>

#include <zend_API.h>

void ZEND_WRONG_PARAM_COUNT_WITH_RETVAL ( mixed return_value )

Note: This macro is part of the API but not used in any bundled or PECL extension

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters and returns its parameter to the calling function. The macro automaticly puts the right function name and class name (if needed) into the error message.

The return_value parameter is returned to the calling function of the current one.

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() is actually a convenience wrapper for zend_wrong_param_count().

Prev | Home | Next
ZEND_WRITE | Up | ZEND_WRONG_PARAM_COUNT


add_assoc_bool

add_assoc_bool -- Add a bool value to an assoc array

Description

#include <zend_API.h>

int add_assoc_bool ( zval* arg, char* key, int b )

...

Parameters

arg

...

key

...

b

...

Return Values

...

Prev | Home | Next
add_assoc_bool_ex | Up | add_assoc_double_ex


add_assoc_bool_ex

add_assoc_bool_ex -- Add a bool value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_bool_ex ( zval* arg, char* key, uint key_len, int b )

...

Parameters

arg

...

key

...

key_len

...

b

...

Return Values

...

Prev | Home | Next
API Function and Macro reference (work in progress) | Up | add_assoc_bool


add_assoc_double

add_assoc_double -- Add a double value to an assoc array

Description

#include <zend_API.h>

int add_assoc_double ( zval* arg, char* key, double d )

...

Parameters

arg

...

key

...

d

...

Return Values

...

Prev | Home | Next
add_assoc_double_ex | Up | add_assoc_function


add_assoc_double_ex

add_assoc_double_ex -- Add a double value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_double_ex ( zval* arg, char* key, uint key_len, double d )

...

Parameters

arg

...

key

...

key_len

...

d

...

Return Values

...

Prev | Home | Next
add_assoc_bool | Up | add_assoc_double


add_assoc_function

add_assoc_function -- Add a function pointer to an assoc array

Description

#include <zend_API.h>

int add_assoc_function ( zval* arg, char* key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS) )

...

Parameters

arg

...

key

...

(*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)

...

Return Values

...

Prev | Home | Next
add_assoc_double | Up | add_assoc_long_ex


add_assoc_long

add_assoc_long -- Add a long value to an assoc array

Description

#include <zend_API.h>

int add_assoc_long ( zval* arg, char* key, long n )

...

Parameters

arg

...

key

...

n

...

Return Values

...

Prev | Home | Next
add_assoc_long_ex | Up | add_assoc_null_ex


add_assoc_long_ex

add_assoc_long_ex -- Add a long value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_long_ex ( zval* arg, char* key, uint key_len, long n )

...

Parameters

arg

...

key

...

key_len

...

n

...

Return Values

...

Prev | Home | Next
add_assoc_function | Up | add_assoc_long


add_assoc_null

add_assoc_null -- Add a null value to an assoc array

Description

#include <zend_API.h>

int add_assoc_null ( zval* arg, char* key )

...

Parameters

arg

...

key

...

Return Values

...

Prev | Home | Next
add_assoc_null_ex | Up | add_assoc_resource_ex


add_assoc_null_ex

add_assoc_null_ex -- Add a null value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_null_ex ( zval* arg, char* key, uint key_len )

...

Parameters

arg

...

key

...

key_len

...

Return Values

...

Prev | Home | Next
add_assoc_long | Up | add_assoc_null


add_assoc_resource

add_assoc_resource -- Add a resource value to an assoc array

Description

#include <zend_API.h>

int add_assoc_resource ( zval* arg, char* key, int r )

...

Parameters

arg

...

key

...

r

...

Return Values

...

Prev | Home | Next
add_assoc_resource_ex | Up | add_assoc_string_ex


add_assoc_resource_ex

add_assoc_resource_ex -- Add a resource value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_resource_ex ( zval* arg, char* key, uint key_len, int r )

...

Parameters

arg

...

key

...

key_len

...

r

...

Return Values

...

Prev | Home | Next
add_assoc_null | Up | add_assoc_resource


add_assoc_string

add_assoc_string -- Add a string value to an assoc array

Description

#include <zend_API.h>

int add_assoc_string ( zval* arg, char* key, char* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_string_ex | Up | add_assoc_stringl_ex


add_assoc_string_ex

add_assoc_string_ex -- Add a string value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_resource | Up | add_assoc_string


add_assoc_stringl

add_assoc_stringl -- Add a binary safe string value to an assoc array

Description

#include <zend_API.h>

int add_assoc_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_stringl_ex | Up | add_assoc_unicode_ex


add_assoc_stringl_ex

add_assoc_stringl_ex -- Add a binary safe string value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_string | Up | add_assoc_stringl


add_assoc_unicode

add_assoc_unicode -- Add a binary safe unicode_string value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_unicode ( zval* arg, char* key, void* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_unicode_ex | Up | add_assoc_unicodel_ex


add_assoc_unicode_ex

add_assoc_unicode_ex -- Add a unicode_string value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_unicode_ex ( zval* arg, char* key, uint key_len, void* str, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_stringl | Up | add_assoc_unicode


add_assoc_unicodel

add_assoc_unicodel -- Add a binary safe unicode_string value to an assoc array

Description

#include <zend_API.h>

int add_assoc_unicodel ( zval* arg, char* key, void* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_unicodel_ex | Up | add_assoc_unset


add_assoc_unicodel_ex

add_assoc_unicodel_ex -- Add a binary safe unicode_string value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_unicodel_ex ( zval* arg, char* key, uint key_len, void* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_unicode | Up | add_assoc_unicodel


add_assoc_unset

add_assoc_unset -- ...

Description

#include <zend_API.h>

int add_assoc_unset ( zval* arg, char* key )

...

Parameters

arg

...

key

...

Return Values

...

Prev | Home | Next
add_assoc_unicodel | Up | add_assoc_zval_ex


add_assoc_zval

add_assoc_zval -- Add a zval value to an assoc array

Description

#include <zend_API.h>

int add_assoc_zval ( zval* arg, char* key, zval* value )

...

Parameters

arg

...

key

...

value

...

Return Values

...

Prev | Home | Next
add_assoc_zval_ex | Up | add_get_assoc_string_ex


add_assoc_zval_ex

add_assoc_zval_ex -- Add a zval value to an assoc array with binary safe key

Description

#include <zend_API.h>

int add_assoc_zval_ex ( zval* arg, char* key, uint key_len, zval* value )

...

Parameters

arg

...

key

...

key_len

...

value

...

Return Values

...

Prev | Home | Next
add_assoc_unset | Up | add_assoc_zval


add_get_assoc_string

add_get_assoc_string -- ...

Description

#include <zend_API.h>

int add_get_assoc_string ( zval* arg, char* key, char* str, void** dest, int duplicate )

...

Parameters

arg

...

key

...

str

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_assoc_string_ex | Up | add_get_assoc_stringl_ex


add_get_assoc_string_ex

add_get_assoc_string_ex -- ...

Description

#include <zend_API.h>

int add_get_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, void** dest, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_assoc_zval | Up | add_get_assoc_string


add_get_assoc_stringl

add_get_assoc_stringl -- ...

Description

#include <zend_API.h>

int add_get_assoc_stringl ( zval* arg, char* key, char* str, uint length, void** dest, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_assoc_stringl_ex | Up | add_get_index_binary


add_get_assoc_stringl_ex

add_get_assoc_stringl_ex -- ...

Description

#include <zend_API.h>

int add_get_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, void** dest, int duplicate )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_assoc_string | Up | add_get_assoc_stringl


add_get_index_binary

add_get_index_binary -- ...

Description

#include <zend_API.h>

int add_get_index_binary ( zval* arg, ulong idx, char* str, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_assoc_stringl | Up | add_get_index_binaryl


add_get_index_binaryl

add_get_index_binaryl -- ...

Description

#include <zend_API.h>

int add_get_index_binaryl ( zval* arg, ulong idx, char* str, uint length, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

length

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_index_binary | Up | add_get_index_double


add_get_index_double

add_get_index_double -- ...

Description

#include <zend_API.h>

int add_get_index_double ( zval* arg, ulong idx, double d, void** dest )

...

Parameters

arg

...

idx

...

d

...

dest

...

Return Values

...

Prev | Home | Next
add_get_index_binaryl | Up | add_get_index_long


add_get_index_long

add_get_index_long -- ...

Description

#include <zend_API.h>

int add_get_index_long ( zval* arg, ulong idx, long l, void** dest )

...

Parameters

arg

...

idx

...

l

...

dest

...

Return Values

...

Prev | Home | Next
add_get_index_double | Up | add_get_index_string


add_get_index_string

add_get_index_string -- ...

Description

#include <zend_API.h>

int add_get_index_string ( zval* arg, ulong idx, char* str, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_index_long | Up | add_get_index_stringl


add_get_index_stringl

add_get_index_stringl -- ...

Description

#include <zend_API.h>

int add_get_index_stringl ( zval* arg, ulong idx, char* str, uint length, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

length

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_index_string | Up | add_get_index_unicode


add_get_index_unicode

add_get_index_unicode -- ...

Description

#include <zend_API.h>

int add_get_index_unicode ( zval* arg, ulong idx, UChar* str, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_index_stringl | Up | add_get_index_unicodel


add_get_index_unicodel

add_get_index_unicodel -- ...

Description

#include <zend_API.h>

int add_get_index_unicodel ( zval* arg, ulong idx, UChar* str, uint length, void** dest, int duplicate )

...

Parameters

arg

...

idx

...

str

...

length

...

dest

...

duplicate

...

Return Values

...

Prev | Home | Next
add_get_index_unicode | Up | add_index_binary


add_index_binary

add_index_binary -- Add binary_string value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_binary ( zval* arg, ulong idx, char* str, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

idx

...

str

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_get_index_unicodel | Up | add_index_binaryl


add_index_binaryl

add_index_binaryl -- Add binary safe binary_string value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_binaryl ( zval* arg, ulong idx, char* str, uint length, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

idx

...

str

...

length

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_index_binary | Up | add_index_bool


add_index_bool

add_index_bool -- Add bool value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_bool ( zval* arg, ulong idx, int b )

...

Parameters

arg

...

idx

...

b

...

Return Values

...

Prev | Home | Next
add_index_binaryl | Up | add_index_double


add_index_double

add_index_double -- Add double value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_double ( zval* arg, ulong idx, double d )

...

Parameters

arg

...

idx

...

d

...

Return Values

...

Prev | Home | Next
add_index_bool | Up | add_index_long


add_index_long

add_index_long -- Add long value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_long ( zval* arg, ulong idx, long n )

...

Parameters

arg

...

idx

...

n

...

Return Values

...

Prev | Home | Next
add_index_double | Up | add_index_null


add_index_null

add_index_null -- Add null value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_null ( zval* arg, ulong idx )

...

Parameters

arg

...

idx

...

Return Values

...

Prev | Home | Next
add_index_long | Up | add_index_resource


add_index_resource

add_index_resource -- Add resource value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_resource ( zval* arg, ulong idx, int r )

...

Parameters

arg

...

idx

...

r

...

Return Values

...

Prev | Home | Next
add_index_null | Up | add_index_string


add_index_string

add_index_string -- Add string value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_string ( zval* arg, ulong idx, char* str, int duplicate )

...

Parameters

arg

...

idx

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_index_resource | Up | add_index_stringl


add_index_stringl

add_index_stringl -- Add binary safe string value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_stringl ( zval* arg, ulong idx, char* str, uint length, int duplicate )

...

Parameters

arg

...

idx

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_index_string | Up | add_index_unicode


add_index_unicode

add_index_unicode -- Add unicode value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_unicode ( zval* arg, ulong idx, UChar* str, int duplicate )

...

Parameters

arg

...

idx

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_index_stringl | Up | add_index_unicodel


add_index_unicodel

add_index_unicodel -- Add binary safe unicode value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_unicodel ( zval* arg, ulong idx, UChar* str, uint length, int duplicate )

...

Parameters

arg

...

idx

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_index_unicode | Up | add_index_unset


add_index_unset

add_index_unset -- Add unset value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_unset ( zval* arg, ... key )

...

Parameters

arg

...

key

...

Return Values

...

Prev | Home | Next
add_index_unicodel | Up | add_index_zval


add_index_zval

add_index_zval -- Add zval value to assoc array using numeric index

Description

#include <zend_API.h>

int add_index_zval ( zval* arg, ulong index, zval* value )

...

Parameters

arg

...

index

...

value

...

Return Values

...

Prev | Home | Next
add_index_unset | Up | add_method


add_method

add_method -- ...

Description

#include <zend_API.h>

int add_method ( zval* arg, char* key, ... method )

...

Parameters

arg

...

key

...

method

...

Return Values

...

Prev | Home | Next
add_index_zval | Up | add_next_index_binary


add_next_index_binary

add_next_index_binary -- Add binary_string value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_binary ( zval* arg, char* str, int duplicate )

...

Parameters

arg

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_method | Up | add_next_index_binaryl


add_next_index_binaryl

add_next_index_binaryl -- Add binary safe binary_string value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_binaryl ( zval* arg, char* str, uint length, int duplicate )

...

Parameters

arg

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_next_index_binary | Up | add_next_index_bool


add_next_index_bool

add_next_index_bool -- Add bool value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_bool ( zval* arg, int b )

...

Parameters

arg

...

b

...

Return Values

...

Prev | Home | Next
add_next_index_binaryl | Up | add_next_index_double


add_next_index_double

add_next_index_double -- Add double value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_double ( zval* arg, double d )

...

Parameters

arg

...

d

...

Return Values

...

Prev | Home | Next
add_next_index_bool | Up | add_next_index_long


add_next_index_long

add_next_index_long -- Add long value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_long ( zval* arg, long n )

...

Parameters

arg

...

n

...

Return Values

...

Prev | Home | Next
add_next_index_double | Up | add_next_index_null


add_next_index_null

add_next_index_null -- Add null value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_null ( zval* arg )

...

Parameters

arg

...

Return Values

...

Prev | Home | Next
add_next_index_long | Up | add_next_index_resource


add_next_index_resource

add_next_index_resource -- Add resource value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_resource ( zval* arg, int r )

...

Parameters

arg

...

r

...

Return Values

...

Prev | Home | Next
add_next_index_null | Up | add_next_index_string


add_next_index_string

add_next_index_string -- Add string value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_string ( zval* arg, char* str, int duplicate )

...

Parameters

arg

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_next_index_resource | Up | add_next_index_stringl


add_next_index_stringl

add_next_index_stringl -- Add binary safe string value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_stringl ( zval* arg, char* str, uint length, int duplicate )

...

Parameters

arg

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_next_index_string | Up | add_next_index_unicode


add_next_index_unicode

add_next_index_unicode -- Add unicode value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_unicode ( zval* arg, UChar* str, int duplicate )

...

Parameters

arg

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_next_index_stringl | Up | add_next_index_unicodel


add_next_index_unicodel

add_next_index_unicodel -- Add binary safe unicode value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_unicodel ( zval* arg, UChar* str, uint length, int duplicate )

...

Parameters

arg

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_next_index_unicode | Up | add_next_index_unset


add_next_index_unset

add_next_index_unset -- Add unset value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_unset ( zval* arg )

...

Parameters

arg

...

Return Values

...

Prev | Home | Next
add_next_index_unicodel | Up | add_next_index_zval


add_next_index_zval

add_next_index_zval -- Add zval value to assoc array using next free numeric index

Description

#include <zend_API.h>

int add_next_index_zval ( zval* arg, zval* value )

...

Parameters

arg

...

value

...

Return Values

...

Prev | Home | Next
add_next_index_unset | Up | add_property_ascii_string_ex


add_property_ascii_string

add_property_ascii_string -- ...

Description

#include <zend_API.h>

int add_property_ascii_string ( zval* arg, char* key, char* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_ascii_string_ex | Up | add_property_ascii_stringl_ex


add_property_ascii_string_ex

add_property_ascii_string_ex -- ...

Description

#include <zend_API.h>

int add_property_ascii_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_next_index_zval | Up | add_property_ascii_string


add_property_ascii_stringl

add_property_ascii_stringl -- ...

Description

#include <zend_API.h>

int add_property_ascii_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_ascii_stringl_ex | Up | add_property_bool_ex


add_property_ascii_stringl_ex

add_property_ascii_stringl_ex -- ...

Description

#include <zend_API.h>

int add_property_ascii_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_ascii_string | Up | add_property_ascii_stringl


add_property_bool

add_property_bool -- ...

Description

#include <zend_API.h>

int add_property_bool ( zval* arg, char* key, int b )

...

Parameters

arg

...

key

...

b

...

Return Values

...

Prev | Home | Next
add_property_bool_ex | Up | add_property_double_ex


add_property_bool_ex

add_property_bool_ex -- ...

Description

#include <zend_API.h>

int add_property_bool_ex ( zval* arg, char* key, uint key_len, int b, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

b

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_ascii_stringl | Up | add_property_bool


add_property_double

add_property_double -- ...

Description

#include <zend_API.h>

int add_property_double ( zval* arg, char* key, double d )

...

Parameters

arg

...

key

...

d

...

Return Values

...

Prev | Home | Next
add_property_double_ex | Up | add_property_long_ex


add_property_double_ex

add_property_double_ex -- ...

Description

#include <zend_API.h>

int add_property_double_ex ( zval* arg, char* key, uint key_len, double d, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

d

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_bool | Up | add_property_double


add_property_long

add_property_long -- ...

Description

#include <zend_API.h>

int add_property_long ( zval* arg, char* key, ... n )

...

Parameters

arg

...

key

...

n

...

Return Values

...

Prev | Home | Next
add_property_long_ex | Up | add_property_null_ex


add_property_long_ex

add_property_long_ex -- ...

Description

#include <zend_API.h>

int add_property_long_ex ( zval* arg, char* key, uint key_len, long l, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

l

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_double | Up | add_property_long


add_property_null

add_property_null -- ...

Description

#include <zend_API.h>

int add_property_null ( zval* arg, char* key )

...

Parameters

arg

...

key

...

Return Values

...

Prev | Home | Next
add_property_null_ex | Up | add_property_resource_ex


add_property_null_ex

add_property_null_ex -- ...

Description

#include <zend_API.h>

int add_property_null_ex ( zval* arg, char* key, uint key_len, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_long | Up | add_property_null


add_property_resource

add_property_resource -- ...

Description

#include <zend_API.h>

int add_property_resource ( zval* arg, char* key, long r )

...

Parameters

arg

...

key

...

r

...

Return Values

...

Prev | Home | Next
add_property_resource_ex | Up | add_property_rt_string_ex


add_property_resource_ex

add_property_resource_ex -- ...

Description

#include <zend_API.h>

int add_property_resource_ex ( zval* arg, char* key, uint key_len, long r, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

r

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_null | Up | add_property_resource


add_property_rt_string

add_property_rt_string -- ...

Description

#include <zend_API.h>

int add_property_rt_string ( zval* arg, char* key, char* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_rt_string_ex | Up | add_property_rt_stringl_ex


add_property_rt_string_ex

add_property_rt_string_ex -- ...

Description

#include <zend_API.h>

int add_property_rt_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_resource | Up | add_property_rt_string


add_property_rt_stringl

add_property_rt_stringl -- ...

Description

#include <zend_API.h>

int add_property_rt_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_rt_stringl_ex | Up | add_property_string_ex


add_property_rt_stringl_ex

add_property_rt_stringl_ex -- ...

Description

#include <zend_API.h>

int add_property_rt_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_rt_string | Up | add_property_rt_stringl


add_property_string

add_property_string -- ...

Description

#include <zend_API.h>

int add_property_string ( zval* arg, char* key, char* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_string_ex | Up | add_property_stringl_ex


add_property_string_ex

add_property_string_ex -- ...

Description

#include <zend_API.h>

int add_property_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_rt_stringl | Up | add_property_string


add_property_stringl

add_property_stringl -- ...

Description

#include <zend_API.h>

int add_property_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_stringl_ex | Up | add_property_unicode_ex


add_property_stringl_ex

add_property_stringl_ex -- ...

Description

#include <zend_API.h>

int add_property_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_string | Up | add_property_stringl


add_property_unicode

add_property_unicode -- ...

Description

#include <zend_API.h>

int add_property_unicode ( zval* arg, char* key, UChar* str, int duplicate )

...

Parameters

arg

...

key

...

str

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_unicode_ex | Up | add_property_unicodel_ex


add_property_unicode_ex

add_property_unicode_ex -- ...

Description

#include <zend_API.h>

int add_property_unicode_ex ( zval* arg, char* key, uint key_len, UChar* str, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_stringl | Up | add_property_unicode


add_property_unicodel

add_property_unicodel -- ...

Description

#include <zend_API.h>

int add_property_unicodel ( zval* arg, char* key, UChar* str, uint length, int duplicate )

...

Parameters

arg

...

key

...

str

...

length

...

duplicate

...

Return Values

...

Prev | Home | Next
add_property_unicodel_ex | Up | add_property_unset


add_property_unicodel_ex

add_property_unicodel_ex -- ...

Description

#include <zend_API.h>

int add_property_unicodel_ex ( zval* arg, char* key, uint key_len, UChar* str, uint length, int duplicate, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_unicode | Up | add_property_unicodel


add_property_unset

add_property_unset -- ...

Description

#include <zend_API.h>

int add_property_unset ( zval* arg, char* key )

...

Parameters

arg

...

key

...

Return Values

...

Prev | Home | Next
add_property_unicodel | Up | add_property_zval_ex


add_property_zval

add_property_zval -- ...

Description

#include <zend_API.h>

int add_property_zval ( zval* arg, char* key, zval* value )

...

Parameters

arg

...

key

...

value

...

Return Values

...

Prev | Home | Next
add_property_zval_ex | Up | add_u_assoc_zval_ex


add_property_zval_ex

add_property_zval_ex -- ...

Description

#include <zend_API.h>

int add_property_zval_ex ( zval* arg, char* key, uint key_len, zval* value, magic TSRMLS_DC )

...

Parameters

arg

...

key

...

key_len

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
add_property_unset | Up | add_property_zval


add_u_assoc_zval

add_u_assoc_zval -- ...

Description

#include <zend_API.h>

int add_u_assoc_zval ( zval* arg, zend_uchar type, void* key, zval* value )

...

Parameters

arg

...

type

...

key

...

value

...

Return Values

...

Prev | Home | Next
add_u_assoc_zval_ex | Up | array_init


add_u_assoc_zval_ex

add_u_assoc_zval_ex -- ...

Description

#include <zend_API.h>

int add_u_assoc_zval_ex ( zval* arg, zend_uchar type, void* key, uint key_len, zval* value )

...

Parameters

arg

...

type

...

key

...

key_len

...

value

...

Return Values

...

Prev | Home | Next
add_property_zval | Up | add_u_assoc_zval


array_init

array_init -- ...

Description

#include <zend_API.h>

int array_init ( zval* arg )

...

Parameters

arg

...

Return Values

...

Prev | Home | Next
add_u_assoc_zval | Up | call_user_function_ex


call_user_function

call_user_function -- ...

Description

#include <zend_API.h>

int call_user_function ( HashTable* function_table, zval** object_pp, zval* function_name, zval* retval_ptr, zend_uint param_count, zval* params[], magic TSRMLS_DC )

...

Parameters

function_table

...

object_pp

...

function_name

...

retval_ptr

...

param_count

...

params[]

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
call_user_function_ex | Up | compile_file


call_user_function_ex

call_user_function_ex -- ...

Description

#include <zend_API.h>

int call_user_function_ex ( HashTable* function_table, zval** object_pp, zval* function_name, zval** retval_ptr_ptr, zend_uint param_count, zval** params[], int no_separation, HashTable* symbol_table, magic TSRMLS_DC )

...

Parameters

function_table

...

object_pp

...

function_name

...

retval_ptr_ptr

...

param_count

...

params[]

...

no_separation

...

symbol_table

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
array_init | Up | call_user_function


compile_file

compile_file -- ...

Description

#include <zend_compile.h>

zend_op_array* compile_file ( zend_file_handle* file_handle, int type, magic TSRMLS_DC )

...

Parameters

file_handle

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
call_user_function | Up | compile_filename


compile_filename

compile_filename -- ...

Description

#include <zend_compile.h>

zend_op_array* compile_filename ( int type, zval* filename, magic TSRMLS_DC )

...

Parameters

type

...

filename

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
compile_file | Up | compile_string


compile_string

compile_string -- ...

Description

#include <zend_compile.h>

zend_op_array* compile_string ( zval* source_string, char* filename, magic TSRMLS_DC )

...

Parameters

source_string

...

filename

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
compile_filename | Up | destroy_op_array


destroy_op_array

destroy_op_array -- ...

Description

#include <zend_compile.h>

void destroy_op_array ( zend_op_array* op_array, magic TSRMLS_DC )

...

Parameters

op_array

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
compile_string | Up | destroy_zend_class


destroy_zend_class

destroy_zend_class -- ...

Description

#include <zend_compile.h>

void destroy_zend_class ( zend_class_entry** pce )

...

Parameters

pce

...

Return Values

...

Prev | Home | Next
destroy_op_array | Up | destroy_zend_function


destroy_zend_function

destroy_zend_function -- ...

Description

#include <zend_compile.h>

void destroy_zend_function ( zend_function* function, magic TSRMLS_DC )

...

Parameters

function

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
destroy_zend_class | Up | display_ini_entries


DISPLAY_INI_ENTRIES

DISPLAY_INI_ENTRIES -- ...

Description

#include <zend_ini.h>

void DISPLAY_INI_ENTRIES ( ... )

...

Parameters

...

Return Values

...

Prev | Home | Next
zval_update_constant | Up | INI_BOOL


do_bind_class

do_bind_class -- ...

Description

#include <zend_compile.h>

zend_class_entry* do_bind_class ( zend_op* opline, HashTable* class_table, zend_bool compile_time, magic TSRMLS_DC )

...

Parameters

opline

...

class_table

...

compile_time

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
display_ini_entries | Up | do_bind_function


do_bind_function

do_bind_function -- ...

Description

#include <zend_compile.h>

int do_bind_function ( zend_op* opline, HashTable* function_table, zend_bool compile_time )

...

Parameters

opline

...

function_table

...

compile_time

...

Return Values

...

Prev | Home | Next
do_bind_class | Up | do_bind_inherited_class


do_bind_inherited_class

do_bind_inherited_class -- ...

Description

#include <zend_compile.h>

zend_class_entry* do_bind_inherited_class ( zend_op* opline, HashTable* class_table, zend_class_entry* parent_ce, zend_bool compile_time, magic TSRMLS_DC )

...

Parameters

opline

...

class_table

...

parent_ce

...

compile_time

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
do_bind_function | Up | estrndup_rel


estrndup

estrndup -- ...

Description

#include <zend_alloc.h>

char* estrndup ( const char* s, unsigned int length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
estrndup_rel | Up | eustrdup


estrndup_rel

estrndup_rel -- ...

Description

#include <zend_alloc.h>

char* estrndup_rel ( const char* s, unsigned int length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
do_bind_inherited_class | Up | estrndup


eustrdup

eustrdup -- ...

Description

#include <zend_alloc.h>

UChar* eustrdup ( const UChar* s )

...

Parameters

s

...

Return Values

...

Prev | Home | Next
estrndup | Up | eustrndup_rel


eustrndup

eustrndup -- ...

Description

#include <zend_alloc.h>

UChar* eustrndup ( const UChar* s, uint length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
eustrndup_rel | Up | execute_internal


eustrndup_rel

eustrndup_rel -- ...

Description

#include <zend_alloc.h>

UChar* eustrndup_rel ( const UChar* s, uint length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
eustrdup | Up | eustrndup


execute

execute -- ...

Description

#include <zend_execute.h>

void execute ( zend_op_array* op_array, magic TSRMLS_DC )

...

Parameters

op_array

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
execute_internal | Up | free_estring


execute_internal

execute_internal -- ...

Description

#include <zend_execute.h>

void execute_internal ( zend_execute_data* execute_data_ptr, int return_value_used, magic TSRMLS_DC )

...

Parameters

execute_data_ptr

...

return_value_used

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
eustrndup | Up | execute


free_estring

free_estring -- ...

Description

#include <zend.h>

void free_estring ( char** str_p )

...

Parameters

str_p

...

Return Values

...

Prev | Home | Next
execute | Up | full_mem_check


full_mem_check

full_mem_check -- ...

Description

#include <zend_alloc.h>

void full_mem_check ( ... silent )

...

Parameters

silent

...

Return Values

...

Prev | Home | Next
free_estring | Up | function_add_ref


function_add_ref

function_add_ref -- ...

Description

#include <zend_compile.h>

void function_add_ref ( zend_function* function, magic TSRMLS_DC )

...

Parameters

function

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
full_mem_check | Up | get_active_class_name


get_active_class_name

get_active_class_name -- ...

Description

#include <zend_execute.h>

char* get_active_class_name ( char** space, magic TSRMLS_DC )

...

Parameters

space

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
function_add_ref | Up | get_active_function_name


get_active_function_name

get_active_function_name -- ...

Description

#include <zend_execute.h>

char* get_active_function_name ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
get_active_class_name | Up | get_binary_op


get_binary_op

get_binary_op -- ...

Description

#include <zend_compile.h>

void* get_binary_op ( int opcode )

...

Parameters

opcode

...

Return Values

...

Prev | Home | Next
get_active_function_name | Up | get_unary_op


get_unary_op

get_unary_op -- ...

Description

#include <zend_compile.h>

unary_op_type get_unary_op ( int opcode )

...

Parameters

opcode

...

Return Values

...

Prev | Home | Next
get_binary_op | Up | get_zend_version


get_zend_version

get_zend_version -- Get Zend Engine version string

Description

#include <zend.h>

char* get_zend_version ( void )

get_zend_version() returns a verbose version string containing both version and copyright information for the Zend Engine in use.

Return Values

A Zend version string like:

Zend Engine v2.0.5, Copyright (c) 1998-2006 Zend Technologies

Prev | Home | Next
get_unary_op | Up | highlight_file


highlight_file

highlight_file -- ...

Description

#include <zend_highlight.h>

int highlight_file ( char* filename, zend_syntax_highlighter_ini* syntax_highlighter_ini, magic TSRMLS_DC )

...

Parameters

filename

...

syntax_highlighter_ini

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
get_zend_version | Up | highlight_string


highlight_string

highlight_string -- ...

Description

#include <zend_highlight.h>

int highlight_string ( zval* str, zend_syntax_highlighter_ini* syntax_highlighter_ini, char* str_name, magic TSRMLS_DC )

...

Parameters

str

...

syntax_highlighter_ini

...

str_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
highlight_file | Up | init_op_array


INI_BOOL

INI_BOOL -- ...

Description

#include <zend_ini.h>

long INI_BOOL ( ... name) ((zend_bool )

...

Parameters

name) ((zend_bool

...

Return Values

...

Prev | Home | Next
DISPLAY_INI_ENTRIES | Up | INI_FLT


INI_FLT

INI_FLT -- ...

Description

#include <zend_ini.h>

double INI_FLT ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_BOOL | Up | INI_INT


INI_INT

INI_INT -- ...

Description

#include <zend_ini.h>

long INI_INT ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_FLT | Up | INI_ORIG_BOOL


INI_ORIG_BOOL

INI_ORIG_BOOL -- ...

Description

#include <zend_ini.h>

long INI_ORIG_BOOL ( ... name) ((zend_bool )

...

Parameters

name) ((zend_bool

...

Return Values

...

Prev | Home | Next
INI_INT | Up | INI_ORIG_FLT


INI_ORIG_FLT

INI_ORIG_FLT -- ...

Description

#include <zend_ini.h>

double INI_ORIG_FLT ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_ORIG_BOOL | Up | INI_ORIG_INT


INI_ORIG_INT

INI_ORIG_INT -- ...

Description

#include <zend_ini.h>

long INI_ORIG_INT ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_ORIG_FLT | Up | INI_ORIG_STR


INI_ORIG_STR

INI_ORIG_STR -- ...

Description

#include <zend_ini.h>

char* INI_ORIG_STR ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_ORIG_INT | Up | INI_STR


INI_STR

INI_STR -- ...

Description

#include <zend_ini.h>

char* INI_STR ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
INI_ORIG_STR | Up | REGISTER_DOUBLE_CONSTANT


init_op_array

init_op_array -- ...

Description

#include <zend_compile.h>

void init_op_array ( zend_op_array* op_array, zend_uchar type, int initial_ops_size, magic TSRMLS_DC )

...

Parameters

op_array

...

type

...

initial_ops_size

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
highlight_string | Up | lex_scan


lex_scan

lex_scan -- ...

Description

#include <zend_compile.h>

int lex_scan ( zval* zendlval, magic TSRMLS_DC )

...

Parameters

zendlval

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
init_op_array | Up | mem_block_check


mem_block_check

mem_block_check -- ...

Description

#include <zend_alloc.h>

int mem_block_check ( void* ptr, ... silent )

...

Parameters

ptr

...

silent

...

Return Values

...

Prev | Home | Next
lex_scan | Up | object_and_properties_init


object_and_properties_init

object_and_properties_init -- ...

Description

#include <zend_API.h>

int object_and_properties_init ( zval* arg, zend_class_entry* ce, HashTable* properties )

...

Parameters

arg

...

ce

...

properties

...

Return Values

...

Prev | Home | Next
mem_block_check | Up | object_init_ex


object_init

object_init -- ...

Description

#include <zend_API.h>

int object_init ( zval* arg )

...

Parameters

arg

...

Return Values

...

Prev | Home | Next
object_init_ex | Up | open_file_for_scanning


object_init_ex

object_init_ex -- ...

Description

#include <zend_API.h>

int object_init_ex ( zval* arg, zend_class_entry* ce )

...

Parameters

arg

...

ce

...

Return Values

...

Prev | Home | Next
object_and_properties_init | Up | object_init


open_file_for_scanning

open_file_for_scanning -- ...

Description

#include <zend_compile.h>

int open_file_for_scanning ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
object_init | Up | register_list_destructors


REGISTER_DOUBLE_CONSTANT

REGISTER_DOUBLE_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_DOUBLE_CONSTANT ( char* name, double dval, int flags )

...

Parameters

name

...

dval

...

flags

...

Return Values

...

Prev | Home | Next
INI_STR | Up | REGISTER_INI_BOOLEAN


REGISTER_INI_BOOLEAN

REGISTER_INI_BOOLEAN -- ...

Description

#include <zend_ini.h>

int REGISTER_INI_BOOLEAN ( char* name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
REGISTER_DOUBLE_CONSTANT | Up | REGISTER_INI_DISPLAYER


REGISTER_INI_DISPLAYER

REGISTER_INI_DISPLAYER -- ...

Description

#include <zend_ini.h>

int REGISTER_INI_DISPLAYER ( char* name, ... displayer )

...

Parameters

name

...

displayer

...

Return Values

...

Prev | Home | Next
REGISTER_INI_BOOLEAN | Up | REGISTER_INI_ENTRIES


REGISTER_INI_ENTRIES

REGISTER_INI_ENTRIES -- ...

Description

#include <zend_ini.h>

int REGISTER_INI_ENTRIES ( ... )

...

Parameters

...

Return Values

...

Prev | Home | Next
REGISTER_INI_DISPLAYER | Up | REGISTER_LONG_CONSTANT


register_list_destructors

register_list_destructors -- ...

Description

#include <zend_list.h>

int register_list_destructors ( ... ld, ... pld )

...

Parameters

ld

...

pld

...

Return Values

...

Prev | Home | Next
open_file_for_scanning | Up | shutdown_memory_manager


REGISTER_LONG_CONSTANT

REGISTER_LONG_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_LONG_CONSTANT ( char* name, long lval, int flags )

...

Parameters

name

...

lval

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_INI_ENTRIES | Up | REGISTER_MAIN_DOUBLE_CONSTANT


REGISTER_MAIN_DOUBLE_CONSTANT

REGISTER_MAIN_DOUBLE_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_MAIN_DOUBLE_CONSTANT ( char* name, double dval, int flags )

...

Parameters

name

...

dval

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_LONG_CONSTANT | Up | REGISTER_MAIN_LONG_CONSTANT


REGISTER_MAIN_LONG_CONSTANT

REGISTER_MAIN_LONG_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_MAIN_LONG_CONSTANT ( char* name, long lval, int flags )

...

Parameters

name

...

lval

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_MAIN_DOUBLE_CONSTANT | Up | REGISTER_MAIN_STRING_CONSTANT


REGISTER_MAIN_STRING_CONSTANT

REGISTER_MAIN_STRING_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_MAIN_STRING_CONSTANT ( char* name, ... str, int flags )

...

Parameters

name

...

str

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_MAIN_LONG_CONSTANT | Up | REGISTER_MAIN_STRINGL_CONSTANT


REGISTER_MAIN_STRINGL_CONSTANT

REGISTER_MAIN_STRINGL_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_MAIN_STRINGL_CONSTANT ( char* name, ... str, ... len, int flags )

...

Parameters

name

...

str

...

len

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_MAIN_STRING_CONSTANT | Up | REGISTER_STRING_CONSTANT


REGISTER_STRING_CONSTANT

REGISTER_STRING_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_STRING_CONSTANT ( char* name, ... str, int flags )

...

Parameters

name

...

str

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_MAIN_STRINGL_CONSTANT | Up | REGISTER_STRINGL_CONSTANT


REGISTER_STRINGL_CONSTANT

REGISTER_STRINGL_CONSTANT -- ...

Description

#include <zend_constants.h>

void REGISTER_STRINGL_CONSTANT ( char* name, ... str, ... len, int flags )

...

Parameters

name

...

str

...

len

...

flags

...

Return Values

...

Prev | Home | Next
REGISTER_STRING_CONSTANT | Up | RETURN_ASCII_STRING


shutdown_memory_manager

shutdown_memory_manager -- ...

Description

#include <zend_alloc.h>

void shutdown_memory_manager ( int silent, int full_shutdown, magic TSRMLS_DC )

...

Parameters

silent

...

full_shutdown

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
register_list_destructors | Up | start_memory_manager


start_memory_manager

start_memory_manager -- ...

Description

#include <zend_alloc.h>

void start_memory_manager ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
shutdown_memory_manager | Up | zend_alter_ini_entry


ts_allocate_id

ts_allocate_id -- ...

Description

#include <TSRM.h>

ts_rsrc_id ts_allocate_id ( ts_rsrc_id* rsrc_id, size_t size, ts_allocate_ctor ctor, ts_allocate_dtor dtor )

...

Parameters

rsrc_id

...

size

...

ctor

...

dtor

...

Return Values

...

Prev | Home | Next
TSRM API | Up | ts_free_id


ts_free_id

ts_free_id -- ...

Description

#include <TSRM.h>

void ts_free_id ( ts_rsrc_id id )

...

Parameters

id

...

Return Values

...

Prev | Home | Next
ts_allocate_id | Up | ts_free_thread


ts_free_thread

ts_free_thread -- ...

Description

#include <TSRM.h>

void ts_free_thread ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
ts_free_id | Up | ts_resource_ex


ts_resource

ts_resource -- ...

Description

#include <TSRM.h>

void* ts_resource ( ts_rsrc_id id )

...

Parameters

id

...

Return Values

...

Prev | Home | Next
ts_resource_ex | Up | tsrm_error_set


ts_resource_ex

ts_resource_ex -- ...

Description

#include <TSRM.h>

void* ts_resource_ex ( ts_rsrc_id id, THREAD_T* th_id )

...

Parameters

id

...

th_id

...

Return Values

...

Prev | Home | Next
ts_free_thread | Up | ts_resource


tsrm_error

tsrm_error -- ...

Description

#include <TSRM.h>

int tsrm_error ( int level, const char* format, ... )

...

Parameters

level

...

format

...

...

...

Return Values

...

Prev | Home | Next
tsrm_error_set | Up | tsrm_free_interpreter_context


tsrm_error_set

tsrm_error_set -- ...

Description

#include <TSRM.h>

void tsrm_error_set ( int level, char* debug_filename )

...

Parameters

level

...

debug_filename

...

Return Values

...

Prev | Home | Next
ts_resource | Up | tsrm_error


tsrm_free_interpreter_context

tsrm_free_interpreter_context -- ...

Description

#include <TSRM.h>

void tsrm_free_interpreter_context ( void* context )

...

Parameters

context

...

Return Values

...

Prev | Home | Next
tsrm_error | Up | tsrm_mutex_alloc


tsrm_mutex_alloc

tsrm_mutex_alloc -- ...

Description

#include <TSRM.h>

MUTEX_T tsrm_mutex_alloc ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
tsrm_free_interpreter_context | Up | tsrm_mutex_free


tsrm_mutex_free

tsrm_mutex_free -- ...

Description

#include <TSRM.h>

void tsrm_mutex_free ( MUTEX_T mutexp )

...

Parameters

mutexp

...

Return Values

...

Prev | Home | Next
tsrm_mutex_alloc | Up | tsrm_mutex_lock


tsrm_mutex_lock

tsrm_mutex_lock -- ...

Description

#include <TSRM.h>

int tsrm_mutex_lock ( MUTEX_T mutexp )

...

Parameters

mutexp

...

Return Values

...

Prev | Home | Next
tsrm_mutex_free | Up | tsrm_mutex_unlock


tsrm_mutex_unlock

tsrm_mutex_unlock -- ...

Description

#include <TSRM.h>

int tsrm_mutex_unlock ( MUTEX_T mutexp )

...

Parameters

mutexp

...

Return Values

...

Prev | Home | Next
tsrm_mutex_lock | Up | tsrm_new_interpreter_context


tsrm_new_interpreter_context

tsrm_new_interpreter_context -- ...

Description

#include <TSRM.h>

void* tsrm_new_interpreter_context ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
tsrm_mutex_unlock | Up | tsrm_set_interpreter_context


tsrm_set_interpreter_context

tsrm_set_interpreter_context -- ...

Description

#include <TSRM.h>

void* tsrm_set_interpreter_context ( void* new_ctx )

...

Parameters

new_ctx

...

Return Values

...

Prev | Home | Next
tsrm_new_interpreter_context | Up | tsrm_set_new_thread_begin_handler


tsrm_set_new_thread_begin_handler

tsrm_set_new_thread_begin_handler -- ...

Description

#include <TSRM.h>

void* tsrm_set_new_thread_begin_handler ( tsrm_thread_begin_func_t new_thread_begin_handler )

...

Parameters

new_thread_begin_handler

...

Return Values

...

Prev | Home | Next
tsrm_set_interpreter_context | Up | tsrm_set_new_thread_end_handler


tsrm_set_new_thread_end_handler

tsrm_set_new_thread_end_handler -- ...

Description

#include <TSRM.h>

void* tsrm_set_new_thread_end_handler ( tsrm_thread_end_func_t new_thread_end_handler )

...

Parameters

new_thread_end_handler

...

Return Values

...

Prev | Home | Next
tsrm_set_new_thread_begin_handler | Up | tsrm_shutdown


tsrm_shutdown

tsrm_shutdown -- ...

Description

#include <TSRM.h>

void tsrm_shutdown ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
tsrm_set_new_thread_end_handler | Up | tsrm_startup


tsrm_startup

tsrm_startup -- ...

Description

#include <TSRM.h>

int tsrm_startup ( int expected_threads, int expected_resources, int debug_level, char* debug_filename )

...

Parameters

expected_threads

...

expected_resources

...

debug_level

...

debug_filename

...

Return Values

...

Prev | Home | Next
tsrm_shutdown | Up | tsrm_thread_id


tsrm_thread_id

tsrm_thread_id -- ...

Description

#include <TSRM.h>

THREAD_T tsrm_thread_id ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
tsrm_startup | Up | virtual_access


UNREGISTER_INI_ENTRIES

UNREGISTER_INI_ENTRIES -- ...

Description

#include <zend_ini.h>

void UNREGISTER_INI_ENTRIES ( ... )

...

Parameters

...

Return Values

...

Prev | Home | Next
RETURN_ZVAL | Up | Z_ARRVAL_P


virtual_access

virtual_access -- Check users permissions for a file

Description

#include <tsrm_virtual_cwd.h>

int virtual_access ( const char* pathname, int mode, magic TSRMLS_DC )

virtual_access() thread safe wrapper around the access() function that takes per-thread virtual working directories into account.

See also VCWD_ACCESS().

Parameters

pathname

File to check permissions for

mode

Mode mask

TSRMLS_DC

Thread context

Return Values

Returns 0 on success and -1 on errors.

Prev | Home | Next
tsrm_thread_id | Up | virtual_chdir_file


virtual_chdir

virtual_chdir -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_chdir ( const char* path, magic TSRMLS_DC )

...

Parameters

path

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_chdir_file | Up | virtual_chmod


virtual_chdir_file

virtual_chdir_file -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_chdir_file ( const char* path, int (*p_chdir)(const char *path TSRMLS_DC) chdir_func, magic TSRMLS_DC )

...

Parameters

path

...

chdir_func

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_access | Up | virtual_chdir


virtual_chmod

virtual_chmod -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_chmod ( const char* filename, mode_t mode, magic TSRMLS_DC )

...

Parameters

filename

...

mode

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_chdir | Up | virtual_chown


virtual_chown

virtual_chown -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_chown ( const char* filename, uid_t owner, gid_t group, int link, magic TSRMLS_DC )

...

Parameters

filename

...

owner

...

group

...

link

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_chmod | Up | virtual_creat


virtual_creat

virtual_creat -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_creat ( const char* path, mode_t mode, magic TSRMLS_DC )

...

Parameters

path

...

mode

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_chown | Up | virtual_cwd_shutdown


virtual_cwd_shutdown

virtual_cwd_shutdown -- ...

Description

#include <tsrm_virtual_cwd.h>

void virtual_cwd_shutdown ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
virtual_creat | Up | virtual_cwd_startup


virtual_cwd_startup

virtual_cwd_startup -- ...

Description

#include <tsrm_virtual_cwd.h>

void virtual_cwd_startup ( void )

...

Parameters

void

...

Return Values

...

Prev | Home | Next
virtual_cwd_shutdown | Up | virtual_file_ex


virtual_file_ex

virtual_file_ex -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_file_ex ( cwd_state* state, const char* path, verify_path_func verify_path, int use_realpath )

...

Parameters

state

...

path

...

verify_path

...

use_realpath

...

Return Values

...

Prev | Home | Next
virtual_cwd_startup | Up | virtual_filepath_ex


virtual_filepath

virtual_filepath -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_filepath ( const char* path, char** filepath, magic TSRMLS_DC )

...

Parameters

path

...

filepath

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_filepath_ex | Up | virtual_fopen


virtual_filepath_ex

virtual_filepath_ex -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_filepath_ex ( const char* path, char** filepath, verify_path_func verify_path, magic TSRMLS_DC )

...

Parameters

path

...

filepath

...

verify_path

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_file_ex | Up | virtual_filepath


virtual_fopen

virtual_fopen -- ...

Description

#include <tsrm_virtual_cwd.h>

FILE* virtual_fopen ( const char* path, const char* mode, magic TSRMLS_DC )

...

Parameters

path

...

mode

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_filepath | Up | virtual_getcwd_ex


virtual_getcwd

virtual_getcwd -- ...

Description

#include <tsrm_virtual_cwd.h>

char* virtual_getcwd ( char* buf, size_t size, magic TSRMLS_DC )

...

Parameters

buf

...

size

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_getcwd_ex | Up | virtual_lstat


virtual_getcwd_ex

virtual_getcwd_ex -- ...

Description

#include <tsrm_virtual_cwd.h>

char* virtual_getcwd_ex ( size_t* length, magic TSRMLS_DC )

...

Parameters

length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_fopen | Up | virtual_getcwd


virtual_lstat

virtual_lstat -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_lstat ( const char* path, struct stat* buf, magic TSRMLS_DC )

...

Parameters

path

...

buf

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_getcwd | Up | virtual_mkdir


virtual_mkdir

virtual_mkdir -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_mkdir ( const char* pathname, mode_t mode, magic TSRMLS_DC )

...

Parameters

pathname

...

mode

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_lstat | Up | virtual_open


virtual_open

virtual_open -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_open ( const char* path, magic TSRMLS_DC, int flags, ... )

...

Parameters

path

...

TSRMLS_DC

...

flags

...

...

...

Return Values

...

Prev | Home | Next
virtual_mkdir | Up | virtual_opendir


virtual_opendir

virtual_opendir -- ...

Description

#include <tsrm_virtual_cwd.h>

DIR* virtual_opendir ( const char* pathname, magic TSRMLS_DC )

...

Parameters

pathname

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_open | Up | virtual_popen


virtual_popen

virtual_popen -- ...

Description

#include <tsrm_virtual_cwd.h>

FILE* virtual_popen ( const char* command, const char* type, magic TSRMLS_DC )

...

Parameters

command

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_opendir | Up | virtual_realpath


virtual_realpath

virtual_realpath -- ...

Description

#include <tsrm_virtual_cwd.h>

char* virtual_realpath ( const char* path, char* real_path, magic TSRMLS_DC )

...

Parameters

path

...

real_path

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_popen | Up | virtual_rename


virtual_rename

virtual_rename -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_rename ( char* oldname, char* newname, magic TSRMLS_DC )

...

Parameters

oldname

...

newname

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_realpath | Up | virtual_rmdir


virtual_rmdir

virtual_rmdir -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_rmdir ( const char* pathname, magic TSRMLS_DC )

...

Parameters

pathname

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_rename | Up | virtual_stat


virtual_stat

virtual_stat -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_stat ( const char* path, struct stat* buf, magic TSRMLS_DC )

...

Parameters

path

...

buf

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_rmdir | Up | virtual_unlink


virtual_unlink

virtual_unlink -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_unlink ( const char* path, magic TSRMLS_DC )

...

Parameters

path

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_stat | Up | virtual_utime


virtual_utime

virtual_utime -- ...

Description

#include <tsrm_virtual_cwd.h>

int virtual_utime ( const char* filename, struct utimbuf* buf, magic TSRMLS_DC )

...

Parameters

filename

...

buf

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
virtual_unlink | Up | VCWD_ACCESS


zend_alter_ini_entry

zend_alter_ini_entry -- ...

Description

#include <zend_ini.h>

int zend_alter_ini_entry ( char* name, uint name_length, char* new_value, uint new_value_length, int modify_type, int stage )

...

Parameters

name

...

name_length

...

new_value

...

new_value_length

...

modify_type

...

stage

...

Return Values

...

Prev | Home | Next
start_memory_manager | Up | zend_auto_global_disable_jit


zend_auto_global_disable_jit

zend_auto_global_disable_jit -- ...

Description

#include <zend_compile.h>

int zend_auto_global_disable_jit ( char* varname, zend_uint varname_length, magic TSRMLS_DC )

...

Parameters

varname

...

varname_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_alter_ini_entry | Up | zend_bailout


zend_bailout

zend_bailout -- ...

Description

#include <zend.h>

void zend_bailout ( ... )

...

Parameters

...

Return Values

...

Prev | Home | Next
zend_auto_global_disable_jit | Up | zend_call_function


zend_call_function

zend_call_function -- ...

Description

#include <zend_API.h>

int zend_call_function ( zend_fcall_info* fci, zend_fcall_info_cache* fci_cache, magic TSRMLS_DC )

...

Parameters

fci

...

fci_cache

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_bailout | Up | zend_call_method_with_0_params


zend_call_method

zend_call_method -- ...

Description

#include <zend_interfaces.h>

zval* zend_call_method ( zval** object_pp, zend_class_entry* obj_ce, zend_function** fn_proxy, char* function_name, int function_name_len, zval** retval_ptr_ptr, int param_count, zval* arg1, zval* arg2, magic TSRMLS_DC )

...

Parameters

object_pp

...

obj_ce

...

fn_proxy

...

function_name

...

function_name_len

...

retval_ptr_ptr

...

param_count

...

arg1

...

arg2

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_call_method_with_2_params | Up | zend_case_fold_string


zend_call_method_with_0_params

zend_call_method_with_0_params -- ...

Description

#include <zend_interfaces.h>

zval* zend_call_method_with_0_params ( ... obj, zend_class_entry* obj_ce, zend_function** fn_proxy, char* function_name, ... retval )

...

Parameters

obj

...

obj_ce

...

fn_proxy

...

function_name

...

retval

...

Return Values

...

Prev | Home | Next
zend_call_function | Up | zend_call_method_with_1_params


zend_call_method_with_1_params

zend_call_method_with_1_params -- ...

Description

#include <zend_interfaces.h>

zval* zend_call_method_with_1_params ( ... obj, zend_class_entry* obj_ce, zend_function** fn_proxy, char* function_name, ... retval, zval* arg1 )

...

Parameters

obj

...

obj_ce

...

fn_proxy

...

function_name

...

retval

...

arg1

...

Return Values

...

Prev | Home | Next
zend_call_method_with_0_params | Up | zend_call_method_with_2_params


zend_call_method_with_2_params

zend_call_method_with_2_params -- ...

Description

#include <zend_interfaces.h>

zval* zend_call_method_with_2_params ( ... obj, zend_class_entry* obj_ce, zend_function** fn_proxy, char* function_name, ... retval, zval* arg1, zval* arg2 )

...

Parameters

obj

...

obj_ce

...

fn_proxy

...

function_name

...

retval

...

arg1

...

arg2

...

Return Values

...

Prev | Home | Next
zend_call_method_with_1_params | Up | zend_call_method


zend_case_fold_string

zend_case_fold_string -- ...

Description

#include <zend_unicode.h>

void zend_case_fold_string ( UChar** dest, int32_t* dest_len, UChar* src, int32_t src_len, uint32_t options, UErrorCode* status )

...

Parameters

dest

...

dest_len

...

src

...

src_len

...

options

...

status

...

Return Values

...

Prev | Home | Next
zend_call_method | Up | zend_check_magic_method_implementation


zend_check_magic_method_implementation

zend_check_magic_method_implementation -- ...

Description

#include <zend_API.h>

void zend_check_magic_method_implementation ( zend_class_entry* ce, zend_function* fptr, int error_type, magic TSRMLS_DC )

...

Parameters

ce

...

fptr

...

error_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_case_fold_string | Up | zend_check_private


zend_check_private

zend_check_private -- ...

Description

#include <zend_object_handlers.h>

int zend_check_private ( union _zend_function* fbc, zend_class_entry* ce, char* function_name_strval, int function_name_strlen, magic TSRMLS_DC )

...

Parameters

fbc

...

ce

...

function_name_strval

...

function_name_strlen

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_check_magic_method_implementation | Up | zend_check_property_access


zend_check_property_access

zend_check_property_access -- ...

Description

#include <zend_object_handlers.h>

int zend_check_property_access ( zend_object* zobj, zend_uchar utype, void* prop_info_name, magic TSRMLS_DC )

...

Parameters

zobj

...

utype

...

prop_info_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_check_private | Up | zend_check_protected


zend_check_protected

zend_check_protected -- ...

Description

#include <zend_object_handlers.h>

int zend_check_protected ( zend_class_entry* ce, zend_class_entry* scope )

...

Parameters

ce

...

scope

...

Return Values

...

Prev | Home | Next
zend_check_property_access | Up | zend_class_implements


zend_class_implements

zend_class_implements -- ...

Description

#include <zend_API.h>

void zend_class_implements ( zend_class_entry* class_entry, magic TSRMLS_DC, int num_interfaces, ... )

...

Parameters

class_entry

...

TSRMLS_DC

...

num_interfaces

...

...

...

Return Values

...

Prev | Home | Next
zend_check_protected | Up | zend_cleanup_class_data


zend_cleanup_class_data

zend_cleanup_class_data -- ...

Description

#include <zend_compile.h>

int zend_cleanup_class_data ( zend_class_entry** pce, magic TSRMLS_DC )

...

Parameters

pce

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_class_implements | Up | zend_cleanup_function_data


zend_cleanup_function_data

zend_cleanup_function_data -- ...

Description

#include <zend_compile.h>

int zend_cleanup_function_data ( zend_function* function, magic TSRMLS_DC )

...

Parameters

function

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_cleanup_class_data | Up | zend_clear_exception


zend_clear_exception

zend_clear_exception -- ...

Description

#include <zend_exceptions.h>

void zend_clear_exception ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_cleanup_function_data | Up | zend_cmp_unicode_and_literal


zend_cmp_unicode_and_literal

zend_cmp_unicode_and_literal -- ...

Description

#include <zend_unicode.h>

int zend_cmp_unicode_and_literal ( UChar* ustr, int32_t ulen, char* str, int32_t slen )

...

Parameters

ustr

...

ulen

...

str

...

slen

...

Return Values

...

Prev | Home | Next
zend_clear_exception | Up | zend_cmp_unicode_and_string


zend_cmp_unicode_and_string

zend_cmp_unicode_and_string -- ...

Description

#include <zend_unicode.h>

int zend_cmp_unicode_and_string ( UChar* ustr, char* str, uint len )

...

Parameters

ustr

...

str

...

len

...

Return Values

...

Prev | Home | Next
zend_cmp_unicode_and_literal | Up | zend_convert_encodings


zend_convert_encodings

zend_convert_encodings -- ...

Description

#include <zend_unicode.h>

void zend_convert_encodings ( UConverter* target_conv, UConverter* source_conv, char** target, int32_t* target_len, const char* source, int32_t source_len, UErrorCode* status )

...

Parameters

target_conv

...

source_conv

...

target

...

target_len

...

source

...

source_len

...

status

...

Return Values

...

Prev | Home | Next
zend_cmp_unicode_and_string | Up | zend_convert_from_unicode


zend_convert_from_unicode

zend_convert_from_unicode -- ...

Description

#include <zend_unicode.h>

void zend_convert_from_unicode ( UConverter* conv, char** target, int32_t* target_len, const UChar* source, int32_t source_len, UErrorCode* status )

...

Parameters

conv

...

target

...

target_len

...

source

...

source_len

...

status

...

Return Values

...

Prev | Home | Next
zend_convert_encodings | Up | zend_convert_scanner_output


zend_convert_scanner_output

zend_convert_scanner_output -- ...

Description

#include <zend_compile.h>

int32_t zend_convert_scanner_output ( UChar** target, int32_t* target_len, const char* source, int32_t source_len, UErrorCode* status, magic TSRMLS_DC )

...

Parameters

target

...

target_len

...

source

...

source_len

...

status

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_convert_from_unicode | Up | zend_convert_to_unicode


zend_convert_to_unicode

zend_convert_to_unicode -- ...

Description

#include <zend_unicode.h>

void zend_convert_to_unicode ( UConverter* conv, UChar** target, int32_t* target_len, const char* source, int32_t source_len, UErrorCode* status )

...

Parameters

conv

...

target

...

target_len

...

source

...

source_len

...

status

...

Return Values

...

Prev | Home | Next
zend_convert_scanner_output | Up | zend_copy_ini_directives


zend_copy_ini_directives

zend_copy_ini_directives -- ...

Description

#include <zend_ini.h>

int zend_copy_ini_directives ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_convert_to_unicode | Up | zend_copy_parameters_array


zend_copy_parameters_array

zend_copy_parameters_array -- ...

Description

#include <zend_API.h>

int zend_copy_parameters_array ( int param_count, zval* argument_array, magic TSRMLS_DC )

...

Parameters

param_count

...

argument_array

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_copy_ini_directives | Up | zend_declare_class_constant_bool


zend_declare_class_constant

zend_declare_class_constant -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant ( zend_class_entry* ce, char* name, size_t name_length, zval* value, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant_stringl | Up | zend_declare_property_bool


zend_declare_class_constant_bool

zend_declare_class_constant_bool -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant_bool ( zend_class_entry* ce, char* name, size_t name_length, zend_bool value, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_copy_parameters_array | Up | zend_declare_class_constant_double


zend_declare_class_constant_double

zend_declare_class_constant_double -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant_double ( zend_class_entry* ce, char* name, size_t name_length, double value, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant_bool | Up | zend_declare_class_constant_long


zend_declare_class_constant_long

zend_declare_class_constant_long -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant_long ( zend_class_entry* ce, char* name, size_t name_length, long value, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant_double | Up | zend_declare_class_constant_string


zend_declare_class_constant_string

zend_declare_class_constant_string -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant_string ( zend_class_entry* ce, char* name, size_t name_length, char* value, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant_long | Up | zend_declare_class_constant_stringl


zend_declare_class_constant_stringl

zend_declare_class_constant_stringl -- ...

Description

#include <zend_API.h>

int zend_declare_class_constant_stringl ( zend_class_entry* ce, char* name, size_t name_length, char* value, size_t value_length, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant_string | Up | zend_declare_class_constant


zend_declare_property

zend_declare_property -- ...

Description

#include <zend_API.h>

int zend_declare_property ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

property

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_stringl | Up | zend_delete_global_variable


zend_declare_property_bool

zend_declare_property_bool -- ...

Description

#include <zend_API.h>

int zend_declare_property_bool ( zend_class_entry* ce, char* name, int name_length, long value, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_class_constant | Up | zend_declare_property_double


zend_declare_property_double

zend_declare_property_double -- ...

Description

#include <zend_API.h>

int zend_declare_property_double ( zend_class_entry* ce, char* name, int name_length, double value, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_bool | Up | zend_declare_property_ex


zend_declare_property_ex

zend_declare_property_ex -- ...

Description

#include <zend_API.h>

int zend_declare_property_ex ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type, char* doc_comment, int doc_comment_len, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

property

...

access_type

...

doc_comment

...

doc_comment_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_double | Up | zend_declare_property_long


zend_declare_property_long

zend_declare_property_long -- ...

Description

#include <zend_API.h>

int zend_declare_property_long ( zend_class_entry* ce, char* name, int name_length, long value, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_ex | Up | zend_declare_property_null


zend_declare_property_null

zend_declare_property_null -- ...

Description

#include <zend_API.h>

int zend_declare_property_null ( zend_class_entry* ce, char* name, int name_length, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_long | Up | zend_declare_property_string


zend_declare_property_string

zend_declare_property_string -- ...

Description

#include <zend_API.h>

int zend_declare_property_string ( zend_class_entry* ce, char* name, int name_length, char* value, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_null | Up | zend_declare_property_stringl


zend_declare_property_stringl

zend_declare_property_stringl -- ...

Description

#include <zend_API.h>

int zend_declare_property_stringl ( zend_class_entry* ce, char* name, int name_length, char* value, int value_len, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

name

...

name_length

...

value

...

value_len

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property_string | Up | zend_declare_property


zend_delete_global_variable

zend_delete_global_variable -- ...

Description

#include <zend_API.h>

int zend_delete_global_variable ( char* name, int name_len, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_declare_property | Up | zend_destroy_file_handle


zend_destroy_file_handle

zend_destroy_file_handle -- ...

Description

#include <zend_compile.h>

void zend_destroy_file_handle ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_delete_global_variable | Up | zend_disable_class


zend_disable_class

zend_disable_class -- ...

Description

#include <zend_API.h>

int zend_disable_class ( char* class_name, uint class_name_length, magic TSRMLS_DC )

...

Parameters

class_name

...

class_name_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_destroy_file_handle | Up | zend_disable_function


zend_disable_function

zend_disable_function -- ...

Description

#include <zend_API.h>

int zend_disable_function ( char* function_name, uint function_name_length, magic TSRMLS_DC )

...

Parameters

function_name

...

function_name_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_disable_class | Up | zend_do_fcall


zend_do_fcall

zend_do_fcall -- ...

Description

#include <zend_execute.h>

int zend_do_fcall ( ZEND_OPCODE_HANDLER_ARGS )

...

Parameters

ZEND_OPCODE_HANDLER_ARGS

...

Return Values

...

Prev | Home | Next
zend_disable_function | Up | zend_do_implement_interface


zend_do_implement_interface

zend_do_implement_interface -- ...

Description

#include <zend_compile.h>

void zend_do_implement_interface ( zend_class_entry* ce, zend_class_entry* iface, magic TSRMLS_DC )

...

Parameters

ce

...

iface

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_do_fcall | Up | zend_do_inherit_interfaces


zend_do_inherit_interfaces

zend_do_inherit_interfaces -- ...

Description

#include <zend_compile.h>

void zend_do_inherit_interfaces ( zend_class_entry* ce, zend_class_entry* iface, magic TSRMLS_DC )

...

Parameters

ce

...

iface

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_do_implement_interface | Up | zend_do_inheritance


zend_do_inheritance

zend_do_inheritance -- ...

Description

#include <zend_compile.h>

void zend_do_inheritance ( zend_class_entry* ce, zend_class_entry* parent_ce, magic TSRMLS_DC )

...

Parameters

ce

...

parent_ce

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_do_inherit_interfaces | Up | zend_error


zend_error

zend_error -- Generate error message and trigger error handling

Description

#include <zend.h>

#include <zend_errors.h>

void zend_error ( int type, const char* format, ... )

...

Parameters

type

One of E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_STRICT, or E_RECOVERABLE_ERROR.

format

A printf() format string.

...

Output parameters for the format string.

Prev | Home | Next
zend_do_inheritance | Up | zend_eval_string_ex


zend_eval_string

zend_eval_string -- ...

Description

#include <zend_execute.h>

int zend_eval_string ( char* str, zval* retval_ptr, char* string_name, magic TSRMLS_DC )

...

Parameters

str

...

retval_ptr

...

string_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_eval_string_ex | Up | zend_exception_error


zend_eval_string_ex

zend_eval_string_ex -- ...

Description

#include <zend_execute.h>

int zend_eval_string_ex ( char* str, zval* retval_ptr, char* string_name, int handle_exceptions, magic TSRMLS_DC )

...

Parameters

str

...

retval_ptr

...

string_name

...

handle_exceptions

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_error | Up | zend_eval_string


zend_exception_error

zend_exception_error -- ...

Description

#include <zend_exceptions.h>

void zend_exception_error ( zval* exception, magic TSRMLS_DC )

...

Parameters

exception

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_eval_string | Up | zend_exception_get_default


zend_exception_get_default

zend_exception_get_default -- ...

Description

#include <zend_exceptions.h>

zend_class_entry* zend_exception_get_default ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_exception_error | Up | zend_execute_scripts


zend_execute_scripts

zend_execute_scripts -- ...

Description

#include <zend_compile.h>

int zend_execute_scripts ( int type, magic TSRMLS_DC, zval** retval, int file_count, ... )

...

Parameters

type

...

TSRMLS_DC

...

retval

...

file_count

...

...

...

Return Values

...

Prev | Home | Next
zend_exception_get_default | Up | zend_fetch_class


zend_fetch_class

zend_fetch_class -- ...

Description

#include <zend_execute.h>

zend_class_entry* zend_fetch_class ( char* class_name, uint class_name_len, int fetch_type, magic TSRMLS_DC )

...

Parameters

class_name

...

class_name_len

...

fetch_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_execute_scripts | Up | zend_fetch_debug_backtrace


zend_fetch_debug_backtrace

zend_fetch_debug_backtrace -- ...

Description

#include <zend_builtin_functions.h>

void zend_fetch_debug_backtrace ( zval* return_value, int skip_last, int provide_object, magic TSRMLS_DC )

...

Parameters

return_value

...

skip_last

...

provide_object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_fetch_class | Up | zend_fetch_list_dtor_id


zend_fetch_list_dtor_id

zend_fetch_list_dtor_id -- ...

Description

#include <zend_list.h>

int zend_fetch_list_dtor_id ( char* type_name )

...

Parameters

type_name

...

Return Values

...

Prev | Home | Next
zend_fetch_debug_backtrace | Up | zend_fetch_resource


zend_fetch_resource

zend_fetch_resource -- ...

Description

#include <zend_list.h>

void* zend_fetch_resource ( zval** passed_id, magic TSRMLS_DC, int default_id, char* resource_type_name, int* found_resource_type, int num_resource_types, ... )

...

Parameters

passed_id

...

TSRMLS_DC

...

default_id

...

resource_type_name

...

found_resource_type

...

num_resource_types

...

...

...

Return Values

...

Prev | Home | Next
zend_fetch_list_dtor_id | Up | zend_file_handle_dtor


zend_file_handle_dtor

zend_file_handle_dtor -- ...

Description

#include <zend_compile.h>

void zend_file_handle_dtor ( zend_file_handle* fh )

...

Parameters

fh

...

Return Values

...

Prev | Home | Next
zend_fetch_resource | Up | zend_function_dtor


zend_function_dtor

zend_function_dtor -- ...

Description

#include <zend_compile.h>

void zend_function_dtor ( zend_function* function )

...

Parameters

function

...

Return Values

...

Prev | Home | Next
zend_file_handle_dtor | Up | zend_get_class_entry


zend_get_class_entry

zend_get_class_entry -- ...

Description

#include <zend_API.h>

zend_class_entry* zend_get_class_entry ( zval* zobject, magic TSRMLS_DC )

...

Parameters

zobject

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_function_dtor | Up | zend_get_compiled_filename


zend_get_compiled_filename

zend_get_compiled_filename -- ...

Description

#include <zend_compile.h>

char* zend_get_compiled_filename ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_class_entry | Up | zend_get_compiled_lineno


zend_get_compiled_lineno

zend_get_compiled_lineno -- ...

Description

#include <zend_compile.h>

int zend_get_compiled_lineno ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_compiled_filename | Up | zend_get_compiled_script_encoding


zend_get_compiled_script_encoding

zend_get_compiled_script_encoding -- ...

Description

#include <zend_compile.h>

char* zend_get_compiled_script_encoding ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_compiled_lineno | Up | zend_get_compiled_variable_name


zend_get_compiled_variable_name

zend_get_compiled_variable_name -- ...

Description

#include <zend_compile.h>

char* zend_get_compiled_variable_name ( zend_op_array* op_array, zend_uint var, int* name_len )

...

Parameters

op_array

...

var

...

name_len

...

Return Values

...

Prev | Home | Next
zend_get_compiled_script_encoding | Up | zend_get_compiled_variable_value


zend_get_compiled_variable_value

zend_get_compiled_variable_value -- ...

Description

#include <zend_execute.h>

zval** zend_get_compiled_variable_value ( zend_execute_data* execute_data_ptr, zend_uint var )

...

Parameters

execute_data_ptr

...

var

...

Return Values

...

Prev | Home | Next
zend_get_compiled_variable_name | Up | zend_get_configuration_directive


zend_get_configuration_directive

zend_get_configuration_directive -- ...

Description

#include <zend.h>

int zend_get_configuration_directive ( char* name, uint name_length, zval* contents )

...

Parameters

name

...

name_length

...

contents

...

Return Values

...

Prev | Home | Next
zend_get_compiled_variable_value | Up | zend_get_constant


zend_get_constant

zend_get_constant -- ...

Description

#include <zend_constants.h>

int zend_get_constant ( char* name, uint name_len, zval* result, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

result

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_get_configuration_directive | Up | zend_get_error_exception


zend_get_error_exception

zend_get_error_exception -- ...

Description

#include <zend_exceptions.h>

zend_class_entry* zend_get_error_exception ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_constant | Up | zend_get_executed_filename


zend_get_executed_filename

zend_get_executed_filename -- ...

Description

#include <zend_execute.h>

char* zend_get_executed_filename ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_error_exception | Up | zend_get_executed_lineno


zend_get_executed_lineno

zend_get_executed_lineno -- ...

Description

#include <zend_execute.h>

uint zend_get_executed_lineno ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_executed_filename | Up | zend_get_hash_value


zend_get_hash_value

zend_get_hash_value -- ...

Description

#include <zend_hash.h>

ulong zend_get_hash_value ( char* arKey, uint nKeyLength )

...

Parameters

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_get_executed_lineno | Up | zend_get_module_started


zend_get_module_started

zend_get_module_started -- ...

Description

#include <zend_API.h>

int zend_get_module_started ( char* module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
zend_get_hash_value | Up | zend_get_module_version


zend_get_module_version

zend_get_module_version -- ...

Description

#include <zend_API.h>

char* zend_get_module_version ( char* module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
zend_get_module_started | Up | zend_get_object_classname


zend_get_object_classname

zend_get_object_classname -- ...

Description

#include <zend_API.h>

int zend_get_object_classname ( zval* object, char** class_name, zend_uint* class_name_len, magic TSRMLS_DC )

...

Parameters

object

...

class_name

...

class_name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_get_module_version | Up | zend_get_parameters_array_ex


zend_get_parameters

zend_get_parameters -- ...

Description

#include <zend_API.h>

int zend_get_parameters ( int ht, int param_count, ... )

...

Parameters

ht

...

param_count

...

...

...

Return Values

...

Prev | Home | Next
zend_get_parameters_ex | Up | zend_get_scanned_file_offset


zend_get_parameters_array

zend_get_parameters_array -- ...

Description

#include <zend_API.h>

int zend_get_parameters_array ( int ht, int param_count, zval** argument_array )

...

Parameters

ht

...

param_count

...

argument_array

...

Return Values

...

Prev | Home | Next
zend_get_parameters_array_ex | Up | zend_get_parameters_ex


zend_get_parameters_array_ex

zend_get_parameters_array_ex -- ...

Description

#include <zend_API.h>

int zend_get_parameters_array_ex ( int param_count, zval*** argument_array )

...

Parameters

param_count

...

argument_array

...

Return Values

...

Prev | Home | Next
zend_get_object_classname | Up | zend_get_parameters_array


zend_get_parameters_ex

zend_get_parameters_ex -- ...

Description

#include <zend_API.h>

int zend_get_parameters_ex ( int param_count, ... )

...

Parameters

param_count

...

...

...

Return Values

...

Prev | Home | Next
zend_get_parameters_array | Up | zend_get_parameters


zend_get_scanned_file_offset

zend_get_scanned_file_offset -- ...

Description

#include <zend_compile.h>

int zend_get_scanned_file_offset ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_get_parameters | Up | zend_get_std_object_handlers


zend_get_std_object_handlers

zend_get_std_object_handlers -- ...

Description

#include <zend_objects_API.h>

zend_object_handlers* zend_get_std_object_handlers ( magic )

...

Parameters

...

Return Values

...

Prev | Home | Next
zend_get_scanned_file_offset | Up | zend_get_unified_string_type


zend_get_unified_string_type

zend_get_unified_string_type -- ...

Description

#include <zend_API.h>

zend_uchar zend_get_unified_string_type ( int num_args, magic TSRMLS_DC, ... )

...

Parameters

num_args

...

TSRMLS_DC

...

...

...

Return Values

...

Prev | Home | Next
zend_get_std_object_handlers | Up | zend_get_user_opcode_handler


zend_get_user_opcode_handler

zend_get_user_opcode_handler -- ...

Description

#include <zend_execute.h>

opcode_handler_t zend_get_user_opcode_handler ( zend_uchar opcode )

...

Parameters

opcode

...

Return Values

...

Prev | Home | Next
zend_get_unified_string_type | Up | zend_get_zval_ptr_ptr


zend_get_zval_ptr

zend_get_zval_ptr -- ...

Description

#include <zend_execute.h>

zval* zend_get_zval_ptr ( znode* node, temp_variable* Ts, zend_free_op* should_free, int type, magic TSRMLS_DC )

...

Parameters

node

...

Ts

...

should_free

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_get_zval_ptr_ptr | Up | zend_hash_add_empty_element


zend_get_zval_ptr_ptr

zend_get_zval_ptr_ptr -- ...

Description

#include <zend_execute.h>

zval** zend_get_zval_ptr_ptr ( znode* node, temp_variable* Ts, zend_free_op* should_free, int type, magic TSRMLS_DC )

...

Parameters

node

...

Ts

...

should_free

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_get_user_opcode_handler | Up | zend_get_zval_ptr


zend_hash_add

zend_hash_add -- ...

Description

#include <zend_hash.h>

int zend_hash_add ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_add_empty_element | Up | zend_hash_apply_with_argument


zend_hash_add_empty_element

zend_hash_add_empty_element -- ...

Description

#include <zend_hash.h>

int zend_hash_add_empty_element ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_get_zval_ptr | Up | zend_hash_add


zend_hash_apply

zend_hash_apply -- ...

Description

#include <zend_hash.h>

void zend_hash_apply ( HashTable* ht, apply_func_t apply_func, magic TSRMLS_DC )

...

Parameters

ht

...

apply_func

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_apply_with_arguments | Up | zend_hash_clean


zend_hash_apply_with_argument

zend_hash_apply_with_argument -- ...

Description

#include <zend_hash.h>

void zend_hash_apply_with_argument ( HashTable* ht, apply_func_arg_t apply_func, void* , magic TSRMLS_DC )

...

Parameters

ht

...

apply_func

...

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_add | Up | zend_hash_apply_with_arguments


zend_hash_apply_with_arguments

zend_hash_apply_with_arguments -- ...

Description

#include <zend_hash.h>

void zend_hash_apply_with_arguments ( HashTable* ht, apply_func_args_t apply_func, int, ... )

...

Parameters

ht

...

apply_func

...

int

...

...

...

Return Values

...

Prev | Home | Next
zend_hash_apply_with_argument | Up | zend_hash_apply


zend_hash_clean

zend_hash_clean -- ...

Description

#include <zend_hash.h>

void zend_hash_clean ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_apply | Up | zend_hash_compare


zend_hash_compare

zend_hash_compare -- ...

Description

#include <zend_hash.h>

int zend_hash_compare ( HashTable* ht1, HashTable* ht2, compare_func_t compar, zend_bool ordered, magic TSRMLS_DC )

...

Parameters

ht1

...

ht2

...

compar

...

ordered

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_clean | Up | zend_hash_copy


zend_hash_copy

zend_hash_copy -- ...

Description

#include <zend_hash.h>

void zend_hash_copy ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size )

...

Parameters

target

...

source

...

pCopyConstructor

...

tmp

...

size

...

Return Values

...

Prev | Home | Next
zend_hash_compare | Up | zend_hash_del_key_or_index


zend_hash_del

zend_hash_del -- ...

Description

#include <zend_hash.h>

int zend_hash_del ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_hash_del_key_or_index | Up | zend_hash_destroy


zend_hash_del_key_or_index

zend_hash_del_key_or_index -- ...

Description

#include <zend_hash.h>

int zend_hash_del_key_or_index ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, int flag )

...

Parameters

ht

...

arKey

...

nKeyLength

...

h

...

flag

...

Return Values

...

Prev | Home | Next
zend_hash_copy | Up | zend_hash_del


zend_hash_destroy

zend_hash_destroy -- ...

Description

#include <zend_hash.h>

void zend_hash_destroy ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_del | Up | zend_hash_exists


zend_hash_exists

zend_hash_exists -- ...

Description

#include <zend_hash.h>

int zend_hash_exists ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_hash_destroy | Up | zend_hash_find


zend_hash_find

zend_hash_find -- ...

Description

#include <zend_hash.h>

int zend_hash_find ( HashTable* ht, char* arKey, uint nKeyLength, void** pData )

...

Parameters

ht

...

arKey

...

nKeyLength

...

pData

...

Return Values

...

Prev | Home | Next
zend_hash_exists | Up | zend_hash_func


zend_hash_func

zend_hash_func -- ...

Description

#include <zend_hash.h>

ulong zend_hash_func ( char* arKey, uint nKeyLength )

...

Parameters

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_hash_find | Up | zend_hash_get_current_data_ex


zend_hash_get_current_data

zend_hash_get_current_data -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_data ( HashTable* ht, void** pData )

...

Parameters

ht

...

pData

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_data_ex | Up | zend_hash_get_current_key_ex


zend_hash_get_current_data_ex

zend_hash_get_current_data_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_data_ex ( HashTable* ht, void** pData, HashPosition* pos )

...

Parameters

ht

...

pData

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_func | Up | zend_hash_get_current_data


zend_hash_get_current_key

zend_hash_get_current_key -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_key ( HashTable* ht, char** str_index, ulong* num_index, zend_bool duplicate )

...

Parameters

ht

...

str_index

...

num_index

...

duplicate

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_key_type | Up | zend_hash_graceful_destroy


zend_hash_get_current_key_ex

zend_hash_get_current_key_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_key_ex ( HashTable* ht, char** str_index, uint* str_length, ulong* num_index, zend_bool duplicate, HashPosition* pos )

...

Parameters

ht

...

str_index

...

str_length

...

num_index

...

duplicate

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_data | Up | zend_hash_get_current_key_type_ex


zend_hash_get_current_key_type

zend_hash_get_current_key_type -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_key_type ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_key_type_ex | Up | zend_hash_get_current_key


zend_hash_get_current_key_type_ex

zend_hash_get_current_key_type_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_get_current_key_type_ex ( HashTable* ht, HashPosition* pos )

...

Parameters

ht

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_key_ex | Up | zend_hash_get_current_key_type


zend_hash_graceful_destroy

zend_hash_graceful_destroy -- ...

Description

#include <zend_hash.h>

void zend_hash_graceful_destroy ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_get_current_key | Up | zend_hash_graceful_reverse_destroy


zend_hash_graceful_reverse_destroy

zend_hash_graceful_reverse_destroy -- ...

Description

#include <zend_hash.h>

void zend_hash_graceful_reverse_destroy ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_graceful_destroy | Up | zend_hash_index_del


zend_hash_index_del

zend_hash_index_del -- ...

Description

#include <zend_hash.h>

int zend_hash_index_del ( HashTable* ht, ulong h )

...

Parameters

ht

...

h

...

Return Values

...

Prev | Home | Next
zend_hash_graceful_reverse_destroy | Up | zend_hash_index_exists


zend_hash_index_exists

zend_hash_index_exists -- ...

Description

#include <zend_hash.h>

int zend_hash_index_exists ( HashTable* ht, ulong h )

...

Parameters

ht

...

h

...

Return Values

...

Prev | Home | Next
zend_hash_index_del | Up | zend_hash_index_find


zend_hash_index_find

zend_hash_index_find -- ...

Description

#include <zend_hash.h>

int zend_hash_index_find ( HashTable* ht, ulong h, void** pData )

...

Parameters

ht

...

h

...

pData

...

Return Values

...

Prev | Home | Next
zend_hash_index_exists | Up | zend_hash_index_update


zend_hash_index_update

zend_hash_index_update -- ...

Description

#include <zend_hash.h>

int zend_hash_index_update ( HashTable* ht, ulong h, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

h

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_index_find | Up | zend_hash_init_ex


zend_hash_init

zend_hash_init -- ...

Description

#include <zend_hash.h>

int zend_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent )

...

Parameters

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

Return Values

...

Prev | Home | Next
zend_hash_init_ex | Up | zend_hash_internal_pointer_end_ex


zend_hash_init_ex

zend_hash_init_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool bApplyProtection )

...

Parameters

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

bApplyProtection

...

Return Values

...

Prev | Home | Next
zend_hash_index_update | Up | zend_hash_init


zend_hash_internal_pointer_end

zend_hash_internal_pointer_end -- ...

Description

#include <zend_hash.h>

void zend_hash_internal_pointer_end ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_internal_pointer_end_ex | Up | zend_hash_internal_pointer_reset_ex


zend_hash_internal_pointer_end_ex

zend_hash_internal_pointer_end_ex -- ...

Description

#include <zend_hash.h>

void zend_hash_internal_pointer_end_ex ( HashTable* ht, HashPosition* pos )

...

Parameters

ht

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_init | Up | zend_hash_internal_pointer_end


zend_hash_internal_pointer_reset

zend_hash_internal_pointer_reset -- ...

Description

#include <zend_hash.h>

void zend_hash_internal_pointer_reset ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_internal_pointer_reset_ex | Up | zend_hash_merge_ex


zend_hash_internal_pointer_reset_ex

zend_hash_internal_pointer_reset_ex -- ...

Description

#include <zend_hash.h>

void zend_hash_internal_pointer_reset_ex ( HashTable* ht, HashPosition* pos )

...

Parameters

ht

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_internal_pointer_end | Up | zend_hash_internal_pointer_reset


zend_hash_merge

zend_hash_merge -- ...

Description

#include <zend_hash.h>

void zend_hash_merge ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size, int overwrite )

...

Parameters

target

...

source

...

pCopyConstructor

...

tmp

...

size

...

overwrite

...

Return Values

...

Prev | Home | Next
zend_hash_merge_ex | Up | zend_hash_minmax


zend_hash_merge_ex

zend_hash_merge_ex -- ...

Description

#include <zend_hash.h>

void zend_hash_merge_ex ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, uint size, merge_checker_func_t pMergeSource, void* pParam )

...

Parameters

target

...

source

...

pCopyConstructor

...

size

...

pMergeSource

...

pParam

...

Return Values

...

Prev | Home | Next
zend_hash_internal_pointer_reset | Up | zend_hash_merge


zend_hash_minmax

zend_hash_minmax -- ...

Description

#include <zend_hash.h>

int zend_hash_minmax ( HashTable* ht, compare_func_t compar, int flag, void** pData, magic TSRMLS_DC )

...

Parameters

ht

...

compar

...

flag

...

pData

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_merge | Up | zend_hash_move_backwards_ex


zend_hash_move_backwards

zend_hash_move_backwards -- ...

Description

#include <zend_hash.h>

int zend_hash_move_backwards ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_move_backwards_ex | Up | zend_hash_move_forward_ex


zend_hash_move_backwards_ex

zend_hash_move_backwards_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_move_backwards_ex ( HashTable* ht, HashPosition* pos )

...

Parameters

ht

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_minmax | Up | zend_hash_move_backwards


zend_hash_move_forward

zend_hash_move_forward -- ...

Description

#include <zend_hash.h>

int zend_hash_move_forward ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_move_forward_ex | Up | zend_hash_next_free_element


zend_hash_move_forward_ex

zend_hash_move_forward_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_move_forward_ex ( HashTable* ht, HashPosition* pos )

...

Parameters

ht

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_move_backwards | Up | zend_hash_move_forward


zend_hash_next_free_element

zend_hash_next_free_element -- ...

Description

#include <zend_hash.h>

ulong zend_hash_next_free_element ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_move_forward | Up | zend_hash_next_index_insert


zend_hash_next_index_insert

zend_hash_next_index_insert -- ...

Description

#include <zend_hash.h>

int zend_hash_next_index_insert ( HashTable* ht, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_next_free_element | Up | zend_hash_num_elements


zend_hash_num_elements

zend_hash_num_elements -- ...

Description

#include <zend_hash.h>

int zend_hash_num_elements ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_next_index_insert | Up | zend_hash_quick_add


zend_hash_quick_add

zend_hash_quick_add -- ...

Description

#include <zend_hash.h>

int zend_hash_quick_add ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_num_elements | Up | zend_hash_quick_exists


zend_hash_quick_exists

zend_hash_quick_exists -- ...

Description

#include <zend_hash.h>

int zend_hash_quick_exists ( HashTable* ht, char* arKey, uint nKeyLength, ulong h )

...

Parameters

ht

...

arKey

...

nKeyLength

...

h

...

Return Values

...

Prev | Home | Next
zend_hash_quick_add | Up | zend_hash_quick_find


zend_hash_quick_find

zend_hash_quick_find -- ...

Description

#include <zend_hash.h>

int zend_hash_quick_find ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void** pData )

...

Parameters

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

Return Values

...

Prev | Home | Next
zend_hash_quick_exists | Up | zend_hash_quick_update


zend_hash_quick_update

zend_hash_quick_update -- ...

Description

#include <zend_hash.h>

int zend_hash_quick_update ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_quick_find | Up | zend_hash_rehash


zend_hash_rehash

zend_hash_rehash -- ...

Description

#include <zend_hash.h>

int zend_hash_rehash ( HashTable* ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
zend_hash_quick_update | Up | zend_hash_reverse_apply


zend_hash_reverse_apply

zend_hash_reverse_apply -- ...

Description

#include <zend_hash.h>

void zend_hash_reverse_apply ( HashTable* ht, apply_func_t apply_func, magic TSRMLS_DC )

...

Parameters

ht

...

apply_func

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_rehash | Up | zend_hash_sort


zend_hash_sort

zend_hash_sort -- ...

Description

#include <zend_hash.h>

int zend_hash_sort ( HashTable* ht, sort_func_t sort_func, compare_func_t compare_func, int renumber, magic TSRMLS_DC )

...

Parameters

ht

...

sort_func

...

compare_func

...

renumber

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_reverse_apply | Up | zend_hash_update_current_key_ex


zend_hash_update

zend_hash_update -- ...

Description

#include <zend_hash.h>

int zend_hash_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_hash_update_current_key | Up | zend_highlight


zend_hash_update_current_key

zend_hash_update_current_key -- ...

Description

#include <zend_hash.h>

int zend_hash_update_current_key ( HashTable* ht, int key_type, char* str_index, uint str_length, ulong num_index )

...

Parameters

ht

...

key_type

...

str_index

...

str_length

...

num_index

...

Return Values

...

Prev | Home | Next
zend_hash_update_current_key_ex | Up | zend_hash_update


zend_hash_update_current_key_ex

zend_hash_update_current_key_ex -- ...

Description

#include <zend_hash.h>

int zend_hash_update_current_key_ex ( HashTable* ht, int key_type, char* str_index, uint str_length, ulong num_index, HashPosition* pos )

...

Parameters

ht

...

key_type

...

str_index

...

str_length

...

num_index

...

pos

...

Return Values

...

Prev | Home | Next
zend_hash_sort | Up | zend_hash_update_current_key


zend_highlight

zend_highlight -- ...

Description

#include <zend_highlight.h>

void zend_highlight ( zend_syntax_highlighter_ini* syntax_highlighter_ini, magic TSRMLS_DC )

...

Parameters

syntax_highlighter_ini

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_hash_update | Up | zend_html_putc


zend_html_putc

zend_html_putc -- ...

Description

#include <zend_highlight.h>

void zend_html_putc ( char c )

...

Parameters

c

...

Return Values

...

Prev | Home | Next
zend_highlight | Up | zend_html_puts


zend_html_puts

zend_html_puts -- ...

Description

#include <zend_highlight.h>

void zend_html_puts ( const char* s, uint len, magic TSRMLS_DC )

...

Parameters

s

...

len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_html_putc | Up | zend_ini_deactivate


zend_ini_deactivate

zend_ini_deactivate -- ...

Description

#include <zend_ini.h>

int zend_ini_deactivate ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_html_puts | Up | zend_ini_double


zend_ini_double

zend_ini_double -- ...

Description

#include <zend_ini.h>

double zend_ini_double ( char* name, uint name_length, int orig )

...

Parameters

name

...

name_length

...

orig

...

Return Values

...

Prev | Home | Next
zend_ini_deactivate | Up | zend_ini_global_shutdown


zend_ini_global_shutdown

zend_ini_global_shutdown -- ...

Description

#include <zend_ini.h>

int zend_ini_global_shutdown ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_ini_double | Up | zend_ini_long


zend_ini_long

zend_ini_long -- ...

Description

#include <zend_ini.h>

long zend_ini_long ( char* name, uint name_length, int orig )

...

Parameters

name

...

name_length

...

orig

...

Return Values

...

Prev | Home | Next
zend_ini_global_shutdown | Up | zend_ini_refresh_caches


zend_ini_refresh_caches

zend_ini_refresh_caches -- ...

Description

#include <zend_ini.h>

void zend_ini_refresh_caches ( int stage, magic TSRMLS_DC )

...

Parameters

stage

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_ini_long | Up | zend_ini_register_displayer


zend_ini_register_displayer

zend_ini_register_displayer -- ...

Description

#include <zend_ini.h>

int zend_ini_register_displayer ( char* name, uint name_length, void (*displayer )

...

Parameters

name

...

name_length

...

(*displayer

...

Return Values

...

Prev | Home | Next
zend_ini_refresh_caches | Up | zend_ini_shutdown


zend_ini_shutdown

zend_ini_shutdown -- ...

Description

#include <zend_ini.h>

int zend_ini_shutdown ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_ini_register_displayer | Up | zend_ini_sort_entries


zend_ini_sort_entries

zend_ini_sort_entries -- ...

Description

#include <zend_ini.h>

void zend_ini_sort_entries ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_ini_shutdown | Up | zend_ini_startup


zend_ini_startup

zend_ini_startup -- ...

Description

#include <zend_ini.h>

int zend_ini_startup ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_ini_sort_entries | Up | zend_ini_string


zend_ini_string

zend_ini_string -- ...

Description

#include <zend_ini.h>

char* zend_ini_string ( char* name, uint name_length, int orig )

...

Parameters

name

...

name_length

...

orig

...

Return Values

...

Prev | Home | Next
zend_ini_startup | Up | zend_initialize_class_data


zend_initialize_class_data

zend_initialize_class_data -- ...

Description

#include <zend_compile.h>

void zend_initialize_class_data ( zend_class_entry* ce, zend_bool nullify_handlers, magic TSRMLS_DC )

...

Parameters

ce

...

nullify_handlers

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_ini_string | Up | zend_is_auto_global


zend_is_auto_global

zend_is_auto_global -- ...

Description

#include <zend_compile.h>

zend_bool zend_is_auto_global ( char* name, uint name_len, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_initialize_class_data | Up | zend_is_callable_ex


zend_is_callable

zend_is_callable -- ...

Description

#include <zend_API.h>

zend_bool zend_is_callable ( zval* callable, uint check_flags, zval* callable_name )

...

Parameters

callable

...

check_flags

...

callable_name

...

Return Values

...

Prev | Home | Next
zend_is_callable_ex | Up | zend_is_compiling


zend_is_callable_ex

zend_is_callable_ex -- ...

Description

#include <zend_API.h>

zend_bool zend_is_callable_ex ( zval* callable, uint check_flags, zval* callable_name, zend_class_entry** ce_ptr, zend_function** fptr_ptr, zval*** zobj_ptr_ptr, magic TSRMLS_DC )

...

Parameters

callable

...

check_flags

...

callable_name

...

ce_ptr

...

fptr_ptr

...

zobj_ptr_ptr

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_is_auto_global | Up | zend_is_callable


zend_is_compiling

zend_is_compiling -- ...

Description

#include <zend_compile.h>

zend_bool zend_is_compiling ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_is_callable | Up | zend_is_executing


zend_is_executing

zend_is_executing -- ...

Description

#include <zend_execute.h>

zend_bool zend_is_executing ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_is_compiling | Up | zend_is_true


zend_is_true

zend_is_true -- ...

Description

#include <zend_execute.h>

int zend_is_true ( zval* op )

...

Parameters

op

...

Return Values

...

Prev | Home | Next
zend_is_executing | Up | zend_is_valid_identifier


zend_is_valid_identifier

zend_is_valid_identifier -- ...

Description

#include <zend_unicode.h>

int zend_is_valid_identifier ( UChar* ident, int32_t ident_len )

...

Parameters

ident

...

ident_len

...

Return Values

...

Prev | Home | Next
zend_is_true | Up | zend_list_addref


zend_list_addref

zend_list_addref -- ...

Description

#include <zend_list.h>

int zend_list_addref ( int id )

...

Parameters

id

...

Return Values

...

Prev | Home | Next
zend_is_valid_identifier | Up | zend_list_delete


zend_list_delete

zend_list_delete -- ...

Description

#include <zend_list.h>

int zend_list_delete ( int id )

...

Parameters

id

...

Return Values

...

Prev | Home | Next
zend_list_addref | Up | zend_list_find


zend_list_find

zend_list_find -- ...

Description

#include <zend_list.h>

void* zend_list_find ( int id, int* type )

...

Parameters

id

...

type

...

Return Values

...

Prev | Home | Next
zend_list_delete | Up | zend_list_insert


zend_list_insert

zend_list_insert -- ...

Description

#include <zend_list.h>

int zend_list_insert ( void* ptr, int type )

...

Parameters

ptr

...

type

...

Return Values

...

Prev | Home | Next
zend_list_find | Up | zend_lookup_class


zend_lookup_class

zend_lookup_class -- ...

Description

#include <zend_execute.h>

int zend_lookup_class ( char* name, int name_length, zend_class_entry*** ce, magic TSRMLS_DC )

...

Parameters

name

...

name_length

...

ce

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_list_insert | Up | zend_make_callable


zend_make_callable

zend_make_callable -- ...

Description

#include <zend_API.h>

zend_bool zend_make_callable ( zval* callable, zval* callable_name, magic TSRMLS_DC )

...

Parameters

callable

...

callable_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_lookup_class | Up | zend_make_compiled_string_description


zend_make_compiled_string_description

zend_make_compiled_string_description -- ...

Description

#include <zend_compile.h>

char* zend_make_compiled_string_description ( char* name, magic TSRMLS_DC )

...

Parameters

name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_make_callable | Up | zend_make_printable_zval


zend_make_printable_zval

zend_make_printable_zval -- ...

Description

#include <zend.h>

void zend_make_printable_zval ( zval* expr, zval* expr_copy, int* use_copy )

...

Parameters

expr

...

expr_copy

...

use_copy

...

Return Values

...

Prev | Home | Next
zend_make_compiled_string_description | Up | zend_make_string_zval


zend_make_string_zval

zend_make_string_zval -- ...

Description

#include <zend.h>

void zend_make_string_zval ( zval* expr, zval* expr_copy, int* use_copy )

...

Parameters

expr

...

expr_copy

...

use_copy

...

Return Values

...

Prev | Home | Next
zend_make_printable_zval | Up | zend_make_unicode_zval


zend_make_unicode_zval

zend_make_unicode_zval -- ...

Description

#include <zend.h>

void zend_make_unicode_zval ( zval* expr, zval* expr_copy, int* use_copy )

...

Parameters

expr

...

expr_copy

...

use_copy

...

Return Values

...

Prev | Home | Next
zend_make_string_zval | Up | zend_mangle_property_name


zend_mangle_property_name

zend_mangle_property_name -- ...

Description

#include <zend_compile.h>

void zend_mangle_property_name ( char** dest, int* dest_length, char* src1, int src1_length, char* src2, int src2_length, int internal )

...

Parameters

dest

...

dest_length

...

src1

...

src1_length

...

src2

...

src2_length

...

internal

...

Return Values

...

Prev | Home | Next
zend_make_unicode_zval | Up | zend_merge_properties


zend_merge_properties

zend_merge_properties -- ...

Description

#include <zend_API.h>

void zend_merge_properties ( zval* obj, HashTable* properties, int destroy_ht, magic TSRMLS_DC )

...

Parameters

obj

...

properties

...

destroy_ht

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_mangle_property_name | Up | zend_message_dispatcher


zend_message_dispatcher

zend_message_dispatcher -- ...

Description

#include <zend.h>

void zend_message_dispatcher ( long message, void* data )

...

Parameters

message

...

data

...

Return Values

...

Prev | Home | Next
zend_merge_properties | Up | zend_normalize_identifier


zend_normalize_identifier

zend_normalize_identifier -- ...

Description

#include <zend_unicode.h>

int zend_normalize_identifier ( UChar** dest, int32_t* dest_len, UChar* ident, int32_t ident_len, zend_bool fold_case )

...

Parameters

dest

...

dest_len

...

ident

...

ident_len

...

fold_case

...

Return Values

...

Prev | Home | Next
zend_message_dispatcher | Up | zend_object_create_proxy


zend_object_create_proxy

zend_object_create_proxy -- ...

Description

#include <zend_objects_API.h>

zval* zend_object_create_proxy ( zval* object, zval* member, magic TSRMLS_DC )

...

Parameters

object

...

member

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_normalize_identifier | Up | zend_object_store_ctor_failed


zend_object_store_ctor_failed

zend_object_store_ctor_failed -- ...

Description

#include <zend_objects_API.h>

void zend_object_store_ctor_failed ( zval* zobject, magic TSRMLS_DC )

...

Parameters

zobject

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_object_create_proxy | Up | zend_object_store_get_object


zend_object_store_get_object

zend_object_store_get_object -- ...

Description

#include <zend_objects_API.h>

void* zend_object_store_get_object ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_object_store_ctor_failed | Up | zend_object_store_set_object


zend_object_store_set_object

zend_object_store_set_object -- ...

Description

#include <zend_objects_API.h>

void zend_object_store_set_object ( zval* zobject, void* object, magic TSRMLS_DC )

...

Parameters

zobject

...

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_object_store_get_object | Up | zend_objects_clone_members


zend_objects_clone_members

zend_objects_clone_members -- ...

Description

#include <zend_objects.h>

void zend_objects_clone_members ( zend_object* new_object, zend_object_value new_obj_val, zend_object* old_object, zend_object_handle handle, magic TSRMLS_DC )

...

Parameters

new_object

...

new_obj_val

...

old_object

...

handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_object_store_set_object | Up | zend_objects_clone_obj


zend_objects_clone_obj

zend_objects_clone_obj -- ...

Description

#include <zend_objects.h>

zend_object_value zend_objects_clone_obj ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_clone_members | Up | zend_objects_destroy_object


zend_objects_destroy_object

zend_objects_destroy_object -- ...

Description

#include <zend_objects.h>

void zend_objects_destroy_object ( zend_object* object, zend_object_handle handle, magic TSRMLS_DC )

...

Parameters

object

...

handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_clone_obj | Up | zend_objects_free_object_storage


zend_objects_free_object_storage

zend_objects_free_object_storage -- ...

Description

#include <zend_objects.h>

void zend_objects_free_object_storage ( zend_object* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_destroy_object | Up | zend_objects_get_address


zend_objects_get_address

zend_objects_get_address -- ...

Description

#include <zend_objects.h>

zend_object* zend_objects_get_address ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_free_object_storage | Up | zend_objects_new


zend_objects_new

zend_objects_new -- ...

Description

#include <zend_objects.h>

zend_object_value zend_objects_new ( zend_object** object, zend_class_entry* class_type, magic TSRMLS_DC )

...

Parameters

object

...

class_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_get_address | Up | zend_objects_store_add_ref


zend_objects_store_add_ref

zend_objects_store_add_ref -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_add_ref ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_new | Up | zend_objects_store_call_destructors


zend_objects_store_call_destructors

zend_objects_store_call_destructors -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_call_destructors ( zend_objects_store* objects, magic TSRMLS_DC )

...

Parameters

objects

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_add_ref | Up | zend_objects_store_clone_obj


zend_objects_store_clone_obj

zend_objects_store_clone_obj -- ...

Description

#include <zend_objects_API.h>

zend_object_value zend_objects_store_clone_obj ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_call_destructors | Up | zend_objects_store_del_ref


zend_objects_store_del_ref

zend_objects_store_del_ref -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_del_ref ( zval* object, magic TSRMLS_DC )

...

Parameters

object

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_clone_obj | Up | zend_objects_store_destroy


zend_objects_store_destroy

zend_objects_store_destroy -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_destroy ( zend_objects_store* objects )

...

Parameters

objects

...

Return Values

...

Prev | Home | Next
zend_objects_store_del_ref | Up | zend_objects_store_free_object_storage


zend_objects_store_free_object_storage

zend_objects_store_free_object_storage -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_free_object_storage ( zend_objects_store* objects, magic TSRMLS_DC )

...

Parameters

objects

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_destroy | Up | zend_objects_store_init


zend_objects_store_init

zend_objects_store_init -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_init ( zend_objects_store* objects, zend_uint init_size )

...

Parameters

objects

...

init_size

...

Return Values

...

Prev | Home | Next
zend_objects_store_free_object_storage | Up | zend_objects_store_mark_destructed


zend_objects_store_mark_destructed

zend_objects_store_mark_destructed -- ...

Description

#include <zend_objects_API.h>

void zend_objects_store_mark_destructed ( zend_objects_store* objects, magic TSRMLS_DC )

...

Parameters

objects

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_init | Up | zend_objects_store_put


zend_objects_store_put

zend_objects_store_put -- ...

Description

#include <zend_objects_API.h>

zend_object_handle zend_objects_store_put ( void* object, zend_objects_store_dtor_t dtor, zend_objects_free_object_storage_t storage, zend_objects_store_clone_t clone, magic TSRMLS_DC )

...

Parameters

object

...

dtor

...

storage

...

clone

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_objects_store_mark_destructed | Up | zend_output_debug_string


zend_output_debug_string

zend_output_debug_string -- ...

Description

#include <zend.h>

void zend_output_debug_string ( zend_bool trigger_break, char* format, ... )

...

Parameters

trigger_break

...

format

...

...

...

Return Values

...

Prev | Home | Next
zend_objects_store_put | Up | zend_parse_ini_file


zend_parse_ini_file

zend_parse_ini_file -- ...

Description

#include <zend_ini.h>

int zend_parse_ini_file ( zend_file_handle* fh, zend_bool unbuffered_errors, zend_ini_parser_cb_t ini_parser_cb, void* arg )

...

Parameters

fh

...

unbuffered_errors

...

ini_parser_cb

...

arg

...

Return Values

...

Prev | Home | Next
zend_output_debug_string | Up | zend_parse_method_parameters_ex


zend_parse_method_parameters

zend_parse_method_parameters -- ...

Description

#include <zend_API.h>

int zend_parse_method_parameters ( int num_args, magic TSRMLS_DC, zval* this_ptr, char* type_spec, ... )

...

Parameters

num_args

...

TSRMLS_DC

...

this_ptr

...

type_spec

...

...

...

Return Values

...

Prev | Home | Next
zend_parse_method_parameters_ex | Up | zend_parse_parameters_ex


zend_parse_method_parameters_ex

zend_parse_method_parameters_ex -- ...

Description

#include <zend_API.h>

int zend_parse_method_parameters_ex ( int flags, int num_args, magic TSRMLS_DC, zval* this_ptr, char* type_spec, ... )

...

Parameters

flags

...

num_args

...

TSRMLS_DC

...

this_ptr

...

type_spec

...

...

...

Return Values

...

Prev | Home | Next
zend_parse_ini_file | Up | zend_parse_method_parameters


zend_parse_parameters

zend_parse_parameters -- ...

Description

#include <zend_API.h>

int zend_parse_parameters ( int num_args, magic TSRMLS_DC, char* type_spec, ... )

...

Parameters

num_args

...

TSRMLS_DC

...

type_spec

...

...

...

Return Values

...

Prev | Home | Next
zend_parse_parameters_ex | Up | zend_prepare_scanner_converters


zend_parse_parameters_ex

zend_parse_parameters_ex -- ...

Description

#include <zend_API.h>

int zend_parse_parameters_ex ( int flags, int num_args, magic TSRMLS_DC, char* type_spec, ... )

...

Parameters

flags

...

num_args

...

TSRMLS_DC

...

type_spec

...

...

...

Return Values

...

Prev | Home | Next
zend_parse_method_parameters | Up | zend_parse_parameters


zend_prepare_scanner_converters

zend_prepare_scanner_converters -- ...

Description

#include <zend_compile.h>

int zend_prepare_scanner_converters ( const char* onetime_encoding, int run_time, magic TSRMLS_DC )

...

Parameters

onetime_encoding

...

run_time

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_parse_parameters | Up | zend_print_flat_zval_r


zend_print_flat_zval_r

zend_print_flat_zval_r -- ...

Description

#include <zend.h>

void zend_print_flat_zval_r ( zval* expr, magic TSRMLS_DC )

...

Parameters

expr

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_prepare_scanner_converters | Up | zend_print_variable


zend_print_variable

zend_print_variable -- ...

Description

#include <zend_variables.h>

int zend_print_variable ( zval* var )

...

Parameters

var

...

Return Values

...

Prev | Home | Next
zend_print_flat_zval_r | Up | zend_print_zval_ex


zend_print_zval

zend_print_zval -- ...

Description

#include <zend.h>

int zend_print_zval ( zval* expr, int indent )

...

Parameters

expr

...

indent

...

Return Values

...

Prev | Home | Next
zend_print_zval_r | Up | zend_qsort


zend_print_zval_ex

zend_print_zval_ex -- ...

Description

#include <zend.h>

int zend_print_zval_ex ( zend_write_func_t write_func, zval* expr, int indent )

...

Parameters

write_func

...

expr

...

indent

...

Return Values

...

Prev | Home | Next
zend_print_variable | Up | zend_print_zval_r_ex


zend_print_zval_r

zend_print_zval_r -- ...

Description

#include <zend.h>

void zend_print_zval_r ( zval* expr, int indent, magic TSRMLS_DC )

...

Parameters

expr

...

indent

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_print_zval_r_ex | Up | zend_print_zval


zend_print_zval_r_ex

zend_print_zval_r_ex -- ...

Description

#include <zend.h>

void zend_print_zval_r_ex ( zend_write_func_t write_func, zval* expr, int indent, magic TSRMLS_DC )

...

Parameters

write_func

...

expr

...

indent

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_print_zval_ex | Up | zend_print_zval_r


zend_qsort

zend_qsort -- ...

Description

#include <zend_qsort.h>

void zend_qsort ( void* base, size_t nmemb, size_t siz, compare_func_t compare, magic TSRMLS_DC )

...

Parameters

base

...

nmemb

...

siz

...

compare

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_print_zval | Up | zend_read_property


zend_read_property

zend_read_property -- ...

Description

#include <zend_API.h>

zval* zend_read_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zend_bool silent, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

silent

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_qsort | Up | zend_read_static_property


zend_read_static_property

zend_read_static_property -- ...

Description

#include <zend_API.h>

zval* zend_read_static_property ( zend_class_entry* scope, char* name, int name_length, zend_bool silent, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

silent

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_read_property | Up | zend_register_auto_global


zend_register_auto_global

zend_register_auto_global -- ...

Description

#include <zend_compile.h>

int zend_register_auto_global ( char* name, uint name_len, zend_auto_global_callback auto_global_callback, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

auto_global_callback

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_read_static_property | Up | zend_register_constant


zend_register_constant

zend_register_constant -- ...

Description

#include <zend_constants.h>

int zend_register_constant ( zend_constant* c, magic TSRMLS_DC )

...

Parameters

c

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_auto_global | Up | zend_register_default_classes


zend_register_default_classes

zend_register_default_classes -- ...

Description

#include <zend_exceptions.h>

void zend_register_default_classes ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_register_constant | Up | zend_register_double_constant


zend_register_double_constant

zend_register_double_constant -- ...

Description

#include <zend_constants.h>

void zend_register_double_constant ( char* name, uint name_len, double dval, int flags, int module_number, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

dval

...

flags

...

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_default_classes | Up | zend_register_functions


zend_register_functions

zend_register_functions -- ...

Description

#include <zend_API.h>

int zend_register_functions ( zend_class_entry* scope, zend_function_entry* functions, HashTable* function_table, int type, magic TSRMLS_DC )

...

Parameters

scope

...

functions

...

function_table

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_double_constant | Up | zend_register_ini_entries


zend_register_ini_entries

zend_register_ini_entries -- ...

Description

#include <zend_ini.h>

int zend_register_ini_entries ( zend_ini_entry* ini_entry, int module_number, magic TSRMLS_DC )

...

Parameters

ini_entry

...

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_functions | Up | zend_register_interfaces


zend_register_interfaces

zend_register_interfaces -- ...

Description

#include <zend_interfaces.h>

void zend_register_interfaces ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_register_ini_entries | Up | zend_register_internal_class_ex


zend_register_internal_class

zend_register_internal_class -- ...

Description

#include <zend_API.h>

zend_class_entry* zend_register_internal_class ( zend_class_entry* class_entry, magic TSRMLS_DC )

...

Parameters

class_entry

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_internal_class_ex | Up | zend_register_internal_interface


zend_register_internal_class_ex

zend_register_internal_class_ex -- ...

Description

#include <zend_API.h>

zend_class_entry* zend_register_internal_class_ex ( zend_class_entry* class_entry, zend_class_entry* parent_ce, char* parent_name, magic TSRMLS_DC )

...

Parameters

class_entry

...

parent_ce

...

parent_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_interfaces | Up | zend_register_internal_class


zend_register_internal_interface

zend_register_internal_interface -- ...

Description

#include <zend_API.h>

zend_class_entry* zend_register_internal_interface ( zend_class_entry* orig_class_entry, magic TSRMLS_DC )

...

Parameters

orig_class_entry

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_internal_class | Up | zend_register_internal_module


zend_register_internal_module

zend_register_internal_module -- ...

Description

#include <zend_API.h>

zend_module_entry* zend_register_internal_module ( zend_module_entry* module_entry, magic TSRMLS_DC )

...

Parameters

module_entry

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_internal_interface | Up | zend_register_list_destructors_ex


zend_register_list_destructors

zend_register_list_destructors -- ...

Description

#include <zend_list.h>

int zend_register_list_destructors ( void (*ld)(void* ), void (*pld)(void* ), int module_number )

...

Parameters

)

...

)

...

module_number

...

Return Values

...

Prev | Home | Next
zend_register_list_destructors_ex | Up | zend_register_long_constant


zend_register_list_destructors_ex

zend_register_list_destructors_ex -- ...

Description

#include <zend_list.h>

int zend_register_list_destructors_ex ( rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char* type_name, int module_number )

...

Parameters

ld

...

pld

...

type_name

...

module_number

...

Return Values

...

Prev | Home | Next
zend_register_internal_module | Up | zend_register_list_destructors


zend_register_long_constant

zend_register_long_constant -- ...

Description

#include <zend_constants.h>

void zend_register_long_constant ( char* name, uint name_len, long lval, int flags, int module_number, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

lval

...

flags

...

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_list_destructors | Up | zend_register_module_ex


zend_register_module

zend_register_module -- ...

Description

int zend_register_module ( zend_module_entry *module_entry )

...

Parameters

...

Return Values

...

Prev | Home | Next
zend_register_module_ex | Up | zend_register_resource


zend_register_module_ex

zend_register_module_ex -- ...

Description

#include <zend_API.h>

zend_module_entry* zend_register_module_ex ( zend_module_entry* module, magic TSRMLS_DC )

...

Parameters

module

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_long_constant | Up | zend_register_module


zend_register_resource

zend_register_resource -- ...

Description

#include <zend_list.h>

int zend_register_resource ( zval* rsrc_result, void* rsrc_pointer, int rsrc_type )

...

Parameters

rsrc_result

...

rsrc_pointer

...

rsrc_type

...

Return Values

...

Prev | Home | Next
zend_register_module | Up | zend_register_string_constant


zend_register_string_constant

zend_register_string_constant -- ...

Description

#include <zend_constants.h>

void zend_register_string_constant ( char* name, uint name_len, char* strval, int flags, int module_number, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

strval

...

flags

...

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_resource | Up | zend_register_stringl_constant


zend_register_stringl_constant

zend_register_stringl_constant -- ...

Description

#include <zend_constants.h>

void zend_register_stringl_constant ( char* name, uint name_len, char* strval, uint strlen, int flags, int module_number, magic TSRMLS_DC )

...

Parameters

name

...

name_len

...

strval

...

strlen

...

flags

...

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_string_constant | Up | zend_reset_all_cv


zend_reset_all_cv

zend_reset_all_cv -- ...

Description

#include <zend_API.h>

void zend_reset_all_cv ( HashTable* symbol_table, magic TSRMLS_DC )

...

Parameters

symbol_table

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_register_stringl_constant | Up | zend_reset_locale_deps


zend_reset_locale_deps

zend_reset_locale_deps -- ...

Description

#include <zend.h>

void zend_reset_locale_deps ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_reset_all_cv | Up | zend_restore_compiled_filename


zend_restore_compiled_filename

zend_restore_compiled_filename -- ...

Description

#include <zend_compile.h>

void zend_restore_compiled_filename ( char* original_compiled_filename, magic TSRMLS_DC )

...

Parameters

original_compiled_filename

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_reset_locale_deps | Up | zend_restore_compiled_script_encoding


zend_restore_compiled_script_encoding

zend_restore_compiled_script_encoding -- ...

Description

#include <zend_compile.h>

void zend_restore_compiled_script_encoding ( char* original_script_enc, magic TSRMLS_DC )

...

Parameters

original_script_enc

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_restore_compiled_filename | Up | zend_restore_ini_entry


zend_restore_ini_entry

zend_restore_ini_entry -- ...

Description

#include <zend_ini.h>

int zend_restore_ini_entry ( char* name, uint name_length, int stage )

...

Parameters

name

...

name_length

...

stage

...

Return Values

...

Prev | Home | Next
zend_restore_compiled_script_encoding | Up | zend_rsrc_list_get_rsrc_type


zend_rsrc_list_get_rsrc_type

zend_rsrc_list_get_rsrc_type -- ...

Description

#include <zend_list.h>

char* zend_rsrc_list_get_rsrc_type ( int resource, magic TSRMLS_DC )

...

Parameters

resource

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_restore_ini_entry | Up | zend_set_compiled_filename


zend_set_compiled_filename

zend_set_compiled_filename -- ...

Description

#include <zend_compile.h>

char* zend_set_compiled_filename ( char* new_compiled_filename, magic TSRMLS_DC )

...

Parameters

new_compiled_filename

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_rsrc_list_get_rsrc_type | Up | zend_set_compiled_script_encoding


zend_set_compiled_script_encoding

zend_set_compiled_script_encoding -- ...

Description

#include <zend_compile.h>

char* zend_set_compiled_script_encoding ( char* new_script_enc, magic TSRMLS_DC )

...

Parameters

new_script_enc

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_set_compiled_filename | Up | zend_set_memory_limit


zend_set_memory_limit

zend_set_memory_limit -- ...

Description

#include <zend_alloc.h>

int zend_set_memory_limit ( unsigned int memory_limit )

...

Parameters

memory_limit

...

Return Values

...

Prev | Home | Next
zend_set_compiled_script_encoding | Up | zend_set_timeout


zend_set_timeout

zend_set_timeout -- ...

Description

#include <zend_execute.h>

void zend_set_timeout ( long seconds )

...

Parameters

seconds

...

Return Values

...

Prev | Home | Next
zend_set_memory_limit | Up | zend_set_user_opcode_handler


zend_set_user_opcode_handler

zend_set_user_opcode_handler -- ...

Description

#include <zend_execute.h>

int zend_set_user_opcode_handler ( zend_uchar opcode, opcode_handler_t handler )

...

Parameters

opcode

...

handler

...

Return Values

...

Prev | Home | Next
zend_set_timeout | Up | zend_startup_module_ex


zend_startup_module

zend_startup_module -- ...

Description

#include <zend_API.h>

int zend_startup_module ( zend_module_entry* module_entry )

...

Parameters

module_entry

...

Return Values

...

Prev | Home | Next
zend_startup_module_ex | Up | zend_startup_modules


zend_startup_module_ex

zend_startup_module_ex -- ...

Description

#include <zend_API.h>

int zend_startup_module_ex ( zend_module_entry* module, magic TSRMLS_DC )

...

Parameters

module

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_set_user_opcode_handler | Up | zend_startup_module


zend_startup_modules

zend_startup_modules -- ...

Description

#include <zend_API.h>

int zend_startup_modules ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_startup_module | Up | zend_std_call_user_call


zend_std_call_user_call

zend_std_call_user_call -- ...

Description

#include <zend_object_handlers.h>

void zend_std_call_user_call ( INTERNAL_FUNCTION_PARAMETERS )

...

Parameters

INTERNAL_FUNCTION_PARAMETERS

...

Return Values

...

Prev | Home | Next
zend_startup_modules | Up | zend_std_cast_object_tostring


zend_std_cast_object_tostring

zend_std_cast_object_tostring -- ...

Description

#include <zend_object_handlers.h>

int zend_std_cast_object_tostring ( zval* readobj, zval* writeobj, int type, magic TSRMLS_DC )

...

Parameters

readobj

...

writeobj

...

type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_std_call_user_call | Up | zend_std_get_static_property


zend_std_get_static_property

zend_std_get_static_property -- ...

Description

#include <zend_object_handlers.h>

zval** zend_std_get_static_property ( zend_class_entry* ce, zend_uchar type, void* property_name, int property_name_len, zend_bool silent, magic TSRMLS_DC )

...

Parameters

ce

...

type

...

property_name

...

property_name_len

...

silent

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_std_cast_object_tostring | Up | zend_std_unset_static_property


zend_std_unset_static_property

zend_std_unset_static_property -- ...

Description

#include <zend_object_handlers.h>

zend_bool zend_std_unset_static_property ( zend_class_entry* ce, zend_uchar type, void* property_name, int property_name_len, magic TSRMLS_DC )

...

Parameters

ce

...

type

...

property_name

...

property_name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_std_get_static_property | Up | zend_stream_close


zend_stream_close

zend_stream_close -- ...

Description

#include <zend_stream.h>

void zend_stream_close ( ... handle )

...

Parameters

handle

...

Return Values

...

Prev | Home | Next
zend_std_unset_static_property | Up | zend_stream_ferror


zend_stream_ferror

zend_stream_ferror -- ...

Description

#include <zend_stream.h>

int zend_stream_ferror ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_close | Up | zend_stream_fixup


zend_stream_fixup

zend_stream_fixup -- ...

Description

#include <zend_stream.h>

int zend_stream_fixup ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_ferror | Up | zend_stream_ftell


zend_stream_ftell

zend_stream_ftell -- ...

Description

#include <zend_stream.h>

long zend_stream_ftell ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_fixup | Up | zend_stream_getc


zend_stream_getc

zend_stream_getc -- ...

Description

#include <zend_stream.h>

int zend_stream_getc ( zend_file_handle* file_handle, magic TSRMLS_DC )

...

Parameters

file_handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_ftell | Up | zend_stream_open


zend_stream_open

zend_stream_open -- ...

Description

#include <zend_stream.h>

int zend_stream_open ( const char* filename, zend_file_handle* handle, magic TSRMLS_DC )

...

Parameters

filename

...

handle

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_getc | Up | zend_stream_read


zend_stream_read

zend_stream_read -- ...

Description

#include <zend_stream.h>

size_t zend_stream_read ( zend_file_handle* file_handle, char* buf, size_t len, magic TSRMLS_DC )

...

Parameters

file_handle

...

buf

...

len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_stream_open | Up | zend_strip


zend_strip

zend_strip -- ...

Description

#include <zend_highlight.h>

void zend_strip ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_stream_read | Up | zend_strndup


zend_strndup

zend_strndup -- ...

Description

#include <zend_alloc.h>

char* zend_strndup ( const char* s, unsigned int length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
zend_strip | Up | zend_strtod


zend_strtod

zend_strtod -- ...

Description

#include <zend_strtod.h>

double zend_strtod ( const char* s00, char** se )

...

Parameters

s00

...

se

...

Return Values

...

Prev | Home | Next
zend_strndup | Up | zend_symtable_del


zend_symtable_del

zend_symtable_del -- ...

Description

#include <zend_hash.h>

int zend_symtable_del ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_strtod | Up | zend_symtable_exists


zend_symtable_exists

zend_symtable_exists -- ...

Description

#include <zend_hash.h>

int zend_symtable_exists ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_symtable_del | Up | zend_symtable_find


zend_symtable_find

zend_symtable_find -- ...

Description

#include <zend_hash.h>

int zend_symtable_find ( HashTable* ht, char* arKey, uint nKeyLength, void** pData )

...

Parameters

ht

...

arKey

...

nKeyLength

...

pData

...

Return Values

...

Prev | Home | Next
zend_symtable_exists | Up | zend_symtable_update_current_key


zend_symtable_update

zend_symtable_update -- ...

Description

#include <zend_hash.h>

int zend_symtable_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_symtable_update_current_key | Up | zend_throw_exception_object


zend_symtable_update_current_key

zend_symtable_update_current_key -- ...

Description

#include <zend_hash.h>

int zend_symtable_update_current_key ( HashTable* ht, char* arKey, uint nKeyLength )

...

Parameters

ht

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_symtable_find | Up | zend_symtable_update


zend_throw_exception_object

zend_throw_exception_object -- ...

Description

#include <zend_exceptions.h>

void zend_throw_exception_object ( zval* exception, magic TSRMLS_DC )

...

Parameters

exception

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_symtable_update | Up | zend_timeout


zend_timeout

zend_timeout -- ...

Description

#include <zend_execute.h>

void zend_timeout ( int dummy )

...

Parameters

dummy

...

Return Values

...

Prev | Home | Next
zend_throw_exception_object | Up | zend_u_declare_property_ex


zend_u_declare_property

zend_u_declare_property -- ...

Description

#include <zend_API.h>

int zend_u_declare_property ( zend_class_entry* ce, zend_uchar type, void* name, int name_length, zval* property, int access_type, magic TSRMLS_DC )

...

Parameters

ce

...

type

...

name

...

name_length

...

property

...

access_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_declare_property_ex | Up | zend_u_delete_global_variable


zend_u_declare_property_ex

zend_u_declare_property_ex -- ...

Description

#include <zend_API.h>

int zend_u_declare_property_ex ( zend_class_entry* ce, zend_uchar type, void* name, int name_length, zval* property, int access_type, char* doc_comment, int doc_comment_len, magic TSRMLS_DC )

...

Parameters

ce

...

type

...

name

...

name_length

...

property

...

access_type

...

doc_comment

...

doc_comment_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_timeout | Up | zend_u_declare_property


zend_u_delete_global_variable

zend_u_delete_global_variable -- ...

Description

#include <zend_API.h>

int zend_u_delete_global_variable ( zend_uchar type, void* name, int name_len, magic TSRMLS_DC )

...

Parameters

type

...

name

...

name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_declare_property | Up | zend_u_eval_string_ex


zend_u_eval_string

zend_u_eval_string -- ...

Description

#include <zend_execute.h>

int zend_u_eval_string ( zend_uchar type, void* str, zval* retval_ptr, char* string_name, magic TSRMLS_DC )

...

Parameters

type

...

str

...

retval_ptr

...

string_name

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_eval_string_ex | Up | zend_u_fetch_class


zend_u_eval_string_ex

zend_u_eval_string_ex -- ...

Description

#include <zend_execute.h>

int zend_u_eval_string_ex ( zend_uchar type, void* str, zval* retval_ptr, char* string_name, int handle_exceptions, magic TSRMLS_DC )

...

Parameters

type

...

str

...

retval_ptr

...

string_name

...

handle_exceptions

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_delete_global_variable | Up | zend_u_eval_string


zend_u_fetch_class

zend_u_fetch_class -- ...

Description

#include <zend_execute.h>

zend_class_entry* zend_u_fetch_class ( zend_uchar type, void* class_name, uint class_name_len, int fetch_type, magic TSRMLS_DC )

...

Parameters

type

...

class_name

...

class_name_len

...

fetch_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_eval_string | Up | zend_u_get_constant


zend_u_get_constant

zend_u_get_constant -- ...

Description

#include <zend_constants.h>

int zend_u_get_constant ( zend_uchar type, void* name, uint name_len, zval* result, magic TSRMLS_DC )

...

Parameters

type

...

name

...

name_len

...

result

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_fetch_class | Up | zend_u_get_hash_value


zend_u_get_hash_value

zend_u_get_hash_value -- ...

Description

#include <zend_hash.h>

ulong zend_u_get_hash_value ( zend_uchar type, char* arKey, uint nKeyLength )

...

Parameters

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_get_constant | Up | zend_u_hash_add_empty_element


zend_u_hash_add

zend_u_hash_add -- ...

Description

#include <zend_hash.h>

int zend_u_hash_add ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_u_hash_add_empty_element | Up | zend_u_hash_del_key_or_index


zend_u_hash_add_empty_element

zend_u_hash_add_empty_element -- ...

Description

#include <zend_hash.h>

int zend_u_hash_add_empty_element ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_get_hash_value | Up | zend_u_hash_add


zend_u_hash_del

zend_u_hash_del -- ...

Description

#include <zend_hash.h>

int zend_u_hash_del ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_hash_del_key_or_index | Up | zend_u_hash_exists


zend_u_hash_del_key_or_index

zend_u_hash_del_key_or_index -- ...

Description

#include <zend_hash.h>

int zend_u_hash_del_key_or_index ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, ulong h, int flag )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

h

...

flag

...

Return Values

...

Prev | Home | Next
zend_u_hash_add | Up | zend_u_hash_del


zend_u_hash_exists

zend_u_hash_exists -- ...

Description

#include <zend_hash.h>

int zend_u_hash_exists ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_hash_del | Up | zend_u_hash_find


zend_u_hash_find

zend_u_hash_find -- ...

Description

#include <zend_hash.h>

int zend_u_hash_find ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, void** pData )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

pData

...

Return Values

...

Prev | Home | Next
zend_u_hash_exists | Up | zend_u_hash_func


zend_u_hash_func

zend_u_hash_func -- ...

Description

#include <zend_hash.h>

ulong zend_u_hash_func ( zend_uchar type, char* arKey, uint nKeyLength )

...

Parameters

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_hash_find | Up | zend_u_hash_init_ex


zend_u_hash_init

zend_u_hash_init -- ...

Description

#include <zend_hash.h>

int zend_u_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool unicode )

...

Parameters

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

unicode

...

Return Values

...

Prev | Home | Next
zend_u_hash_init_ex | Up | zend_u_hash_quick_add


zend_u_hash_init_ex

zend_u_hash_init_ex -- ...

Description

#include <zend_hash.h>

int zend_u_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool unicode, zend_bool bApplyProtection )

...

Parameters

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

unicode

...

bApplyProtection

...

Return Values

...

Prev | Home | Next
zend_u_hash_func | Up | zend_u_hash_init


zend_u_hash_quick_add

zend_u_hash_quick_add -- ...

Description

#include <zend_hash.h>

int zend_u_hash_quick_add ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_u_hash_init | Up | zend_u_hash_quick_exists


zend_u_hash_quick_exists

zend_u_hash_quick_exists -- ...

Description

#include <zend_hash.h>

int zend_u_hash_quick_exists ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, ulong h )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

h

...

Return Values

...

Prev | Home | Next
zend_u_hash_quick_add | Up | zend_u_hash_quick_find


zend_u_hash_quick_find

zend_u_hash_quick_find -- ...

Description

#include <zend_hash.h>

int zend_u_hash_quick_find ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, ulong h, void** pData )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

h

...

pData

...

Return Values

...

Prev | Home | Next
zend_u_hash_quick_exists | Up | zend_u_hash_quick_update


zend_u_hash_quick_update

zend_u_hash_quick_update -- ...

Description

#include <zend_hash.h>

int zend_u_hash_quick_update ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_u_hash_quick_find | Up | zend_u_hash_update


zend_u_hash_update

zend_u_hash_update -- ...

Description

#include <zend_hash.h>

int zend_u_hash_update ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_u_hash_quick_update | Up | zend_u_is_auto_global


zend_u_is_auto_global

zend_u_is_auto_global -- ...

Description

#include <zend_compile.h>

zend_bool zend_u_is_auto_global ( zend_uchar type, void* name, uint name_len, magic TSRMLS_DC )

...

Parameters

type

...

name

...

name_len

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_hash_update | Up | zend_u_lookup_class_ex


zend_u_lookup_class

zend_u_lookup_class -- ...

Description

#include <zend_execute.h>

int zend_u_lookup_class ( zend_uchar type, void* name, int name_length, zend_class_entry*** ce, magic TSRMLS_DC )

...

Parameters

type

...

name

...

name_length

...

ce

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_lookup_class_ex | Up | zend_u_mangle_property_name


zend_u_lookup_class_ex

zend_u_lookup_class_ex -- ...

Description

#include <zend_execute.h>

int zend_u_lookup_class_ex ( zend_uchar type, void* name, int name_length, int use_autoload, zend_class_entry*** ce, magic TSRMLS_DC )

...

Parameters

type

...

name

...

name_length

...

use_autoload

...

ce

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_is_auto_global | Up | zend_u_lookup_class


zend_u_mangle_property_name

zend_u_mangle_property_name -- ...

Description

#include <zend_compile.h>

void zend_u_mangle_property_name ( char** dest, int* dest_length, zend_uchar type, char* src1, int src1_length, char* src2, int src2_length, int internal )

...

Parameters

dest

...

dest_length

...

type

...

src1

...

src1_length

...

src2

...

src2_length

...

internal

...

Return Values

...

Prev | Home | Next
zend_u_lookup_class | Up | zend_u_register_constant


zend_u_register_constant

zend_u_register_constant -- ...

Description

#include <zend_constants.h>

int zend_u_register_constant ( zend_uchar type, zend_constant* c, magic TSRMLS_DC )

...

Parameters

type

...

c

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_u_mangle_property_name | Up | zend_u_symtable_del


zend_u_symtable_del

zend_u_symtable_del -- ...

Description

#include <zend_hash.h>

int zend_u_symtable_del ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_register_constant | Up | zend_u_symtable_exists


zend_u_symtable_exists

zend_u_symtable_exists -- ...

Description

#include <zend_hash.h>

int zend_u_symtable_exists ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_symtable_del | Up | zend_u_symtable_find


zend_u_symtable_find

zend_u_symtable_find -- ...

Description

#include <zend_hash.h>

int zend_u_symtable_find ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, void** pData )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

pData

...

Return Values

...

Prev | Home | Next
zend_u_symtable_exists | Up | zend_u_symtable_update_current_key


zend_u_symtable_update

zend_u_symtable_update -- ...

Description

#include <zend_hash.h>

int zend_u_symtable_update ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Return Values

...

Prev | Home | Next
zend_u_symtable_update_current_key | Up | zend_u_unmangle_property_name


zend_u_symtable_update_current_key

zend_u_symtable_update_current_key -- ...

Description

#include <zend_hash.h>

int zend_u_symtable_update_current_key ( HashTable* ht, zend_uchar type, void* arKey, uint nKeyLength )

...

Parameters

ht

...

type

...

arKey

...

nKeyLength

...

Return Values

...

Prev | Home | Next
zend_u_symtable_find | Up | zend_u_symtable_update


zend_u_unmangle_property_name

zend_u_unmangle_property_name -- ...

Description

#include <zend_compile.h>

void zend_u_unmangle_property_name ( zend_uchar type, char* mangled_property, char** prop_name, char** class_name )

...

Parameters

type

...

mangled_property

...

prop_name

...

class_name

...

Return Values

...

Prev | Home | Next
zend_u_symtable_update | Up | zend_unmangle_property_name


zend_unmangle_property_name

zend_unmangle_property_name -- ...

Description

#include <zend_compile.h>

void zend_unmangle_property_name ( char* mangled_property, char** prop_name, char** class_name )

...

Parameters

mangled_property

...

prop_name

...

class_name

...

Return Values

...

Prev | Home | Next
zend_u_unmangle_property_name | Up | zend_unregister_functions


zend_unregister_functions

zend_unregister_functions -- ...

Description

#include <zend_API.h>

void zend_unregister_functions ( zend_function_entry* functions, int count, HashTable* function_table, magic TSRMLS_DC )

...

Parameters

functions

...

count

...

function_table

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_unmangle_property_name | Up | zend_unregister_ini_entries


zend_unregister_ini_entries

zend_unregister_ini_entries -- ...

Description

#include <zend_ini.h>

void zend_unregister_ini_entries ( int module_number, magic TSRMLS_DC )

...

Parameters

module_number

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_unregister_functions | Up | zend_unset_timeout


zend_unset_timeout

zend_unset_timeout -- ...

Description

#include <zend_execute.h>

void zend_unset_timeout ( TSRMLS_D )

...

Parameters

TSRMLS_D

...

Return Values

...

Prev | Home | Next
zend_unregister_ini_entries | Up | zend_update_class_constants


zend_update_class_constants

zend_update_class_constants -- ...

Description

#include <zend_API.h>

void zend_update_class_constants ( zend_class_entry* class_type, magic TSRMLS_DC )

...

Parameters

class_type

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_unset_timeout | Up | zend_update_property_ascii_string


zend_update_property

zend_update_property -- ...

Description

#include <zend_API.h>

void zend_update_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zval* value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_unicodel | Up | zend_update_static_property_ascii_string


zend_update_property_ascii_string

zend_update_property_ascii_string -- ...

Description

#include <zend_API.h>

void zend_update_property_ascii_string ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_class_constants | Up | zend_update_property_ascii_stringl


zend_update_property_ascii_stringl

zend_update_property_ascii_stringl -- ...

Description

#include <zend_API.h>

void zend_update_property_ascii_stringl ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_ascii_string | Up | zend_update_property_bool


zend_update_property_bool

zend_update_property_bool -- ...

Description

#include <zend_API.h>

void zend_update_property_bool ( zend_class_entry* scope, zval* object, char* name, int name_length, long value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_ascii_stringl | Up | zend_update_property_double


zend_update_property_double

zend_update_property_double -- ...

Description

#include <zend_API.h>

void zend_update_property_double ( zend_class_entry* scope, zval* object, char* name, int name_length, double value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_bool | Up | zend_update_property_long


zend_update_property_long

zend_update_property_long -- ...

Description

#include <zend_API.h>

void zend_update_property_long ( zend_class_entry* scope, zval* object, char* name, int name_length, long value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_double | Up | zend_update_property_null


zend_update_property_null

zend_update_property_null -- ...

Description

#include <zend_API.h>

void zend_update_property_null ( zend_class_entry* scope, zval* object, char* name, int name_length, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_long | Up | zend_update_property_rt_string


zend_update_property_rt_string

zend_update_property_rt_string -- ...

Description

#include <zend_API.h>

void zend_update_property_rt_string ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_null | Up | zend_update_property_rt_stringl


zend_update_property_rt_stringl

zend_update_property_rt_stringl -- ...

Description

#include <zend_API.h>

void zend_update_property_rt_stringl ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_rt_string | Up | zend_update_property_string


zend_update_property_string

zend_update_property_string -- ...

Description

#include <zend_API.h>

void zend_update_property_string ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_rt_stringl | Up | zend_update_property_stringl


zend_update_property_stringl

zend_update_property_stringl -- ...

Description

#include <zend_API.h>

void zend_update_property_stringl ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_string | Up | zend_update_property_unicode


zend_update_property_unicode

zend_update_property_unicode -- ...

Description

#include <zend_API.h>

void zend_update_property_unicode ( zend_class_entry* scope, zval* object, char* name, int name_length, UChar* value, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_stringl | Up | zend_update_property_unicodel


zend_update_property_unicodel

zend_update_property_unicodel -- ...

Description

#include <zend_API.h>

void zend_update_property_unicodel ( zend_class_entry* scope, zval* object, char* name, int name_length, UChar* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

object

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property_unicode | Up | zend_update_property


zend_update_static_property

zend_update_static_property -- ...

Description

#include <zend_API.h>

int zend_update_static_property ( zend_class_entry* scope, char* name, int name_length, zval* value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_unicodel | Up | zend_ustrndup


zend_update_static_property_ascii_string

zend_update_static_property_ascii_string -- ...

Description

#include <zend_API.h>

int zend_update_static_property_ascii_string ( zend_class_entry* scope, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_property | Up | zend_update_static_property_ascii_stringl


zend_update_static_property_ascii_stringl

zend_update_static_property_ascii_stringl -- ...

Description

#include <zend_API.h>

int zend_update_static_property_ascii_stringl ( zend_class_entry* scope, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_ascii_string | Up | zend_update_static_property_bool


zend_update_static_property_bool

zend_update_static_property_bool -- ...

Description

#include <zend_API.h>

int zend_update_static_property_bool ( zend_class_entry* scope, char* name, int name_length, long value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_ascii_stringl | Up | zend_update_static_property_double


zend_update_static_property_double

zend_update_static_property_double -- ...

Description

#include <zend_API.h>

int zend_update_static_property_double ( zend_class_entry* scope, char* name, int name_length, double value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_bool | Up | zend_update_static_property_long


zend_update_static_property_long

zend_update_static_property_long -- ...

Description

#include <zend_API.h>

int zend_update_static_property_long ( zend_class_entry* scope, char* name, int name_length, long value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_double | Up | zend_update_static_property_null


zend_update_static_property_null

zend_update_static_property_null -- ...

Description

#include <zend_API.h>

int zend_update_static_property_null ( zend_class_entry* scope, char* name, int name_length, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_long | Up | zend_update_static_property_rt_string


zend_update_static_property_rt_string

zend_update_static_property_rt_string -- ...

Description

#include <zend_API.h>

int zend_update_static_property_rt_string ( zend_class_entry* scope, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_null | Up | zend_update_static_property_rt_stringl


zend_update_static_property_rt_stringl

zend_update_static_property_rt_stringl -- ...

Description

#include <zend_API.h>

int zend_update_static_property_rt_stringl ( zend_class_entry* scope, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_rt_string | Up | zend_update_static_property_string


zend_update_static_property_string

zend_update_static_property_string -- ...

Description

#include <zend_API.h>

int zend_update_static_property_string ( zend_class_entry* scope, char* name, int name_length, char* value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_rt_stringl | Up | zend_update_static_property_stringl


zend_update_static_property_stringl

zend_update_static_property_stringl -- ...

Description

#include <zend_API.h>

int zend_update_static_property_stringl ( zend_class_entry* scope, char* name, int name_length, char* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_string | Up | zend_update_static_property_unicode


zend_update_static_property_unicode

zend_update_static_property_unicode -- ...

Description

#include <zend_API.h>

int zend_update_static_property_unicode ( zend_class_entry* scope, char* name, int name_length, UChar* value, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_stringl | Up | zend_update_static_property_unicodel


zend_update_static_property_unicodel

zend_update_static_property_unicodel -- ...

Description

#include <zend_API.h>

int zend_update_static_property_unicodel ( zend_class_entry* scope, char* name, int name_length, UChar* value, int value_length, magic TSRMLS_DC )

...

Parameters

scope

...

name

...

name_length

...

value

...

value_length

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zend_update_static_property_unicode | Up | zend_update_static_property


zend_ustrndup

zend_ustrndup -- ...

Description

#include <zend_alloc.h>

UChar* zend_ustrndup ( const UChar* s, uint length )

...

Parameters

s

...

length

...

Return Values

...

Prev | Home | Next
zend_update_static_property | Up | zend_wrong_param_count


zend_wrong_param_count

zend_wrong_param_count -- Generate standard error message for wrong parameter count in function or method call

Description

#include <zend_API.h>

void zend_wrong_param_count ( magic TSRMLS_D )

zend_wrong_param_count() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters. The function automaticly puts the right function name and class name (if needed) into the error message.

Usually the ZEND_WRONG_PARAM_COUNT() and ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() macros are used to invoke this function instead of calling it immediately as this saves typing the TSRMLS_C argument.

Parameters

TSRMLS_D

Thread context

Prev | Home | Next
zend_ustrndup | Up | zend_zval_type_name


zend_zval_type_name

zend_zval_type_name -- Returns the PHP type name for a given zval

Description

#include <zend_API.h>

char* zend_zval_type_name ( zval* arg )

zend_zval_type_name() returns the PHP typename for the current value of the zval pointed to by arg.

Parameters

arg

A pointer to the zval to be examined.

Return Values

A pointer to a static PHP typename string.

Prev | Home | Next
zend_wrong_param_count | Up | zval_add_ref


zval_add_ref

zval_add_ref -- ...

Description

#include <zend_variables.h>

void zval_add_ref ( zval** p )

...

Parameters

p

...

Return Values

...

Prev | Home | Next
zend_zval_type_name | Up | zval_internal_dtor


zval_internal_dtor

zval_internal_dtor -- ...

Description

#include <zend_variables.h>

void zval_internal_dtor ( zval* zvalue )

...

Parameters

zvalue

...

Return Values

...

Prev | Home | Next
zval_add_ref | Up | zval_internal_ptr_dtor


zval_internal_ptr_dtor

zval_internal_ptr_dtor -- ...

Description

#include <zend_variables.h>

void zval_internal_ptr_dtor ( zval** zvalue )

...

Parameters

zvalue

...

Return Values

...

Prev | Home | Next
zval_internal_dtor | Up | zval_ptr_dtor


zval_ptr_dtor

zval_ptr_dtor -- ...

Description

#include <zend_variables.h>

void zval_ptr_dtor ( zval** zval_ptr )

...

Parameters

zval_ptr

...

Return Values

...

Prev | Home | Next
zval_internal_ptr_dtor | Up | zval_string_to_unicode_ex


zval_string_to_unicode

zval_string_to_unicode -- ...

Description

#include <zend_unicode.h>

int zval_string_to_unicode ( zval* string, magic TSRMLS_DC )

...

Parameters

string

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zval_string_to_unicode_ex | Up | zval_unicode_to_string


zval_string_to_unicode_ex

zval_string_to_unicode_ex -- ...

Description

#include <zend_unicode.h>

int zval_string_to_unicode_ex ( zval* string, UConverter* conv )

...

Parameters

string

...

conv

...

Return Values

...

Prev | Home | Next
zval_ptr_dtor | Up | zval_string_to_unicode


zval_unicode_to_string

zval_unicode_to_string -- ...

Description

#include <zend_unicode.h>

int zval_unicode_to_string ( zval* string, UConverter* conv, magic TSRMLS_DC )

...

Parameters

string

...

conv

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zval_string_to_unicode | Up | zval_update_constant


zval_update_constant

zval_update_constant -- ...

Description

#include <zend_execute.h>

int zval_update_constant ( zval** pp, void* arg, magic TSRMLS_DC )

...

Parameters

pp

...

arg

...

TSRMLS_DC

...

Return Values

...

Prev | Home | Next
zval_unicode_to_string | Up | DISPLAY_INI_ENTRIES


RETURN_ASCII_STRING

RETURN_ASCII_STRING -- ...

Description

#include <zend_API.h>

??? RETURN_ASCII_STRING ( ??? t, ??? duplicate )

...

Parameters

t

...

duplicate

...

Return Values

...

Prev | Home | Next
REGISTER_STRINGL_CONSTANT | Up | RETURN_ASCII_STRINGL


RETURN_ASCII_STRINGL

RETURN_ASCII_STRINGL -- ...

Description

#include <zend_API.h>

??? RETURN_ASCII_STRINGL ( ??? t, ??? l, ??? duplicate )

...

Parameters

t

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_ASCII_STRING | Up | RETURN_BINARY


RETURN_BINARY

RETURN_BINARY -- ...

Description

#include <zend_API.h>

??? RETURN_BINARY ( ??? s, ??? duplicate )

...

Parameters

s

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_ASCII_STRINGL | Up | RETURN_BINARYL


RETURN_BINARYL

RETURN_BINARYL -- ...

Description

#include <zend_API.h>

??? RETURN_BINARYL ( ??? s, ??? l, ??? duplicate )

...

Parameters

s

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_BINARY | Up | RETURN_BOOL


RETURN_BOOL

RETURN_BOOL -- Return a bool value from a function

Description

#include <zend_API.h>

void RETURN_BOOL ( zend_bool b )

RETURN_BOOL() sets the return_value of the given function to b and returns control to the calling function.

Parameters

b

bool value to return.

Prev | Home | Next
RETURN_BINARYL | Up | RETURN_DOUBLE


RETURN_DOUBLE

RETURN_DOUBLE -- Return a double value from a function

Description

#include <zend_API.h>

void RETURN_DOUBLE ( double d )

RETURN_DOUBLE() sets the return_value of the given function to d and returns control to the calling function.

Parameters

d

double value to return.

Prev | Home | Next
RETURN_BOOL | Up | RETURN_EMPTY_BINARY


RETURN_EMPTY_BINARY

RETURN_EMPTY_BINARY -- ...

Description

#include <zend_API.h>

void RETURN_EMPTY_BINARY ( void )

...

Parameters

...

Return Values

...

Prev | Home | Next
RETURN_DOUBLE | Up | RETURN_EMPTY_STRING


RETURN_EMPTY_STRING

RETURN_EMPTY_STRING -- Return an empty string value from a function

Description

#include <zend_API.h>

void RETURN_EMPTY_STRING ( void )

This returns an empty string without the need to create such a string first.

Prev | Home | Next
RETURN_EMPTY_BINARY | Up | RETURN_EMPTY_UNICODE


RETURN_EMPTY_UNICODE

RETURN_EMPTY_UNICODE -- ...

Description

#include <zend_API.h>

void RETURN_EMPTY_UNICODE ( void )

...

Parameters

...

Return Values

...

Prev | Home | Next
RETURN_EMPTY_STRING | Up | RETURN_LONG


RETURN_LONG

RETURN_LONG -- Return a long value from a function

Description

#include <zend_API.h>

void RETURN_LONG ( long l )

RETURN_LONG() sets the return_value of the given function to l and returns control to the calling function.

Parameters

l

long value to return.

Prev | Home | Next
RETURN_EMPTY_UNICODE | Up | RETURN_NULL


RETURN_NULL

RETURN_NULL -- Return a null value from a function

Description

#include <zend_API.h>

void RETURN_NULL ( void )

RETURN_BOOL() sets the return_value of the given function to NULL and returns control to the calling function.

Prev | Home | Next
RETURN_LONG | Up | RETURN_RESOURCE


RETURN_RESOURCE

RETURN_RESOURCE -- Return a resource from a function

Description

#include <zend_API.h>

void RETURN_RESOURCE ( resource r )

RETURN_RESOURCE() sets the return_value of the given function to r and returns control to the calling function.

Parameters

r

The resource to be returned.

Prev | Home | Next
RETURN_NULL | Up | RETURN_RT_STRING


RETURN_RT_STRING

RETURN_RT_STRING -- ...

Description

#include <zend_API.h>

??? RETURN_RT_STRING ( ??? t, ??? duplicate )

...

Parameters

t

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_RESOURCE | Up | RETURN_RT_STRINGL


RETURN_RT_STRINGL

RETURN_RT_STRINGL -- ...

Description

#include <zend_API.h>

??? RETURN_RT_STRINGL ( ??? t, ??? l, ??? duplicate )

...

Parameters

t

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_RT_STRING | Up | RETURN_STRING


RETURN_STRING

RETURN_STRING -- ...

Description

#include <zend_API.h>

??? RETURN_STRING ( ??? s, ??? duplicate )

...

Parameters

s

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_RT_STRINGL | Up | RETURN_STRINGL


RETURN_STRINGL

RETURN_STRINGL -- ...

Description

#include <zend_API.h>

??? RETURN_STRINGL ( ??? s, ??? l, ??? duplicate )

...

Parameters

s

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_STRING | Up | RETURN_TEXT


RETURN_TEXT

RETURN_TEXT -- ...

Description

#include <zend_API.h>

??? RETURN_TEXT ( ??? t, ??? duplicate )

...

Parameters

t

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_STRINGL | Up | RETURN_TEXTL


RETURN_TEXTL

RETURN_TEXTL -- ...

Description

#include <zend_API.h>

??? RETURN_TEXTL ( ??? t, ??? l, ??? duplicate )

...

Parameters

t

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_TEXT | Up | RETURN_U_STRING


RETURN_U_STRING

RETURN_U_STRING -- ...

Description

#include <zend_API.h>

??? RETURN_U_STRING ( ??? conv, ??? t, ??? duplicate )

...

Parameters

conv

...

t

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_TEXTL | Up | RETURN_U_STRINGL


RETURN_U_STRINGL

RETURN_U_STRINGL -- ...

Description

#include <zend_API.h>

??? RETURN_U_STRINGL ( ??? conv, ??? t, ??? l, ??? duplicate )

...

Parameters

conv

...

t

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_U_STRING | Up | RETURN_UNICODE


RETURN_UNICODE

RETURN_UNICODE -- ...

Description

#include <zend_API.h>

??? RETURN_UNICODE ( ??? u, ??? duplicate )

...

Parameters

u

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_U_STRINGL | Up | RETURN_UNICODEL


RETURN_UNICODEL

RETURN_UNICODEL -- ...

Description

#include <zend_API.h>

??? RETURN_UNICODEL ( ??? u, ??? l, ??? duplicate )

...

Parameters

u

...

l

...

duplicate

...

Return Values

...

Prev | Home | Next
RETURN_UNICODE | Up | RETURN_ZVAL


RETURN_ZVAL

RETURN_ZVAL -- Return a zval value from a function

Description

#include <zend_API.h>

void RETURN_ZVAL ( zval * zv, bool copy, bool dtor )

...

Parameters

zv

Pointer to the zval to return.

copy

Create a copy of zv before returning it?

dtor

Destruct the original value before returning from the function, this is needed if zv was only temporarily created within the function.

Prev | Home | Next
RETURN_UNICODEL | Up | UNREGISTER_INI_ENTRIES


VCWD_ACCESS

VCWD_ACCESS -- Check users permissions for a file

Description

#include <tsrm_virtual_cwd.h>

int VCWD_ACCESS ( const char * pathname, mode_t mode )

This is a convenience wrapper for virtual_access().

Parameters

pathname

...

mode

...

Return Values

...

Prev | Home | Next
virtual_utime | Up | VCWD_CHDIR_FILE


VCWD_CHDIR

VCWD_CHDIR -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_CHDIR ( char * path )

...

Parameters

path

...

Return Values

...

Prev | Home | Next
VCWD_CHDIR_FILE | Up | VCWD_CHMOD


VCWD_CHDIR_FILE

VCWD_CHDIR_FILE -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_CHDIR_FILE ( char * path )

...

Parameters

path

...

Return Values

...

Prev | Home | Next
VCWD_ACCESS | Up | VCWD_CHDIR


VCWD_CHMOD

VCWD_CHMOD -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_CHMOD ( char * path, mode_t mode )

...

Parameters

path

...

mode

...

Return Values

...

Prev | Home | Next
VCWD_CHDIR | Up | VCWD_CHOWN


VCWD_CHOWN

VCWD_CHOWN -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_CHOWN ( char * path, uid_t owner, gid_t group )

...

Parameters

path

...

owner

...

group

...

Return Values

...

Prev | Home | Next
VCWD_CHMOD | Up | VCWD_CREAT


VCWD_CREAT

VCWD_CREAT -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_CREAT ( char * path, mode_t mode )

...

Parameters

path

...

mode

...

Return Values

...

Prev | Home | Next
VCWD_CHOWN | Up | VCWD_FOPEN


VCWD_FOPEN

VCWD_FOPEN -- ...

Description

#include <tsrm_virtual_cwd.h>

FILE * VCWD_FOPEN ( char * path, char * mode )

...

Parameters

path

...

mode

...

Return Values

...

Prev | Home | Next
VCWD_CREAT | Up | VCWD_GETCWD


VCWD_GETCWD

VCWD_GETCWD -- ...

Description

#include <tsrm_virtual_cwd.h>

char * VCWD_GETCWD ( char * buff, size_t size )

...

Parameters

buff

...

size

...

Return Values

...

Prev | Home | Next
VCWD_FOPEN | Up | VCWD_GETWD


VCWD_GETWD

VCWD_GETWD -- ...

Description

#include <tsrm_virtual_cwd.h>

char * VCWD_GETWD ( char * buf )

...

Parameters

buf

...

Return Values

...

Prev | Home | Next
VCWD_GETCWD | Up | VCWD_LCHOWN


VCWD_LCHOWN

VCWD_LCHOWN -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_LCHOWN ( char * path, uid_t owner, gid_t group )

...

Parameters

path

...

owner

...

group

...

Return Values

...

Prev | Home | Next
VCWD_GETWD | Up | VCWD_LSTAT


VCWD_LSTAT

VCWD_LSTAT -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_LSTAT ( char * path, struct stat * buff )

...

Parameters

path

...

buff

...

Return Values

...

Prev | Home | Next
VCWD_LCHOWN | Up | VCWD_MKDIR


VCWD_MKDIR

VCWD_MKDIR -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_MKDIR ( char * pathname, mode_t mode )

...

Parameters

pathname

...

mode

...

Return Values

...

Prev | Home | Next
VCWD_LSTAT | Up | VCWD_OPEN_MODE


VCWD_OPEN

VCWD_OPEN -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_OPEN ( char * path, int flags )

...

Parameters

path

...

flags

...

Return Values

...

Prev | Home | Next
VCWD_OPEN_MODE | Up | VCWD_OPENDIR


VCWD_OPEN_MODE

VCWD_OPEN_MODE -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_OPEN_MODE ( char * path, int flags, mode_t mode )

...

Parameters

path

...

flags

...

mode

...

Return Values

...

Prev | Home | Next
VCWD_MKDIR | Up | VCWD_OPEN


VCWD_OPENDIR

VCWD_OPENDIR -- ...

Description

#include <tsrm_virtual_cwd.h>

DIR * VCWD_OPENDIR ( char * pathname )

...

Parameters

pathname

...

Return Values

...

Prev | Home | Next
VCWD_OPEN | Up | VCWD_POPEN


VCWD_POPEN

VCWD_POPEN -- ...

Description

#include <tsrm_virtual_cwd.h>

FILE * VCWD_POPEN ( char * command, char * type )

...

Parameters

command

...

type

...

Return Values

...

Prev | Home | Next
VCWD_OPENDIR | Up | VCWD_REALPATH


VCWD_REALPATH

VCWD_REALPATH -- ...

Description

#include <tsrm_virtual_cwd.h>

char * VCWD_REALPATH ( char * path, char * real_path )

...

Parameters

path

...

real_path

...

Return Values

...

Prev | Home | Next
VCWD_POPEN | Up | VCWD_RENAME


VCWD_RENAME

VCWD_RENAME -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_RENAME ( char * oldname, char * newname )

...

Parameters

oldname

...

newname

...

Return Values

...

Prev | Home | Next
VCWD_REALPATH | Up | VCWD_RMDIR


VCWD_RMDIR

VCWD_RMDIR -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_RMDIR ( char * pathname )

...

Parameters

pathname

...

Return Values

...

Prev | Home | Next
VCWD_RENAME | Up | VCWD_STAT


VCWD_STAT

VCWD_STAT -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_STAT ( char * path, struct stat * buff )

...

Parameters

path

...

buff

...

Return Values

...

Prev | Home | Next
VCWD_RMDIR | Up | VCWD_UNLINK


VCWD_UNLINK

VCWD_UNLINK -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_UNLINK ( char * path )

...

Parameters

path

...

Return Values

...

Prev | Home | Next
VCWD_STAT | Up | VCWD_UTIME


VCWD_UTIME

VCWD_UTIME -- ...

Description

#include <tsrm_virtual_cwd.h>

int VCWD_UTIME ( char * path, struct utimebuf * time )

...

Parameters

path

...

time

...

Return Values

...

Prev | Home | Next
VCWD_UNLINK | Up | Extending PHP 3


Z_ARRVAL

Z_ARRVAL -- ...

Description

#include <zend_operators.h>

HashTable Z_ARRVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_ARRVAL_PP | Up | Z_BINLEN_P


Z_ARRVAL_P

Z_ARRVAL_P -- ...

Description

#include <zend_operators.h>

HashTable Z_ARRVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
UNREGISTER_INI_ENTRIES | Up | Z_ARRVAL_PP


Z_ARRVAL_PP

Z_ARRVAL_PP -- ...

Description

#include <zend_operators.h>

HashTable Z_ARRVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_ARRVAL_P | Up | Z_ARRVAL


Z_BINLEN

Z_BINLEN -- ...

Description

#include <zend_operators.h>

char * Z_BINLEN ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_BINLEN_PP | Up | Z_BINVAL_P


Z_BINLEN_P

Z_BINLEN_P -- ...

Description

#include <zend_operators.h>

char * Z_BINLEN_P ( zval * zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_ARRVAL | Up | Z_BINLEN_PP


Z_BINLEN_PP

Z_BINLEN_PP -- ...

Description

#include <zend_operators.h>

char * Z_BINLEN_PP ( zval ** zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_BINLEN_P | Up | Z_BINLEN


Z_BINVAL

Z_BINVAL -- ...

Description

#include <zend_operators.h>

??? Z_BINVAL ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_BINVAL_PP | Up | Z_BVAL_P


Z_BINVAL_P

Z_BINVAL_P -- ...

Description

#include <zend_operators.h>

??? Z_BINVAL_P ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_BINLEN | Up | Z_BINVAL_PP


Z_BINVAL_PP

Z_BINVAL_PP -- ...

Description

#include <zend_operators.h>

??? Z_BINVAL_PP ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_BINVAL_P | Up | Z_BINVAL


Z_BVAL

Z_BVAL -- Return a zval lval element as bool

Description

#include <zend_operators.h>

zend_bool Z_BVAL ( zval zv )

Z_BVAL() returns the lval element of zv casted to zend_bool.

Parameters

zv

The zval structure to extract the result value from.

Return Values

The lval element of zv casted to a zend_bool which is either TRUE or FALSE.

See Also

See Z_BVAL_P() and Z_BVAL_PP() for other macros that access the lval field of a zval as zend_bool.

For macros that extract other values from a zval ** see
Z_ARRVAL(), Z_BINLEN(),
Z_BINVAL(), ,
Z_DVAL(), Z_LVAL(),
Z_OBJCE(), Z_OBJ_HANDLE(),
Z_OBJ_HANDLER(), Z_OBJ_HT(),
Z_OBJPROP(), Z_OBJVAL(),
Z_RESVAL(), Z_STRLEN(),
Z_STRVAL(), Z_TYPE(),
Z_UNILEN(), Z_UNIVAL(),
Z_USTRCPLEN(), Z_USTRLEN(),
and Z_USTRVAL().

Prev | Home | Next
Z_BVAL_PP | Up | Z_DBG


Z_BVAL_P

Z_BVAL_P -- Dereference a zval pointer and return its lval element as bool

Description

#include <zend_operators.h>

zend_bool Z_BVAL_P ( zval * zval_p )

Z_BVAL_P() returns the lval element of the zval structure pointed to by zval_p casted to zend_bool.

Parameters

zval_p

Pointer to the zval structure to extract the result value from.

Return Values

The lval element of the zval structure pointed to by zval_p casted to a zend_bool which is either TRUE or FALSE.

See Also

See Z_BVAL() and Z_BVAL_PP() for other macros that access the lval field of a zval as zend_bool.

For macros that extract other values from a zval ** see
Z_ARRVAL_P(), Z_BINLEN_P(),
Z_BINVAL_P(), ,
Z_DVAL_P(), Z_LVAL_P(),
Z_OBJCE_P(), Z_OBJ_HANDLE_P(),
Z_OBJ_HANDLER_P(), Z_OBJ_HT_P(),
Z_OBJPROP_P(), Z_OBJVAL_P(),
Z_RESVAL_P(), Z_STRLEN_P(),
Z_STRVAL_P(), Z_TYPE_P(),
Z_UNILEN_P(), Z_UNIVAL_P(),
Z_USTRCPLEN_P(), Z_USTRLEN_P(),
and Z_USTRVAL_P().

Prev | Home | Next
Z_BINVAL | Up | Z_BVAL_PP


Z_BVAL_PP

Z_BVAL_PP -- Dereference a pointer to a zval pointer and return its lval element as bool

Description

#include <zend_operators.h>

zend_bool Z_BVAL_PP ( zval ** zval_pp )

Z_BVAL_PP() returns the lval element of the zval structure indirectly pointed to by zval_pp casted to zend_bool.

Parameters

zval_pp

Pointer to a pointer to the zval structure to extract the result value from.

Return Values

The lval element of the zval structure pointed to by the pointer pointed to by zval_pp casted to a zend_bool which is either TRUE or FALSE.

See Also

See Z_BVAL() and Z_BVAL_P() for other macros that access the lval field of a zval as zend_bool.

For macros that extract other values from a zval ** see
Z_ARRVAL_PP(), Z_BINLEN_PP(),
Z_BINVAL_PP(), ,
Z_DVAL_PP(), Z_LVAL_PP(),
Z_OBJCE_PP(), Z_OBJ_HANDLE_PP(),
Z_OBJ_HANDLER_PP(), Z_OBJ_HT_PP(),
Z_OBJPROP_PP(), Z_OBJVAL_PP(),
Z_RESVAL_PP(), Z_STRLEN_PP(),
Z_STRVAL_PP(), Z_TYPE_PP(),
Z_UNILEN_PP(), Z_UNIVAL_PP(),
Z_USTRCPLEN_PP(), Z_USTRLEN_PP(),
and Z_USTRVAL_PP().

Prev | Home | Next
Z_BVAL_P | Up | Z_BVAL


Z_DBG

Z_DBG -- ...

Description

#include <zend.h>

??? Z_DBG ( ??? expr )

...

Parameters

expr

...

Return Values

...

Prev | Home | Next
Z_BVAL | Up | Z_DVAL_P


Z_DVAL

Z_DVAL -- Return the dval element of a zval

Description

#include <zend_operators.h>

double Z_DVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_DVAL_PP | Up | Z_LVAL_P


Z_DVAL_P

Z_DVAL_P -- Dereference a zval pointer and return its dval element

Description

#include <zend_operators.h>

double Z_DVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_DBG | Up | Z_DVAL_PP


Z_DVAL_PP

Z_DVAL_PP -- Dereference a pointer to a zval pointer and return its dval element

Description

#include <zend_operators.h>

double Z_DVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_DVAL_P | Up | Z_DVAL


Z_LVAL

Z_LVAL -- ...

Description

#include <zend_operators.h>

long Z_LVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_LVAL_PP | Up | Z_OBJ_CLASS_NAME_P


Z_LVAL_P

Z_LVAL_P -- ...

Description

#include <zend_operators.h>

long Z_LVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_DVAL | Up | Z_LVAL_PP


Z_LVAL_PP

Z_LVAL_PP -- Dereference a pointer to a zval pointer and return its lval element

Description

#include <zend_operators.h>

long Z_LVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_LVAL_P | Up | Z_LVAL


Z_OBJ_CLASS_NAME_P

Z_OBJ_CLASS_NAME_P -- ...

Description

#include <zend_execute.h>

??? Z_OBJ_CLASS_NAME_P ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_LVAL | Up | Z_OBJ_HANDLE_P


Z_OBJ_HANDLE

Z_OBJ_HANDLE -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLE ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLE_PP | Up | Z_OBJ_HANDLER_P


Z_OBJ_HANDLE_P

Z_OBJ_HANDLE_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLE_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJ_CLASS_NAME_P | Up | Z_OBJ_HANDLE_PP


Z_OBJ_HANDLE_PP

Z_OBJ_HANDLE_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLE_PP ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLE_P | Up | Z_OBJ_HANDLE


Z_OBJ_HANDLER

Z_OBJ_HANDLER -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLER ( ??? zval, ??? hf )

...

Parameters

zval

...

hf

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLER_PP | Up | Z_OBJ_HT_P


Z_OBJ_HANDLER_P

Z_OBJ_HANDLER_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLER_P ( ??? zval_p, ??? h )

...

Parameters

zval_p

...

h

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLE | Up | Z_OBJ_HANDLER_PP


Z_OBJ_HANDLER_PP

Z_OBJ_HANDLER_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HANDLER_PP ( ??? zval_p, ??? h )

...

Parameters

zval_p

...

h

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLER_P | Up | Z_OBJ_HANDLER


Z_OBJ_HT

Z_OBJ_HT -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HT ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_OBJ_HT_PP | Up | Z_OBJCE_P


Z_OBJ_HT_P

Z_OBJ_HT_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HT_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJ_HANDLER | Up | Z_OBJ_HT_PP


Z_OBJ_HT_PP

Z_OBJ_HT_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJ_HT_PP ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJ_HT_P | Up | Z_OBJ_HT


Z_OBJCE

Z_OBJCE -- ...

Description

#include <zend_operators.h>

??? Z_OBJCE ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_OBJCE_PP | Up | Z_OBJPROP_P


Z_OBJCE_P

Z_OBJCE_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJCE_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJ_HT | Up | Z_OBJCE_PP


Z_OBJCE_PP

Z_OBJCE_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJCE_PP ( ??? zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_OBJCE_P | Up | Z_OBJCE


Z_OBJPROP

Z_OBJPROP -- ...

Description

#include <zend_operators.h>

??? Z_OBJPROP ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_OBJPROP_PP | Up | Z_OBJVAL_P


Z_OBJPROP_P

Z_OBJPROP_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJPROP_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJCE | Up | Z_OBJPROP_PP


Z_OBJPROP_PP

Z_OBJPROP_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJPROP_PP ( ??? zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_OBJPROP_P | Up | Z_OBJPROP


Z_OBJVAL

Z_OBJVAL -- ...

Description

#include <zend_operators.h>

??? Z_OBJVAL ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_OBJVAL_PP | Up | Z_RESVAL_P


Z_OBJVAL_P

Z_OBJVAL_P -- ...

Description

#include <zend_operators.h>

??? Z_OBJVAL_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJPROP | Up | Z_OBJVAL_PP


Z_OBJVAL_PP

Z_OBJVAL_PP -- ...

Description

#include <zend_operators.h>

??? Z_OBJVAL_PP ( ??? zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_OBJVAL_P | Up | Z_OBJVAL


Z_RESVAL

Z_RESVAL -- ...

Description

#include <zend_operators.h>

??? Z_RESVAL ( ??? zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_RESVAL_PP | Up | Z_STRLEN_P


Z_RESVAL_P

Z_RESVAL_P -- ...

Description

#include <zend_operators.h>

??? Z_RESVAL_P ( ??? zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_OBJVAL | Up | Z_RESVAL_PP


Z_RESVAL_PP

Z_RESVAL_PP -- ...

Description

#include <zend_operators.h>

??? Z_RESVAL_PP ( ??? zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_RESVAL_P | Up | Z_RESVAL


Z_STRLEN

Z_STRLEN -- ...

Description

#include <zend_operators.h>

int Z_STRLEN ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_STRLEN_PP | Up | Z_STRVAL_P


Z_STRLEN_P

Z_STRLEN_P -- ...

Description

#include <zend_operators.h>

int Z_STRLEN_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_RESVAL | Up | Z_STRLEN_PP


Z_STRLEN_PP

Z_STRLEN_PP -- ...

Description

#include <zend_operators.h>

int Z_STRLEN_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_STRLEN_P | Up | Z_STRLEN


Z_STRVAL

Z_STRVAL -- ...

Description

#include <zend_operators.h>

char * Z_STRVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_STRVAL_PP | Up | Z_TYPE_P


Z_STRVAL_P

Z_STRVAL_P -- ...

Description

#include <zend_operators.h>

char * Z_STRVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_STRLEN | Up | Z_STRVAL_PP


Z_STRVAL_PP

Z_STRVAL_PP -- ...

Description

#include <zend_operators.h>

char * Z_STRVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_STRVAL_P | Up | Z_STRVAL


Z_TYPE

Z_TYPE -- Get the type field of a zval

Description

#include <zend_operators.h>

zend_uchar Z_TYPE ( zval zv )

Return the type field of a zval.

Parameters

zv

A zval data structure.

Return Values

The type field of zv.

Prev | Home | Next
Z_TYPE_PP | Up | Z_UNILEN_P


Z_TYPE_P

Z_TYPE_P -- Get type field from zval pointer

Description

#include <zend_operators.h>

zend_uchar Z_TYPE_P ( zval * zval_p )

Return the type filed from the zval data structure pointed to by zval_p.

Parameters

zval_p

Pointer to a zval.

Return Values

Type of the zval pointed to.

Prev | Home | Next
Z_STRVAL | Up | Z_TYPE_PP


Z_TYPE_PP

Z_TYPE_PP -- Get type field from zval pointer pointer

Description

#include <zend_operators.h>

zend_uchar Z_TYPE_PP ( zval ** zval_pp )

Return the type filed from the zval data structure pointed to by the pointer pointed to by zval_pp.

Parameters

zval_pp

Pointer to a pointer to a zval structure.

Return Values

Type of the zval structure pointed to.

Prev | Home | Next
Z_TYPE_P | Up | Z_TYPE


Z_UNILEN

Z_UNILEN -- ...

Description

#include <zend_operators.h>

int Z_UNILEN ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_UNILEN_PP | Up | Z_UNIVAL_P


Z_UNILEN_P

Z_UNILEN_P -- ...

Description

#include <zend_operators.h>

int Z_UNILEN_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_TYPE | Up | Z_UNILEN_PP


Z_UNILEN_PP

Z_UNILEN_PP -- ...

Description

#include <zend_operators.h>

int Z_UNILEN_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_UNILEN_P | Up | Z_UNILEN


Z_UNIVAL

Z_UNIVAL -- ...

Description

#include <zend_operators.h>

char * Z_UNIVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_UNIVAL_PP | Up | Z_USTRCPLEN_P


Z_UNIVAL_P

Z_UNIVAL_P -- ...

Description

#include <zend_operators.h>

char * Z_UNIVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_UNILEN | Up | Z_UNIVAL_PP


Z_UNIVAL_PP

Z_UNIVAL_PP -- ...

Description

#include <zend_operators.h>

char * Z_UNIVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_UNIVAL_P | Up | Z_UNIVAL


Z_USTRCPLEN

Z_USTRCPLEN -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRCPLEN ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_USTRCPLEN_PP | Up | Z_USTRLEN_P


Z_USTRCPLEN_P

Z_USTRCPLEN_P -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRCPLEN_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_UNIVAL | Up | Z_USTRCPLEN_PP


Z_USTRCPLEN_PP

Z_USTRCPLEN_PP -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRCPLEN_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_USTRCPLEN_P | Up | Z_USTRCPLEN


Z_USTRLEN

Z_USTRLEN -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRLEN ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_USTRLEN_PP | Up | Z_USTRVAL_P


Z_USTRLEN_P

Z_USTRLEN_P -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRLEN_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_USTRCPLEN | Up | Z_USTRLEN_PP


Z_USTRLEN_PP

Z_USTRLEN_PP -- ...

Description

#include <zend_operators.h>

int32_t Z_USTRLEN_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_USTRLEN_P | Up | Z_USTRLEN


Z_USTRVAL

Z_USTRVAL -- ...

Description

#include <zend_operators.h>

UChar * Z_USTRVAL ( zval zval )

...

Parameters

zval

...

Return Values

...

Prev | Home | Next
Z_USTRVAL_PP | Up | ZEND_ABSTRACT_ME


Z_USTRVAL_P

Z_USTRVAL_P -- ...

Description

#include <zend_operators.h>

UChar * Z_USTRVAL_P ( zval * zval_p )

...

Parameters

zval_p

...

Return Values

...

Prev | Home | Next
Z_USTRLEN | Up | Z_USTRVAL_PP


Z_USTRVAL_PP

Z_USTRVAL_PP -- ...

Description

#include <zend_operators.h>

UChar * Z_USTRVAL_PP ( zval ** zval_pp )

...

Parameters

zval_pp

...

Return Values

...

Prev | Home | Next
Z_USTRVAL_P | Up | Z_USTRVAL


ZEND_ABSTRACT_ME

ZEND_ABSTRACT_ME -- ...

Description

#include <zend_API.h>

??? ZEND_ABSTRACT_ME ( ??? classname, ??? name, ??? arg_info )

...

Parameters

classname

...

name

...

arg_info

...

Return Values

...

Prev | Home | Next
Z_USTRVAL | Up | ZEND_ARG_ARRAY_INFO


ZEND_ARG_ARRAY_INFO

ZEND_ARG_ARRAY_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_ARG_ARRAY_INFO ( ??? pass_by_ref, ??? name, ??? allow_null )

...

Parameters

pass_by_ref

...

name

...

allow_null

...

Return Values

...

Prev | Home | Next
ZEND_ABSTRACT_ME | Up | ZEND_ARG_INFO


ZEND_ARG_INFO

ZEND_ARG_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_ARG_INFO ( ??? pass_by_ref, ??? name )

...

Parameters

pass_by_ref

...

name

...

Return Values

...

Prev | Home | Next
ZEND_ARG_ARRAY_INFO | Up | ZEND_ARG_OBJ_INFO


ZEND_ARG_OBJ_INFO

ZEND_ARG_OBJ_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_ARG_OBJ_INFO ( ??? pass_by_ref, ??? name, ??? classname, ??? allow_null )

...

Parameters

pass_by_ref

...

name

...

classname

...

allow_null

...

Return Values

...

Prev | Home | Next
ZEND_ARG_INFO | Up | ZEND_ARG_PASS_INFO


ZEND_ARG_PASS_INFO

ZEND_ARG_PASS_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_ARG_PASS_INFO ( ??? pass_by_ref )

...

Parameters

pass_by_ref

...

Return Values

...

Prev | Home | Next
ZEND_ARG_OBJ_INFO | Up | ZEND_BEGIN_ARG_INFO_EX


ZEND_BEGIN_ARG_INFO

ZEND_BEGIN_ARG_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_BEGIN_ARG_INFO ( ??? name, ??? pass_rest_by_reference )

...

Parameters

name

...

pass_rest_by_reference

...

Return Values

...

Prev | Home | Next
ZEND_BEGIN_ARG_INFO_EX | Up | ZEND_BEGIN_MODULE_GLOBALS


ZEND_BEGIN_ARG_INFO_EX

ZEND_BEGIN_ARG_INFO_EX -- ...

Description

#include <zend_API.h>

??? ZEND_BEGIN_ARG_INFO_EX ( ??? name, ??? pass_rest_by_reference, ??? return_reference, ??? required_num_args )

...

Parameters

name

...

pass_rest_by_reference

...

return_reference

...

required_num_args

...

Return Values

...

Prev | Home | Next
ZEND_ARG_PASS_INFO | Up | ZEND_BEGIN_ARG_INFO


ZEND_BEGIN_MODULE_GLOBALS

ZEND_BEGIN_MODULE_GLOBALS -- ...

Description

#include <zend_API.h>

??? ZEND_BEGIN_MODULE_GLOBALS ( ??? module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
ZEND_BEGIN_ARG_INFO | Up | ZEND_COLL_RESULT


ZEND_COLL_RESULT

ZEND_COLL_RESULT -- ...

Description

#include <zend.h>

??? ZEND_COLL_RESULT ( ??? n )

...

Parameters

n

...

Return Values

...

Prev | Home | Next
ZEND_BEGIN_MODULE_GLOBALS | Up | ZEND_DECLARE_MODULE_GLOBALS


ZEND_DECLARE_MODULE_GLOBALS

ZEND_DECLARE_MODULE_GLOBALS -- ...

Description

#include <zend_API.h>

??? ZEND_DECLARE_MODULE_GLOBALS ( ??? module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
ZEND_COLL_RESULT | Up | ZEND_DEFINE_PROPERTY


ZEND_DEFINE_PROPERTY

ZEND_DEFINE_PROPERTY -- ...

Description

#include <zend_API.h>

??? ZEND_DEFINE_PROPERTY ( ??? class_ptr, ??? name, ??? value, ??? mask )

...

Parameters

class_ptr

...

name

...

value

...

mask

...

Return Values

...

Prev | Home | Next
ZEND_DECLARE_MODULE_GLOBALS | Up | ZEND_END_ARG_INFO


ZEND_END_ARG_INFO

ZEND_END_ARG_INFO -- ...

Description

#include <zend_API.h>

??? ZEND_END_ARG_INFO ( ??? )

...

Parameters

...

Return Values

...

Prev | Home | Next
ZEND_DEFINE_PROPERTY | Up | ZEND_END_MODULE_GLOBALS


ZEND_END_MODULE_GLOBALS

ZEND_END_MODULE_GLOBALS -- ...

Description

#include <zend_API.h>

??? ZEND_END_MODULE_GLOBALS ( ??? module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
ZEND_END_ARG_INFO | Up | ZEND_EXTERN_MODULE_GLOBALS


ZEND_EXTERN_MODULE_GLOBALS

ZEND_EXTERN_MODULE_GLOBALS -- ...

Description

#include <zend_API.h>

??? ZEND_EXTERN_MODULE_GLOBALS ( ??? module_name )

...

Parameters

module_name

...

Return Values

...

Prev | Home | Next
ZEND_END_MODULE_GLOBALS | Up | ZEND_FALIAS


ZEND_FALIAS

ZEND_FALIAS -- ...

Description

#include <zend_API.h>

??? ZEND_FALIAS ( ??? name, ??? alias, ??? arg_info )

...

Parameters

name

...

alias

...

arg_info

...

Return Values

...

Prev | Home | Next
ZEND_EXTERN_MODULE_GLOBALS | Up | ZEND_FE


ZEND_FE

ZEND_FE -- ...

Description

#include <zend_API.h>

??? ZEND_FE ( ??? name, ??? arg_info )

...

Parameters

name

...

arg_info

...

Return Values

...

Prev | Home | Next
ZEND_FALIAS | Up | ZEND_FENTRY


ZEND_FENTRY

ZEND_FENTRY -- ...

Description

#include <zend_API.h>

??? ZEND_FENTRY ( ??? zend_name, ??? name, ??? arg_info, ??? flags )

...

Parameters

zend_name

...

name

...

arg_info

...

flags

...

Return Values

...

Prev | Home | Next
ZEND_FE | Up | ZEND_FETCH_RESOURCE2


ZEND_FETCH_RESOURCE

ZEND_FETCH_RESOURCE -- ...

Description

#include <zend_list.h>

??? ZEND_FETCH_RESOURCE ( ??? rsrc, ??? rsrc_type, ??? passed_id, ??? default_id, ??? resource_type_name, ??? resource_type )

...

Parameters

rsrc

...

rsrc_type

...

passed_id

...

default_id

...

resource_type_name

...

resource_type

...

Return Values

...

Prev | Home | Next
ZEND_FETCH_RESOURCE2 | Up | ZEND_FN_SCOPE_NAME


ZEND_FETCH_RESOURCE2

ZEND_FETCH_RESOURCE2 -- ...

Description

#include <zend_list.h>

??? ZEND_FETCH_RESOURCE2 ( ??? rsrc, ??? rsrc_type, ??? passed_id, ??? default_id, ??? resource_type_name, ??? resource_type1, ??? resource_type2 )

...

Parameters

rsrc

...

rsrc_type

...

passed_id

...

default_id

...

resource_type_name

...

resource_type1

...

resource_type2

...

Return Values

...

Prev | Home | Next
ZEND_FENTRY | Up | ZEND_FETCH_RESOURCE


ZEND_FN

ZEND_FN -- ...

Description

#include <zend_API.h>

??? ZEND_FN ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_FN_SCOPE_NAME | Up | ZEND_FUNCTION


ZEND_FN_SCOPE_NAME

ZEND_FN_SCOPE_NAME -- ...

Description

#include <zend_compile.h>

??? ZEND_FN_SCOPE_NAME ( ??? function )

...

Parameters

function

...

Return Values

...

Prev | Home | Next
ZEND_FETCH_RESOURCE | Up | ZEND_FN


ZEND_FUNCTION

ZEND_FUNCTION -- ...

Description

#include <zend_API.h>

??? ZEND_FUNCTION ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_FN | Up | ZEND_GET_MODULE


ZEND_GET_MODULE

ZEND_GET_MODULE -- ...

Description

#include <zend_API.h>

void ZEND_GET_MODULE ( char * name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_FUNCTION | Up | ZEND_GET_RESOURCE_TYPE_ID


ZEND_GET_RESOURCE_TYPE_ID

ZEND_GET_RESOURCE_TYPE_ID -- ...

Description

#include <zend_list.h>

??? ZEND_GET_RESOURCE_TYPE_ID ( ??? le_id, ??? le_type_name )

...

Parameters

le_id

...

le_type_name

...

Return Values

...

Prev | Home | Next
ZEND_GET_MODULE | Up | ZEND_INI_BEGIN


ZEND_INI_BEGIN

ZEND_INI_BEGIN -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_BEGIN ( ??? )

...

Parameters

...

Return Values

...

Prev | Home | Next
ZEND_GET_RESOURCE_TYPE_ID | Up | ZEND_INI_DISP


ZEND_INI_DISP

ZEND_INI_DISP -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_DISP ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_INI_BEGIN | Up | ZEND_INI_END


ZEND_INI_END

ZEND_INI_END -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_END ( ??? )

...

Parameters

...

Return Values

...

Prev | Home | Next
ZEND_INI_DISP | Up | ZEND_INI_ENTRY_EX


ZEND_INI_ENTRY

ZEND_INI_ENTRY -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY ( ??? name, ??? default_value, ??? modifiable, ??? on_modify )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY3 | Up | ZEND_INI_MH


ZEND_INI_ENTRY1

ZEND_INI_ENTRY1 -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY1 ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1 )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY1_EX | Up | ZEND_INI_ENTRY2_EX


ZEND_INI_ENTRY1_EX

ZEND_INI_ENTRY1_EX -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY1_EX ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1, ??? displayer )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

displayer

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY_EX | Up | ZEND_INI_ENTRY1


ZEND_INI_ENTRY2

ZEND_INI_ENTRY2 -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY2 ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1, ??? arg2 )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

arg2

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY2_EX | Up | ZEND_INI_ENTRY3_EX


ZEND_INI_ENTRY2_EX

ZEND_INI_ENTRY2_EX -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY2_EX ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1, ??? arg2, ??? displayer )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

arg2

...

displayer

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY1 | Up | ZEND_INI_ENTRY2


ZEND_INI_ENTRY3

ZEND_INI_ENTRY3 -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY3 ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1, ??? arg2, ??? arg3 )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

arg2

...

arg3

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY3_EX | Up | ZEND_INI_ENTRY


ZEND_INI_ENTRY3_EX

ZEND_INI_ENTRY3_EX -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY3_EX ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? arg1, ??? arg2, ??? arg3, ??? displayer )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

arg1

...

arg2

...

arg3

...

displayer

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY2 | Up | ZEND_INI_ENTRY3


ZEND_INI_ENTRY_EX

ZEND_INI_ENTRY_EX -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_ENTRY_EX ( ??? name, ??? default_value, ??? modifiable, ??? on_modify, ??? displayer )

...

Parameters

name

...

default_value

...

modifiable

...

on_modify

...

displayer

...

Return Values

...

Prev | Home | Next
ZEND_INI_END | Up | ZEND_INI_ENTRY1_EX


ZEND_INI_MH

ZEND_INI_MH -- ...

Description

#include <zend_ini.h>

??? ZEND_INI_MH ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_INI_ENTRY | Up | ZEND_INIT_MODULE_GLOBALS


ZEND_INIT_MODULE_GLOBALS

ZEND_INIT_MODULE_GLOBALS -- ...

Description

#include <zend_API.h>

??? ZEND_INIT_MODULE_GLOBALS ( ??? module_name, ??? globals_ctor, ??? globals_dtor )

...

Parameters

module_name

...

globals_ctor

...

globals_dtor

...

Return Values

...

Prev | Home | Next
ZEND_INI_MH | Up | ZEND_INIT_SYMTABLE_EX


ZEND_INIT_SYMTABLE

ZEND_INIT_SYMTABLE -- ...

Description

#include <zend_hash.h>

??? ZEND_INIT_SYMTABLE ( ??? ht )

...

Parameters

ht

...

Return Values

...

Prev | Home | Next
ZEND_INIT_SYMTABLE_EX | Up | ZEND_LOG_XOR


ZEND_INIT_SYMTABLE_EX

ZEND_INIT_SYMTABLE_EX -- ...

Description

#include <zend_hash.h>

??? ZEND_INIT_SYMTABLE_EX ( ??? ht, ??? n, ??? persistent )

...

Parameters

ht

...

n

...

persistent

...

Return Values

...

Prev | Home | Next
ZEND_INIT_MODULE_GLOBALS | Up | ZEND_INIT_SYMTABLE


ZEND_LOG_XOR

ZEND_LOG_XOR -- ...

Description

#include <zend.h>

??? ZEND_LOG_XOR ( ??? a, ??? b )

...

Parameters

a

...

b

...

Return Values

...

Prev | Home | Next
ZEND_INIT_SYMTABLE | Up | ZEND_MALIAS


ZEND_MALIAS

ZEND_MALIAS -- ...

Description

#include <zend_API.h>

??? ZEND_MALIAS ( ??? classname, ??? name, ??? alias, ??? arg_info, ??? flags )

...

Parameters

classname

...

name

...

alias

...

arg_info

...

flags

...

Return Values

...

Prev | Home | Next
ZEND_LOG_XOR | Up | ZEND_ME_MAPPING


ZEND_ME

ZEND_ME -- ...

Description

#include <zend_API.h>

??? ZEND_ME ( ??? classname, ??? name, ??? arg_info, ??? flags )

...

Parameters

classname

...

name

...

arg_info

...

flags

...

Return Values

...

Prev | Home | Next
ZEND_ME_MAPPING | Up | ZEND_METHOD


ZEND_ME_MAPPING

ZEND_ME_MAPPING -- ...

Description

#include <zend_API.h>

??? ZEND_ME_MAPPING ( ??? name, ??? func_name, ??? arg_types )

...

Parameters

name

...

func_name

...

arg_types

...

Return Values

...

Prev | Home | Next
ZEND_MALIAS | Up | ZEND_ME


ZEND_METHOD

ZEND_METHOD -- ...

Description

#include <zend_API.h>

??? ZEND_METHOD ( ??? classname, ??? name )

...

Parameters

classname

...

name

...

Return Values

...

Prev | Home | Next
ZEND_ME | Up | ZEND_MOD_CONFLICTS_EX


ZEND_MOD_CONFLICTS

ZEND_MOD_CONFLICTS -- ...

Description

#include <zend_modules.h>

void ZEND_MOD_CONFLICTS ( char * name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_MOD_CONFLICTS_EX | Up | ZEND_MOD_OPTIONAL_EX


ZEND_MOD_CONFLICTS_EX

ZEND_MOD_CONFLICTS_EX -- ...

Description

#include <zend_modules.h>

void ZEND_MOD_CONFLICTS_EX ( char * name, char * rel, char * ver )

...

Parameters

name

...

rel

...

ver

...

Return Values

...

Prev | Home | Next
ZEND_METHOD | Up | ZEND_MOD_CONFLICTS


ZEND_MOD_OPTIONAL

ZEND_MOD_OPTIONAL -- ...

Description

#include <zend_modules.h>

void ZEND_MOD_OPTIONAL ( char * name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_MOD_OPTIONAL_EX | Up | ZEND_MOD_REQUIRED_EX


ZEND_MOD_OPTIONAL_EX

ZEND_MOD_OPTIONAL_EX -- ...

Description

#include <zend_modules.h>

void ZEND_MOD_OPTIONAL_EX ( char * name, char * rel, char * ver )

...

Parameters

name

...

rel

...

ver

...

Return Values

...

Prev | Home | Next
ZEND_MOD_CONFLICTS | Up | ZEND_MOD_OPTIONAL


ZEND_MOD_REQUIRED

ZEND_MOD_REQUIRED -- Create a simple dependency entry for a required extension

Description

#include <zend_modules.h>

void ZEND_MOD_REQUIRED ( char * ext_name )

ZEND_MOD_REQUIRED() generates a zend_module_dep entry for the extension named by ext_name. A simple entry without further version specifications is generated. See ZEND_MOD_REQUIRED_EX() for an extended version of this macro that also allows to specify version dependencies.

Parameters

ext_name

The name of a required extension

Return Values

Code to register the required extension dependency

See Also

See ZEND_MOD_REQUIRED_EX() if you also need to specify extension version requirements.

See also ZEND_MOD_OPTIONAL(),
ZEND_MOD_OPTIONAL_EX(),
ZEND_MOD_CONFLICTS(), and
ZEND_MOD_CONFLICTS_EX().

Prev | Home | Next
ZEND_MOD_REQUIRED_EX | Up | ZEND_MODULE_ACTIVATE_D


ZEND_MOD_REQUIRED_EX

ZEND_MOD_REQUIRED_EX -- Create a full dependency entry for the required version of an extension

Description

#include <zend_modules.h>

void ZEND_MOD_REQUIRED_EX ( char * name, char * rel, char * ver )

ZEND_MOD_REQUIRED_EX() generates a zend_module_dep entry for the extension named by ext_name, including version information. It allows to specify requirements like "up to version x.y", "starting with version x.y" or "exactly version x.y".

Warning

Version specific comparisons are not implemented yet, so for now ZEND_MOD_REUQUIRE() and ZEND_MOD_REQUIRE_EX() define identical behavior.

Parameters

name

Name of the required extension

rel

Comparison operator, one of eq, lt, le, gt, or ge

ver

Version string

Return Values

Code to register the required extension

See Also

See ZEND_MOD_REQUIRED() if you do not need to specify extension version requirements.

See also ZEND_MOD_OPTIONAL(),
ZEND_MOD_OPTIONAL_EX(),
ZEND_MOD_CONFLICTS(), and
ZEND_MOD_CONFLICTS_EX().

Prev | Home | Next
ZEND_MOD_OPTIONAL | Up | ZEND_MOD_REQUIRED


ZEND_MODULE_ACTIVATE_D

ZEND_MODULE_ACTIVATE_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_ACTIVATE_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MOD_REQUIRED | Up | ZEND_MODULE_ACTIVATE_N


ZEND_MODULE_ACTIVATE_N

ZEND_MODULE_ACTIVATE_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_ACTIVATE_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_ACTIVATE_D | Up | ZEND_MODULE_DEACTIVATE_D


ZEND_MODULE_DEACTIVATE_D

ZEND_MODULE_DEACTIVATE_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_DEACTIVATE_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_ACTIVATE_N | Up | ZEND_MODULE_DEACTIVATE_N


ZEND_MODULE_DEACTIVATE_N

ZEND_MODULE_DEACTIVATE_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_DEACTIVATE_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_DEACTIVATE_D | Up | ZEND_MODULE_INFO_D


ZEND_MODULE_INFO_D

ZEND_MODULE_INFO_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_INFO_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_DEACTIVATE_N | Up | ZEND_MODULE_INFO_N


ZEND_MODULE_INFO_N

ZEND_MODULE_INFO_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_INFO_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_INFO_D | Up | ZEND_MODULE_POST_ZEND_DEACTIVATE_D


ZEND_MODULE_POST_ZEND_DEACTIVATE_D

ZEND_MODULE_POST_ZEND_DEACTIVATE_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_POST_ZEND_DEACTIVATE_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_INFO_N | Up | ZEND_MODULE_POST_ZEND_DEACTIVATE_N


ZEND_MODULE_POST_ZEND_DEACTIVATE_N

ZEND_MODULE_POST_ZEND_DEACTIVATE_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_POST_ZEND_DEACTIVATE_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_POST_ZEND_DEACTIVATE_D | Up | ZEND_MODULE_SHUTDOWN_D


ZEND_MODULE_SHUTDOWN_D

ZEND_MODULE_SHUTDOWN_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_SHUTDOWN_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_POST_ZEND_DEACTIVATE_N | Up | ZEND_MODULE_SHUTDOWN_N


ZEND_MODULE_SHUTDOWN_N

ZEND_MODULE_SHUTDOWN_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_SHUTDOWN_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_SHUTDOWN_D | Up | ZEND_MODULE_STARTUP_D


ZEND_MODULE_STARTUP_D

ZEND_MODULE_STARTUP_D -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_STARTUP_D ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_SHUTDOWN_N | Up | ZEND_MODULE_STARTUP_N


ZEND_MODULE_STARTUP_N

ZEND_MODULE_STARTUP_N -- ...

Description

#include <zend_API.h>

??? ZEND_MODULE_STARTUP_N ( ??? module )

...

Parameters

module

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_STARTUP_D | Up | ZEND_NAMED_FE


ZEND_NAMED_FE

ZEND_NAMED_FE -- ...

Description

#include <zend_API.h>

??? ZEND_NAMED_FE ( ??? zend_name, ??? name, ??? arg_info )

...

Parameters

zend_name

...

name

...

arg_info

...

Return Values

...

Prev | Home | Next
ZEND_MODULE_STARTUP_N | Up | ZEND_NAMED_FUNCTION


ZEND_NAMED_FUNCTION

ZEND_NAMED_FUNCTION -- ...

Description

#include <zend_API.h>

??? ZEND_NAMED_FUNCTION ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_NAMED_FE | Up | ZEND_NORMALIZE_BOOL


ZEND_NORMALIZE_BOOL

ZEND_NORMALIZE_BOOL -- ...

Description

#include <zend.h>

??? ZEND_NORMALIZE_BOOL ( ??? n )

...

Parameters

n

...

Return Values

...

Prev | Home | Next
ZEND_NAMED_FUNCTION | Up | ZEND_NUM_ARGS


ZEND_NUM_ARGS

ZEND_NUM_ARGS -- ...

Description

#include <zend_API.h>

int ZEND_NUM_ARGS ( void )

ZEND_NUM_ARGS() returns the number of arguments that have been passed by the caller of the current PHP function.

Return Values

Number of arguments passed to the current PHP function.

Prev | Home | Next
ZEND_NORMALIZE_BOOL | Up | ZEND_PUTC


ZEND_PUTC

ZEND_PUTC -- Write a single character to the default output stream

Description

#include <zend.h>

int ZEND_PUTC ( char c )

Writes a single character c to the default output stream.

Parameters

c

Output character

Return Values

Number of characters written or -1 on errors.

See Also

See also ZEND_PUTS() and ZEND_WRITE().

Prev | Home | Next
ZEND_NUM_ARGS | Up | ZEND_PUTS


ZEND_PUTS

ZEND_PUTS -- Write a string to the default output stream

Description

#include <zend.h>

int ZEND_PUTS ( char * str )

Writes the zero terminated string str to the default output stream.

Parameters

str

Output string

Return Values

Number of characters written or -1 on errors.

See Also

See also ZEND_PUTC() and ZEND_WRITE().

Prev | Home | Next
ZEND_PUTC | Up | ZEND_REGISTER_RESOURCE


ZEND_REGISTER_RESOURCE

ZEND_REGISTER_RESOURCE -- ...

Description

#include <zend_list.h>

??? ZEND_REGISTER_RESOURCE ( ??? rsrc_result, ??? rsrc_pointer, ??? rsrc_type )

...

Parameters

rsrc_result

...

rsrc_pointer

...

rsrc_type

...

Return Values

...

Prev | Home | Next
ZEND_PUTS | Up | ZEND_RSRC_DTOR_FUNC


ZEND_RSRC_DTOR_FUNC

ZEND_RSRC_DTOR_FUNC -- ...

Description

#include <zend_list.h>

??? ZEND_RSRC_DTOR_FUNC ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_REGISTER_RESOURCE | Up | ZEND_SET_GLOBAL_VAR_WITH_LENGTH


ZEND_SET_GLOBAL_VAR

ZEND_SET_GLOBAL_VAR -- ...

Description

#include <zend_API.h>

??? ZEND_SET_GLOBAL_VAR ( ??? name, ??? var )

...

Parameters

name

...

var

...

Return Values

...

Prev | Home | Next
ZEND_SET_GLOBAL_VAR_WITH_LENGTH | Up | ZEND_SET_SYMBOL_WITH_LENGTH


ZEND_SET_GLOBAL_VAR_WITH_LENGTH

ZEND_SET_GLOBAL_VAR_WITH_LENGTH -- ...

Description

#include <zend_API.h>

??? ZEND_SET_GLOBAL_VAR_WITH_LENGTH ( ??? name, ??? name_length, ??? var, ??? _refcount, ??? _is_ref )

...

Parameters

name

...

name_length

...

var

...

_refcount

...

_is_ref

...

Return Values

...

Prev | Home | Next
ZEND_RSRC_DTOR_FUNC | Up | ZEND_SET_GLOBAL_VAR


ZEND_SET_SYMBOL

ZEND_SET_SYMBOL -- ...

Description

#include <zend_API.h>

??? ZEND_SET_SYMBOL ( ??? symtable, ??? name, ??? var )

...

Parameters

symtable

...

name

...

var

...

Return Values

...

Prev | Home | Next
ZEND_SET_SYMBOL_WITH_LENGTH | Up | ZEND_STRL


ZEND_SET_SYMBOL_WITH_LENGTH

ZEND_SET_SYMBOL_WITH_LENGTH -- ...

Description

#include <zend_API.h>

??? ZEND_SET_SYMBOL_WITH_LENGTH ( ??? symtable, ??? name, ??? name_length, ??? var, ??? _refcount, ??? _is_ref )

...

Parameters

symtable

...

name

...

name_length

...

var

...

_refcount

...

_is_ref

...

Return Values

...

Prev | Home | Next
ZEND_SET_GLOBAL_VAR | Up | ZEND_SET_SYMBOL


ZEND_STRL

ZEND_STRL -- Pass string pointer and length in one operation

Description

#include <zend.h>

void ZEND_STRL ( char * str )

This is a convenience macro that can be used when passing a static string to a function that requires a string length argument together with a string. This saves duplicating the static string in the sourcecode or adding an extra variable for it.

Example 46-1. ZEND_STRL() example

write(0, ZEND_STRL("Hello World!"));
/* same as
char str[] = "Hello World!";
write(0, str, sizeof(str)-1);
*/

Parameters

str

Pointer to a zero terminated string.

Prev | Home | Next
ZEND_SET_SYMBOL | Up | ZEND_STRS


ZEND_STRS

ZEND_STRS -- Pass string pointer and buffer size in one operation

Description

#include <zend.h>

void ZEND_STRS ( char * str )

This is a convenience macro that can be used when passing a static string to a function that requires a buffer length argument together with a string. This saves duplicating the static string in the sourcecode or adding an extra variable for it.

Parameters

str

...

Return Values

...

Prev | Home | Next
ZEND_STRL | Up | ZEND_TRUTH


ZEND_TRUTH

ZEND_TRUTH -- Cast a value to zend_bool

Description

#include <zend.h>

zend_bool ZEND_TRUTH ( mixed x )

A simple conversion macro, actually defined as ((x) ? 1 : 0)

Parameters

x

Value to cast

Return Values

1 if x was considered TRUE, else 0

Prev | Home | Next
ZEND_STRS | Up | ZEND_U_CONVERTER


ZEND_U_CONVERTER

ZEND_U_CONVERTER -- ...

Description

#include <zend_unicode.h>

??? ZEND_U_CONVERTER ( ??? c )

...

Parameters

c

...

Return Values

...

Prev | Home | Next
ZEND_TRUTH | Up | ZEND_U_EQUAL


ZEND_U_EQUAL

ZEND_U_EQUAL -- ...

Description

#include <zend.h>

??? ZEND_U_EQUAL ( ??? type, ??? ustr, ??? ulen, ??? str, ??? slen )

...

Parameters

type

...

ustr

...

ulen

...

str

...

slen

...

Return Values

...

Prev | Home | Next
ZEND_U_CONVERTER | Up | ZEND_U_SET_SYMBOL_WITH_LENGTH


ZEND_U_SET_SYMBOL_WITH_LENGTH

ZEND_U_SET_SYMBOL_WITH_LENGTH -- ...

Description

#include <zend_API.h>

??? ZEND_U_SET_SYMBOL_WITH_LENGTH ( ??? symtable, ??? type, ??? name, ??? name_length, ??? var, ??? _refcount, ??? _is_ref )

...

Parameters

symtable

...

type

...

name

...

name_length

...

var

...

_refcount

...

_is_ref

...

Return Values

...

Prev | Home | Next
ZEND_U_EQUAL | Up | ZEND_UV


ZEND_UV

ZEND_UV -- ...

Description

#include <zend.h>

??? ZEND_UV ( ??? name )

...

Parameters

name

...

Return Values

...

Prev | Home | Next
ZEND_U_SET_SYMBOL_WITH_LENGTH | Up | ZEND_VERIFY_RESOURCE


ZEND_VERIFY_RESOURCE

ZEND_VERIFY_RESOURCE -- ...

Description

#include <zend_list.h>

??? ZEND_VERIFY_RESOURCE ( ??? rsrc )

...

Parameters

rsrc

...

Return Values

...

Prev | Home | Next
ZEND_UV | Up | ZEND_WRITE


ZEND_WRITE

ZEND_WRITE -- Write character buffer to the default output stream

Description

#include <zend.h>

int ZEND_WRITE ( char * str, int str_len )

Write str_len bytes from the buffer pointed to by str to the default output stream.

Parameters

str

Pointer to character buffer

str_len

Buffer length

Return Values

Number of characters written or -1 on errors.

See Also

See also ZEND_PUTC() and ZEND_PUTS().

Prev | Home | Next
ZEND_VERIFY_RESOURCE | Up | ZEND_WRONG_PARAM_COUNT_WITH_RETVAL


ZEND_WRONG_PARAM_COUNT

ZEND_WRONG_PARAM_COUNT -- ...

Description

#include <zend_API.h>

??? ZEND_WRONG_PARAM_COUNT ( ??? )

...

Parameters

...

Return Values

...

Prev | Home | Next
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL | Up | TSRM API


API Function and Macro reference (work in progress)

Table of Contents
add_assoc_bool_ex -- Add a bool value to an assoc array with binary safe key
add_assoc_bool -- Add a bool value to an assoc array
add_assoc_double_ex -- Add a double value to an assoc array with binary safe key
add_assoc_double -- Add a double value to an assoc array
add_assoc_function -- Add a function pointer to an assoc array
add_assoc_long_ex -- Add a long value to an assoc array with binary safe key
add_assoc_long -- Add a long value to an assoc array
add_assoc_null_ex -- Add a null value to an assoc array with binary safe key
add_assoc_null -- Add a null value to an assoc array
add_assoc_resource_ex -- Add a resource value to an assoc array with binary safe key
add_assoc_resource -- Add a resource value to an assoc array
add_assoc_string_ex -- Add a string value to an assoc array with binary safe key
add_assoc_string -- Add a string value to an assoc array
add_assoc_stringl_ex -- Add a binary safe string value to an assoc array with binary safe key
add_assoc_stringl -- Add a binary safe string value to an assoc array
add_assoc_unicode_ex -- Add a unicode_string value to an assoc array with binary safe key
add_assoc_unicode -- Add a binary safe unicode_string value to an assoc array with binary safe key
add_assoc_unicodel_ex -- Add a binary safe unicode_string value to an assoc array with binary safe key
add_assoc_unicodel -- Add a binary safe unicode_string value to an assoc array
add_assoc_unset -- ...
add_assoc_zval_ex -- Add a zval value to an assoc array with binary safe key
add_assoc_zval -- Add a zval value to an assoc array
add_get_assoc_string_ex -- ...
add_get_assoc_string -- ...
add_get_assoc_stringl_ex -- ...
add_get_assoc_stringl -- ...
add_get_index_binary -- ...
add_get_index_binaryl -- ...
add_get_index_double -- ...
add_get_index_long -- ...
add_get_index_string -- ...
add_get_index_stringl -- ...
add_get_index_unicode -- ...
add_get_index_unicodel -- ...
add_index_binary -- Add binary_string value to assoc array using numeric index
add_index_binaryl -- Add binary safe binary_string value to assoc array using numeric index
add_index_bool -- Add bool value to assoc array using numeric index
add_index_double -- Add double value to assoc array using numeric index
add_index_long -- Add long value to assoc array using numeric index
add_index_null -- Add null value to assoc array using numeric index
add_index_resource -- Add resource value to assoc array using numeric index
add_index_string -- Add string value to assoc array using numeric index
add_index_stringl -- Add binary safe string value to assoc array using numeric index
add_index_unicode -- Add unicode value to assoc array using numeric index
add_index_unicodel -- Add binary safe unicode value to assoc array using numeric index
add_index_unset -- Add unset value to assoc array using numeric index
add_index_zval -- Add zval value to assoc array using numeric index
add_method -- ...
add_next_index_binary -- Add binary_string value to assoc array using next free numeric index
add_next_index_binaryl -- Add binary safe binary_string value to assoc array using next free numeric index
add_next_index_bool -- Add bool value to assoc array using next free numeric index
add_next_index_double -- Add double value to assoc array using next free numeric index
add_next_index_long -- Add long value to assoc array using next free numeric index
add_next_index_null -- Add null value to assoc array using next free numeric index
add_next_index_resource -- Add resource value to assoc array using next free numeric index
add_next_index_string -- Add string value to assoc array using next free numeric index
add_next_index_stringl -- Add binary safe string value to assoc array using next free numeric index
add_next_index_unicode -- Add unicode value to assoc array using next free numeric index
add_next_index_unicodel -- Add binary safe unicode value to assoc array using next free numeric index
add_next_index_unset -- Add unset value to assoc array using next free numeric index
add_next_index_zval -- Add zval value to assoc array using next free numeric index
add_property_ascii_string_ex -- ...
add_property_ascii_string -- ...
add_property_ascii_stringl_ex -- ...
add_property_ascii_stringl -- ...
add_property_bool_ex -- ...
add_property_bool -- ...
add_property_double_ex -- ...
add_property_double -- ...
add_property_long_ex -- ...
add_property_long -- ...
add_property_null_ex -- ...
add_property_null -- ...
add_property_resource_ex -- ...
add_property_resource -- ...
add_property_rt_string_ex -- ...
add_property_rt_string -- ...
add_property_rt_stringl_ex -- ...
add_property_rt_stringl -- ...
add_property_string_ex -- ...
add_property_string -- ...
add_property_stringl_ex -- ...
add_property_stringl -- ...
add_property_unicode_ex -- ...
add_property_unicode -- ...
add_property_unicodel_ex -- ...
add_property_unicodel -- ...
add_property_unset -- ...
add_property_zval_ex -- ...
add_property_zval -- ...
add_u_assoc_zval_ex -- ...
add_u_assoc_zval -- ...
array_init -- ...
call_user_function_ex -- ...
call_user_function -- ...
compile_file -- ...
compile_filename -- ...
compile_string -- ...
destroy_op_array -- ...
destroy_zend_class -- ...
destroy_zend_function -- ...
display_ini_entries -- ...
do_bind_class -- ...
do_bind_function -- ...
do_bind_inherited_class -- ...
estrndup_rel -- ...
estrndup -- ...
eustrdup -- ...
eustrndup_rel -- ...
eustrndup -- ...
execute_internal -- ...
execute -- ...
free_estring -- ...
full_mem_check -- ...
function_add_ref -- ...
get_active_class_name -- ...
get_active_function_name -- ...
get_binary_op -- ...
get_unary_op -- ...
get_zend_version -- Get Zend Engine version string
highlight_file -- ...
highlight_string -- ...
init_op_array -- ...
lex_scan -- ...
mem_block_check -- ...
object_and_properties_init -- ...
object_init_ex -- ...
object_init -- ...
open_file_for_scanning -- ...
register_list_destructors -- ...
shutdown_memory_manager -- ...
start_memory_manager -- ...
zend_alter_ini_entry -- ...
zend_auto_global_disable_jit -- ...
zend_bailout -- ...
zend_call_function -- ...
zend_call_method_with_0_params -- ...
zend_call_method_with_1_params -- ...
zend_call_method_with_2_params -- ...
zend_call_method -- ...
zend_case_fold_string -- ...
zend_check_magic_method_implementation -- ...
zend_check_private -- ...
zend_check_property_access -- ...
zend_check_protected -- ...
zend_class_implements -- ...
zend_cleanup_class_data -- ...
zend_cleanup_function_data -- ...
zend_clear_exception -- ...
zend_cmp_unicode_and_literal -- ...
zend_cmp_unicode_and_string -- ...
zend_convert_encodings -- ...
zend_convert_from_unicode -- ...
zend_convert_scanner_output -- ...
zend_convert_to_unicode -- ...
zend_copy_ini_directives -- ...
zend_copy_parameters_array -- ...
zend_declare_class_constant_bool -- ...
zend_declare_class_constant_double -- ...
zend_declare_class_constant_long -- ...
zend_declare_class_constant_string -- ...
zend_declare_class_constant_stringl -- ...
zend_declare_class_constant -- ...
zend_declare_property_bool -- ...
zend_declare_property_double -- ...
zend_declare_property_ex -- ...
zend_declare_property_long -- ...
zend_declare_property_null -- ...
zend_declare_property_string -- ...
zend_declare_property_stringl -- ...
zend_declare_property -- ...
zend_delete_global_variable -- ...
zend_destroy_file_handle -- ...
zend_disable_class -- ...
zend_disable_function -- ...
zend_do_fcall -- ...
zend_do_implement_interface -- ...
zend_do_inherit_interfaces -- ...
zend_do_inheritance -- ...
zend_error -- Generate error message and trigger error handling
zend_eval_string_ex -- ...
zend_eval_string -- ...
zend_exception_error -- ...
zend_exception_get_default -- ...
zend_execute_scripts -- ...
zend_fetch_class -- ...
zend_fetch_debug_backtrace -- ...
zend_fetch_list_dtor_id -- ...
zend_fetch_resource -- ...
zend_file_handle_dtor -- ...
zend_function_dtor -- ...
zend_get_class_entry -- ...
zend_get_compiled_filename -- ...
zend_get_compiled_lineno -- ...
zend_get_compiled_script_encoding -- ...
zend_get_compiled_variable_name -- ...
zend_get_compiled_variable_value -- ...
zend_get_configuration_directive -- ...
zend_get_constant -- ...
zend_get_error_exception -- ...
zend_get_executed_filename -- ...
zend_get_executed_lineno -- ...
zend_get_hash_value -- ...
zend_get_module_started -- ...
zend_get_module_version -- ...
zend_get_object_classname -- ...
zend_get_parameters_array_ex -- ...
zend_get_parameters_array -- ...
zend_get_parameters_ex -- ...
zend_get_parameters -- ...
zend_get_scanned_file_offset -- ...
zend_get_std_object_handlers -- ...
zend_get_unified_string_type -- ...
zend_get_user_opcode_handler -- ...
zend_get_zval_ptr_ptr -- ...
zend_get_zval_ptr -- ...
zend_hash_add_empty_element -- ...
zend_hash_add -- ...
zend_hash_apply_with_argument -- ...
zend_hash_apply_with_arguments -- ...
zend_hash_apply -- ...
zend_hash_clean -- ...
zend_hash_compare -- ...
zend_hash_copy -- ...
zend_hash_del_key_or_index -- ...
zend_hash_del -- ...
zend_hash_destroy -- ...
zend_hash_exists -- ...
zend_hash_find -- ...
zend_hash_func -- ...
zend_hash_get_current_data_ex -- ...
zend_hash_get_current_data -- ...
zend_hash_get_current_key_ex -- ...
zend_hash_get_current_key_type_ex -- ...
zend_hash_get_current_key_type -- ...
zend_hash_get_current_key -- ...
zend_hash_graceful_destroy -- ...
zend_hash_graceful_reverse_destroy -- ...
zend_hash_index_del -- ...
zend_hash_index_exists -- ...
zend_hash_index_find -- ...
zend_hash_index_update -- ...
zend_hash_init_ex -- ...
zend_hash_init -- ...
zend_hash_internal_pointer_end_ex -- ...
zend_hash_internal_pointer_end -- ...
zend_hash_internal_pointer_reset_ex -- ...
zend_hash_internal_pointer_reset -- ...
zend_hash_merge_ex -- ...
zend_hash_merge -- ...
zend_hash_minmax -- ...
zend_hash_move_backwards_ex -- ...
zend_hash_move_backwards -- ...
zend_hash_move_forward_ex -- ...
zend_hash_move_forward -- ...
zend_hash_next_free_element -- ...
zend_hash_next_index_insert -- ...
zend_hash_num_elements -- ...
zend_hash_quick_add -- ...
zend_hash_quick_exists -- ...
zend_hash_quick_find -- ...
zend_hash_quick_update -- ...
zend_hash_rehash -- ...
zend_hash_reverse_apply -- ...
zend_hash_sort -- ...
zend_hash_update_current_key_ex -- ...
zend_hash_update_current_key -- ...
zend_hash_update -- ...
zend_highlight -- ...
zend_html_putc -- ...
zend_html_puts -- ...
zend_ini_deactivate -- ...
zend_ini_double -- ...
zend_ini_global_shutdown -- ...
zend_ini_long -- ...
zend_ini_refresh_caches -- ...
zend_ini_register_displayer -- ...
zend_ini_shutdown -- ...
zend_ini_sort_entries -- ...
zend_ini_startup -- ...
zend_ini_string -- ...
zend_initialize_class_data -- ...
zend_is_auto_global -- ...
zend_is_callable_ex -- ...
zend_is_callable -- ...
zend_is_compiling -- ...
zend_is_executing -- ...
zend_is_true -- ...
zend_is_valid_identifier -- ...
zend_list_addref -- ...
zend_list_delete -- ...
zend_list_find -- ...
zend_list_insert -- ...
zend_lookup_class -- ...
zend_make_callable -- ...
zend_make_compiled_string_description -- ...
zend_make_printable_zval -- ...
zend_make_string_zval -- ...
zend_make_unicode_zval -- ...
zend_mangle_property_name -- ...
zend_merge_properties -- ...
zend_message_dispatcher -- ...
zend_normalize_identifier -- ...
zend_object_create_proxy -- ...
zend_object_store_ctor_failed -- ...
zend_object_store_get_object -- ...
zend_object_store_set_object -- ...
zend_objects_clone_members -- ...
zend_objects_clone_obj -- ...
zend_objects_destroy_object -- ...
zend_objects_free_object_storage -- ...
zend_objects_get_address -- ...
zend_objects_new -- ...
zend_objects_store_add_ref -- ...
zend_objects_store_call_destructors -- ...
zend_objects_store_clone_obj -- ...
zend_objects_store_del_ref -- ...
zend_objects_store_destroy -- ...
zend_objects_store_free_object_storage -- ...
zend_objects_store_init -- ...
zend_objects_store_mark_destructed -- ...
zend_objects_store_put -- ...
zend_output_debug_string -- ...
zend_parse_ini_file -- ...
zend_parse_method_parameters_ex -- ...
zend_parse_method_parameters -- ...
zend_parse_parameters_ex -- ...
zend_parse_parameters -- ...
zend_prepare_scanner_converters -- ...
zend_print_flat_zval_r -- ...
zend_print_variable -- ...
zend_print_zval_ex -- ...
zend_print_zval_r_ex -- ...
zend_print_zval_r -- ...
zend_print_zval -- ...
zend_qsort -- ...
zend_read_property -- ...
zend_read_static_property -- ...
zend_register_auto_global -- ...
zend_register_constant -- ...
zend_register_default_classes -- ...
zend_register_double_constant -- ...
zend_register_functions -- ...
zend_register_ini_entries -- ...
zend_register_interfaces -- ...
zend_register_internal_class_ex -- ...
zend_register_internal_class -- ...
zend_register_internal_interface -- ...
zend_register_internal_module -- ...
zend_register_list_destructors_ex -- ...
zend_register_list_destructors -- ...
zend_register_long_constant -- ...
zend_register_module_ex -- ...
zend_register_module -- ...
zend_register_resource -- ...
zend_register_string_constant -- ...
zend_register_stringl_constant -- ...
zend_reset_all_cv -- ...
zend_reset_locale_deps -- ...
zend_restore_compiled_filename -- ...
zend_restore_compiled_script_encoding -- ...
zend_restore_ini_entry -- ...
zend_rsrc_list_get_rsrc_type -- ...
zend_set_compiled_filename -- ...
zend_set_compiled_script_encoding -- ...
zend_set_memory_limit -- ...
zend_set_timeout -- ...
zend_set_user_opcode_handler -- ...
zend_startup_module_ex -- ...
zend_startup_module -- ...
zend_startup_modules -- ...
zend_std_call_user_call -- ...
zend_std_cast_object_tostring -- ...
zend_std_get_static_property -- ...
zend_std_unset_static_property -- ...
zend_stream_close -- ...
zend_stream_ferror -- ...
zend_stream_fixup -- ...
zend_stream_ftell -- ...
zend_stream_getc -- ...
zend_stream_open -- ...
zend_stream_read -- ...
zend_strip -- ...
zend_strndup -- ...
zend_strtod -- ...
zend_symtable_del -- ...
zend_symtable_exists -- ...
zend_symtable_find -- ...
zend_symtable_update_current_key -- ...
zend_symtable_update -- ...
zend_throw_exception_object -- ...
zend_timeout -- ...
zend_u_declare_property_ex -- ...
zend_u_declare_property -- ...
zend_u_delete_global_variable -- ...
zend_u_eval_string_ex -- ...
zend_u_eval_string -- ...
zend_u_fetch_class -- ...
zend_u_get_constant -- ...
zend_u_get_hash_value -- ...
zend_u_hash_add_empty_element -- ...
zend_u_hash_add -- ...
zend_u_hash_del_key_or_index -- ...
zend_u_hash_del -- ...
zend_u_hash_exists -- ...
zend_u_hash_find -- ...
zend_u_hash_func -- ...
zend_u_hash_init_ex -- ...
zend_u_hash_init -- ...
zend_u_hash_quick_add -- ...
zend_u_hash_quick_exists -- ...
zend_u_hash_quick_find -- ...
zend_u_hash_quick_update -- ...
zend_u_hash_update -- ...
zend_u_is_auto_global -- ...
zend_u_lookup_class_ex -- ...
zend_u_lookup_class -- ...
zend_u_mangle_property_name -- ...
zend_u_register_constant -- ...
zend_u_symtable_del -- ...
zend_u_symtable_exists -- ...
zend_u_symtable_find -- ...
zend_u_symtable_update_current_key -- ...
zend_u_symtable_update -- ...
zend_u_unmangle_property_name -- ...
zend_unmangle_property_name -- ...
zend_unregister_functions -- ...
zend_unregister_ini_entries -- ...
zend_unset_timeout -- ...
zend_update_class_constants -- ...
zend_update_property_ascii_string -- ...
zend_update_property_ascii_stringl -- ...
zend_update_property_bool -- ...
zend_update_property_double -- ...
zend_update_property_long -- ...
zend_update_property_null -- ...
zend_update_property_rt_string -- ...
zend_update_property_rt_stringl -- ...
zend_update_property_string -- ...
zend_update_property_stringl -- ...
zend_update_property_unicode -- ...
zend_update_property_unicodel -- ...
zend_update_property -- ...
zend_update_static_property_ascii_string -- ...
zend_update_static_property_ascii_stringl -- ...
zend_update_static_property_bool -- ...
zend_update_static_property_double -- ...
zend_update_static_property_long -- ...
zend_update_static_property_null -- ...
zend_update_static_property_rt_string -- ...
zend_update_static_property_rt_stringl -- ...
zend_update_static_property_string -- ...
zend_update_static_property_stringl -- ...
zend_update_static_property_unicode -- ...
zend_update_static_property_unicodel -- ...
zend_update_static_property -- ...
zend_ustrndup -- ...
zend_wrong_param_count -- Generate standard error message for wrong parameter count in function or method call
zend_zval_type_name -- Returns the PHP type name for a given zval
zval_add_ref -- ...
zval_internal_dtor -- ...
zval_internal_ptr_dtor -- ...
zval_ptr_dtor -- ...
zval_string_to_unicode_ex -- ...
zval_string_to_unicode -- ...
zval_unicode_to_string -- ...
zval_update_constant -- ...
DISPLAY_INI_ENTRIES -- ...
INI_BOOL -- ...
INI_FLT -- ...
INI_INT -- ...
INI_ORIG_BOOL -- ...
INI_ORIG_FLT -- ...
INI_ORIG_INT -- ...
INI_ORIG_STR -- ...
INI_STR -- ...
REGISTER_DOUBLE_CONSTANT -- ...
REGISTER_INI_BOOLEAN -- ...
REGISTER_INI_DISPLAYER -- ...
REGISTER_INI_ENTRIES -- ...
REGISTER_LONG_CONSTANT -- ...
REGISTER_MAIN_DOUBLE_CONSTANT -- ...
REGISTER_MAIN_LONG_CONSTANT -- ...
REGISTER_MAIN_STRING_CONSTANT -- ...
REGISTER_MAIN_STRINGL_CONSTANT -- ...
REGISTER_STRING_CONSTANT -- ...
REGISTER_STRINGL_CONSTANT -- ...
RETURN_ASCII_STRING -- ...
RETURN_ASCII_STRINGL -- ...
RETURN_BINARY -- ...
RETURN_BINARYL -- ...
RETURN_BOOL -- Return a bool value from a function
RETURN_DOUBLE -- Return a double value from a function
RETURN_EMPTY_BINARY -- ...
RETURN_EMPTY_STRING -- Return an empty string value from a function
RETURN_EMPTY_UNICODE -- ...
RETURN_LONG -- Return a long value from a function
RETURN_NULL -- Return a null value from a function
RETURN_RESOURCE -- Return a resource from a function
RETURN_RT_STRING -- ...
RETURN_RT_STRINGL -- ...
RETURN_STRING -- ...
RETURN_STRINGL -- ...
RETURN_TEXT -- ...
RETURN_TEXTL -- ...
RETURN_U_STRING -- ...
RETURN_U_STRINGL -- ...
RETURN_UNICODE -- ...
RETURN_UNICODEL -- ...
RETURN_ZVAL -- Return a zval value from a function
UNREGISTER_INI_ENTRIES -- ...
Z_ARRVAL_P -- ...
Z_ARRVAL_PP -- ...
Z_ARRVAL -- ...
Z_BINLEN_P -- ...
Z_BINLEN_PP -- ...
Z_BINLEN -- ...
Z_BINVAL_P -- ...
Z_BINVAL_PP -- ...
Z_BINVAL -- ...
Z_BVAL_P -- Dereference a zval pointer and return its lval element as bool
Z_BVAL_PP -- Dereference a pointer to a zval pointer and return its lval element as bool
Z_BVAL -- Return a zval lval element as bool
Z_DBG -- ...
Z_DVAL_P -- Dereference a zval pointer and return its dval element
Z_DVAL_PP -- Dereference a pointer to a zval pointer and return its dval element
Z_DVAL -- Return the dval element of a zval
Z_LVAL_P -- ...
Z_LVAL_PP -- Dereference a pointer to a zval pointer and return its lval element
Z_LVAL -- ...
Z_OBJ_CLASS_NAME_P -- ...
Z_OBJ_HANDLE_P -- ...
Z_OBJ_HANDLE_PP -- ...
Z_OBJ_HANDLE -- ...
Z_OBJ_HANDLER_P -- ...
Z_OBJ_HANDLER_PP -- ...
Z_OBJ_HANDLER -- ...
Z_OBJ_HT_P -- ...
Z_OBJ_HT_PP -- ...
Z_OBJ_HT -- ...
Z_OBJCE_P -- ...
Z_OBJCE_PP -- ...
Z_OBJCE -- ...
Z_OBJPROP_P -- ...
Z_OBJPROP_PP -- ...
Z_OBJPROP -- ...
Z_OBJVAL_P -- ...
Z_OBJVAL_PP -- ...
Z_OBJVAL -- ...
Z_RESVAL_P -- ...
Z_RESVAL_PP -- ...
Z_RESVAL -- ...
Z_STRLEN_P -- ...
Z_STRLEN_PP -- ...
Z_STRLEN -- ...
Z_STRVAL_P -- ...
Z_STRVAL_PP -- ...
Z_STRVAL -- ...
Z_TYPE_P -- Get type field from zval pointer
Z_TYPE_PP -- Get type field from zval pointer pointer
Z_TYPE -- Get the type field of a zval
Z_UNILEN_P -- ...
Z_UNILEN_PP -- ...
Z_UNILEN -- ...
Z_UNIVAL_P -- ...
Z_UNIVAL_PP -- ...
Z_UNIVAL -- ...
Z_USTRCPLEN_P -- ...
Z_USTRCPLEN_PP -- ...
Z_USTRCPLEN -- ...
Z_USTRLEN_P -- ...
Z_USTRLEN_PP -- ...
Z_USTRLEN -- ...
Z_USTRVAL_P -- ...
Z_USTRVAL_PP -- ...
Z_USTRVAL -- ...
ZEND_ABSTRACT_ME -- ...
ZEND_ARG_ARRAY_INFO -- ...
ZEND_ARG_INFO -- ...
ZEND_ARG_OBJ_INFO -- ...
ZEND_ARG_PASS_INFO -- ...
ZEND_BEGIN_ARG_INFO_EX -- ...
ZEND_BEGIN_ARG_INFO -- ...
ZEND_BEGIN_MODULE_GLOBALS -- ...
ZEND_COLL_RESULT -- ...
ZEND_DECLARE_MODULE_GLOBALS -- ...
ZEND_DEFINE_PROPERTY -- ...
ZEND_END_ARG_INFO -- ...
ZEND_END_MODULE_GLOBALS -- ...
ZEND_EXTERN_MODULE_GLOBALS -- ...
ZEND_FALIAS -- ...
ZEND_FE -- ...
ZEND_FENTRY -- ...
ZEND_FETCH_RESOURCE2 -- ...
ZEND_FETCH_RESOURCE -- ...
ZEND_FN_SCOPE_NAME -- ...
ZEND_FN -- ...
ZEND_FUNCTION -- ...
ZEND_GET_MODULE -- ...
ZEND_GET_RESOURCE_TYPE_ID -- ...
ZEND_INI_BEGIN -- ...
ZEND_INI_DISP -- ...
ZEND_INI_END -- ...
ZEND_INI_ENTRY_EX -- ...
ZEND_INI_ENTRY1_EX -- ...
ZEND_INI_ENTRY1 -- ...
ZEND_INI_ENTRY2_EX -- ...
ZEND_INI_ENTRY2 -- ...
ZEND_INI_ENTRY3_EX -- ...
ZEND_INI_ENTRY3 -- ...
ZEND_INI_ENTRY -- ...
ZEND_INI_MH -- ...
ZEND_INIT_MODULE_GLOBALS -- ...
ZEND_INIT_SYMTABLE_EX -- ...
ZEND_INIT_SYMTABLE -- ...
ZEND_LOG_XOR -- ...
ZEND_MALIAS -- ...
ZEND_ME_MAPPING -- ...
ZEND_ME -- ...
ZEND_METHOD -- ...
ZEND_MOD_CONFLICTS_EX -- ...
ZEND_MOD_CONFLICTS -- ...
ZEND_MOD_OPTIONAL_EX -- ...
ZEND_MOD_OPTIONAL -- ...
ZEND_MOD_REQUIRED_EX -- Create a full dependency entry for the required version of an extension
ZEND_MOD_REQUIRED -- Create a simple dependency entry for a required extension
ZEND_MODULE_ACTIVATE_D -- ...
ZEND_MODULE_ACTIVATE_N -- ...
ZEND_MODULE_DEACTIVATE_D -- ...
ZEND_MODULE_DEACTIVATE_N -- ...
ZEND_MODULE_INFO_D -- ...
ZEND_MODULE_INFO_N -- ...
ZEND_MODULE_POST_ZEND_DEACTIVATE_D -- ...
ZEND_MODULE_POST_ZEND_DEACTIVATE_N -- ...
ZEND_MODULE_SHUTDOWN_D -- ...
ZEND_MODULE_SHUTDOWN_N -- ...
ZEND_MODULE_STARTUP_D -- ...
ZEND_MODULE_STARTUP_N -- ...
ZEND_NAMED_FE -- ...
ZEND_NAMED_FUNCTION -- ...
ZEND_NORMALIZE_BOOL -- ...
ZEND_NUM_ARGS -- ...
ZEND_PUTC -- Write a single character to the default output stream
ZEND_PUTS -- Write a string to the default output stream
ZEND_REGISTER_RESOURCE -- ...
ZEND_RSRC_DTOR_FUNC -- ...
ZEND_SET_GLOBAL_VAR_WITH_LENGTH -- ...
ZEND_SET_GLOBAL_VAR -- ...
ZEND_SET_SYMBOL_WITH_LENGTH -- ...
ZEND_SET_SYMBOL -- ...
ZEND_STRL -- Pass string pointer and length in one operation
ZEND_STRS -- Pass string pointer and buffer size in one operation
ZEND_TRUTH -- Cast a value to zend_bool
ZEND_U_CONVERTER -- ...
ZEND_U_EQUAL -- ...
ZEND_U_SET_SYMBOL_WITH_LENGTH -- ...
ZEND_UV -- ...
ZEND_VERIFY_RESOURCE -- ...
ZEND_WRITE -- Write character buffer to the default output stream
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL -- Generate standard error message and return custom value
ZEND_WRONG_PARAM_COUNT -- ...

Prev | Home | Next
API Macros | Up | add_assoc_bool_ex